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.

BaseSession.cs 18 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 NumSharp;
  14. using System;
  15. using System.Collections;
  16. using System.Collections.Generic;
  17. using System.Linq;
  18. using System.Numerics;
  19. using System.Text;
  20. namespace Tensorflow
  21. {
  22. public class BaseSession : DisposableObject
  23. {
  24. protected Graph _graph;
  25. protected bool _opened;
  26. protected bool _closed;
  27. protected int _current_version;
  28. protected byte[] _target;
  29. protected IntPtr _session;
  30. public Graph graph => _graph;
  31. public BaseSession(string target = "", Graph g = null, SessionOptions opts = null)
  32. {
  33. _graph = g is null ? ops.get_default_graph() : g;
  34. _graph.as_default();
  35. _target = UTF8Encoding.UTF8.GetBytes(target);
  36. SessionOptions newOpts = null;
  37. if (opts == null)
  38. newOpts = new SessionOptions();
  39. var status = new Status();
  40. _session = c_api.TF_NewSession(_graph, opts ?? newOpts, status);
  41. status.Check(true);
  42. }
  43. public virtual NDArray run(object fetches, params FeedItem[] feed_dict)
  44. {
  45. return _run(fetches, feed_dict);
  46. }
  47. public virtual NDArray run(object fetches, Hashtable feed_dict = null)
  48. {
  49. var feed_items = feed_dict == null ? new FeedItem[0] :
  50. feed_dict.Keys.OfType<object>().Select(key => new FeedItem(key, feed_dict[key])).ToArray();
  51. return _run(fetches, feed_items);
  52. }
  53. private NDArray _run(object fetches, FeedItem[] feed_dict = null)
  54. {
  55. var feed_dict_tensor = new Dictionary<object, object>();
  56. var feed_map = new Dictionary<object, object>();
  57. Func<FeedItem, IEnumerable<(object, object)>> feed_fn = (item) =>
  58. {
  59. return new (object, object)[] { (item.Key, item.Value) };
  60. };
  61. // Validate and process feed_dict.
  62. if (feed_dict != null)
  63. {
  64. foreach (var feed in feed_dict)
  65. {
  66. foreach (var (subfeed, subfeed_val) in feed_fn(feed))
  67. {
  68. var subfeed_t = _graph.as_graph_element(subfeed, allow_tensor: true, allow_operation: false);
  69. //var subfeed_dtype = subfeed_t.dtype.as_numpy_datatype(); // subfeed_dtype was never used
  70. feed_dict_tensor[subfeed_t] = subfeed_val;
  71. feed_map[subfeed_t.name] = (subfeed_t, subfeed_val);
  72. }
  73. }
  74. }
  75. // Create a fetch handler to take care of the structure of fetches.
  76. var fetch_handler = new _FetchHandler(_graph, fetches, feed_dict_tensor);
  77. // Run request and get response.
  78. // We need to keep the returned movers alive for the following _do_run().
  79. // These movers are no longer needed when _do_run() completes, and
  80. // are deleted when `movers` goes out of scope when this _run() ends.
  81. var _ = _update_with_movers();
  82. var final_fetches = fetch_handler.fetches();
  83. var final_targets = fetch_handler.targets();
  84. // We only want to really perform the run if fetches or targets are provided,
  85. // or if the call is a partial run that specifies feeds.
  86. var results = _do_run(final_targets.Select(x => (Operation)x).ToList(), final_fetches, feed_dict_tensor);
  87. return fetch_handler.build_results(this, results);
  88. }
  89. /// <summary>
  90. /// Runs a step based on the given fetches and feeds.
  91. /// </summary>
  92. /// <typeparam name="T"></typeparam>
  93. /// <param name="target_list">A list of operations to be run, but not fetched.</param>
  94. /// <param name="fetch_list"></param>
  95. /// <param name="feed_dict"></param>
  96. /// <returns>
  97. /// A list of numpy ndarrays, corresponding to the elements of
  98. /// `fetch_list`. If the ith element of `fetch_list` contains the
  99. /// name of an operation, the first Tensor output of that operation
  100. /// will be returned for that element.
  101. /// </returns>
  102. private NDArray[] _do_run(List<Operation> target_list, List<Tensor> fetch_list, Dictionary<object, object> feed_dict)
  103. {
  104. var feeds = feed_dict.Select(x =>
  105. {
  106. if (x.Key is Tensor tensor)
  107. {
  108. switch (x.Value)
  109. {
  110. #if _REGEN
  111. %types=["sbyte", "byte", "short", "ushort", "int", "uint", "long", "ulong", "float", "double", "Complex"]
  112. %foreach types%
  113. case #1 v:
  114. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  115. case #1[] v:
  116. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  117. %
  118. #else
  119. case sbyte v:
  120. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  121. case sbyte[] v:
  122. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  123. case byte v:
  124. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  125. case byte[] v:
  126. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  127. case short v:
  128. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  129. case short[] v:
  130. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  131. case ushort v:
  132. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  133. case ushort[] v:
  134. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  135. case int v:
  136. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  137. case int[] v:
  138. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  139. case uint v:
  140. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  141. case uint[] v:
  142. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  143. case long v:
  144. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  145. case long[] v:
  146. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  147. case ulong v:
  148. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  149. case ulong[] v:
  150. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  151. case float v:
  152. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  153. case float[] v:
  154. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  155. case double v:
  156. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  157. case double[] v:
  158. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  159. case Complex v:
  160. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  161. case Complex[] v:
  162. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  163. #endif
  164. case bool v:
  165. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor((byte)(v?1:0), TF_DataType.TF_BOOL));
  166. case string v:
  167. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  168. case IntPtr v:
  169. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v));
  170. case Tensor v:
  171. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), v);
  172. case NDArray v:
  173. return new KeyValuePair<TF_Output, Tensor>(tensor._as_tf_output(), new Tensor(v, tensor.dtype));
  174. default:
  175. throw new NotImplementedException($"feed_dict data type {(x.Value?.GetType().Name ?? "<null>")}");
  176. }
  177. }
  178. throw new NotImplementedException("_do_run.feed_dict");
  179. }).ToArray();
  180. var fetches = fetch_list.Select(x => x._as_tf_output()).ToArray();
  181. var targets = target_list;
  182. return _call_tf_sessionrun(feeds, fetches, target_list);
  183. }
  184. private unsafe NDArray[] _call_tf_sessionrun(KeyValuePair<TF_Output, Tensor>[] feed_dict, TF_Output[] fetch_list, List<Operation> target_list)
  185. {
  186. // Ensure any changes to the graph are reflected in the runtime.
  187. _extend_graph();
  188. var status = new Status();
  189. var output_values = fetch_list.Select(x => IntPtr.Zero).ToArray();
  190. c_api.TF_SessionRun(_session,
  191. run_options: null,
  192. inputs: feed_dict.Select(f => f.Key).ToArray(),
  193. input_values: feed_dict.Select(f => (IntPtr)f.Value).ToArray(),
  194. ninputs: feed_dict.Length,
  195. outputs: fetch_list,
  196. output_values: output_values,
  197. noutputs: fetch_list.Length,
  198. target_opers: target_list.Select(f => (IntPtr)f).ToArray(),
  199. ntargets: target_list.Count,
  200. run_metadata: IntPtr.Zero,
  201. status: status);
  202. status.Check(true);
  203. var result = new NDArray[fetch_list.Length];
  204. for (int i = 0; i < fetch_list.Length; i++)
  205. result[i] = fetchValue(output_values[i]);
  206. for (int i = 0; i < feed_dict.Length; i++)
  207. feed_dict[i].Value.Dispose();
  208. return result;
  209. }
  210. private unsafe NDArray fetchValue(IntPtr output)
  211. {
  212. var tensor = new Tensor(output);
  213. NDArray nd = null;
  214. Type type = tensor.dtype.as_numpy_datatype();
  215. var ndims = tensor.shape;
  216. var offset = c_api.TF_TensorData(output);
  217. if(ndims.Length == 0)
  218. {
  219. switch (tensor.dtype)
  220. {
  221. case TF_DataType.TF_BOOL:
  222. nd = NDArray.Scalar(*(bool*)offset);
  223. break;
  224. case TF_DataType.TF_STRING:
  225. var bytes = tensor.Data();
  226. // wired, don't know why we have to start from offset 9.
  227. // length in the begin
  228. var str = UTF8Encoding.Default.GetString(bytes, 9, bytes[8]);
  229. nd = np.array(str).reshape();
  230. break;
  231. case TF_DataType.TF_UINT8:
  232. nd = NDArray.Scalar(*(byte*)offset);
  233. break;
  234. case TF_DataType.TF_INT16:
  235. nd = NDArray.Scalar(*(short*)offset);
  236. break;
  237. case TF_DataType.TF_INT32:
  238. nd = NDArray.Scalar(*(int*)offset);
  239. break;
  240. case TF_DataType.TF_INT64:
  241. nd = NDArray.Scalar(*(long*)offset);
  242. break;
  243. case TF_DataType.TF_FLOAT:
  244. nd = NDArray.Scalar(*(float*)offset);
  245. break;
  246. case TF_DataType.TF_DOUBLE:
  247. nd = NDArray.Scalar(*(double*)offset);
  248. break;
  249. default:
  250. throw new NotImplementedException("can't fetch output");
  251. }
  252. }
  253. else
  254. {
  255. switch (tensor.dtype)
  256. {
  257. case TF_DataType.TF_BOOL:
  258. var bools = new bool[tensor.size];
  259. for (ulong i = 0; i < tensor.size; i++)
  260. bools[i] = *(bool*)(offset + (int)(tensor.itemsize * i));
  261. nd = np.array(bools).reshape(ndims);
  262. break;
  263. case TF_DataType.TF_STRING:
  264. var bytes = tensor.Data();
  265. // wired, don't know why we have to start from offset 9.
  266. // length in the begin
  267. var str = UTF8Encoding.Default.GetString(bytes, 9, bytes[8]);
  268. nd = np.array(str);
  269. break;
  270. case TF_DataType.TF_UINT8:
  271. var _bytes = new byte[tensor.size];
  272. for (ulong i = 0; i < tensor.size; i++)
  273. _bytes[i] = *(byte*)(offset + (int)(tensor.itemsize * i));
  274. nd = np.array(_bytes).reshape(ndims);
  275. break;
  276. case TF_DataType.TF_INT16:
  277. var shorts = new short[tensor.size];
  278. for (ulong i = 0; i < tensor.size; i++)
  279. shorts[i] = *(short*)(offset + (int)(tensor.itemsize * i));
  280. nd = np.array(shorts).reshape(ndims);
  281. break;
  282. case TF_DataType.TF_INT32:
  283. var ints = new int[tensor.size];
  284. for (ulong i = 0; i < tensor.size; i++)
  285. ints[i] = *(int*)(offset + (int)(tensor.itemsize * i));
  286. nd = np.array(ints).reshape(ndims);
  287. break;
  288. case TF_DataType.TF_INT64:
  289. var longs = new long[tensor.size];
  290. for (ulong i = 0; i < tensor.size; i++)
  291. longs[i] = *(long*)(offset + (int)(tensor.itemsize * i));
  292. nd = np.array(longs).reshape(ndims);
  293. break;
  294. case TF_DataType.TF_FLOAT:
  295. var floats = new float[tensor.size];
  296. for (ulong i = 0; i < tensor.size; i++)
  297. floats[i] = *(float*)(offset + (int)(tensor.itemsize * i));
  298. nd = np.array(floats).reshape(ndims);
  299. break;
  300. case TF_DataType.TF_DOUBLE:
  301. var doubles = new double[tensor.size];
  302. for (ulong i = 0; i < tensor.size; i++)
  303. doubles[i] = *(double*)(offset + (int)(tensor.itemsize * i));
  304. nd = np.array(doubles).reshape(ndims);
  305. break;
  306. default:
  307. throw new NotImplementedException("can't fetch output");
  308. }
  309. }
  310. tensor.Dispose();
  311. return nd;
  312. }
  313. /// <summary>
  314. /// If a tensor handle that is fed to a device incompatible placeholder,
  315. /// we move the tensor to the right device, generate a new tensor handle,
  316. /// and update feed_dict to use the new handle.
  317. /// </summary>
  318. private List<object> _update_with_movers()
  319. {
  320. return new List<object> { };
  321. }
  322. private void _extend_graph()
  323. {
  324. }
  325. public void close()
  326. {
  327. Dispose();
  328. }
  329. protected override void DisposeUnManagedState()
  330. {
  331. using (var status = new Status())
  332. {
  333. c_api.TF_DeleteSession(_handle, status);
  334. status.Check(true);
  335. }
  336. }
  337. }
  338. }