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.

PythonTest.cs 18 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. using Microsoft.VisualStudio.TestTools.UnitTesting;
  2. using Newtonsoft.Json.Linq;
  3. using Tensorflow.NumPy;
  4. using System;
  5. using System.Collections;
  6. using System.Linq;
  7. using Tensorflow;
  8. using static Tensorflow.Binding;
  9. using OneOf.Types;
  10. using System.Collections.Generic;
  11. namespace TensorFlowNET.UnitTest
  12. {
  13. /// <summary>
  14. /// Use as base class for test classes to get additional assertions
  15. /// </summary>
  16. public class PythonTest
  17. {
  18. #region python compatibility layer
  19. protected PythonTest self { get => this; }
  20. protected int None => -1;
  21. #endregion
  22. #region pytest assertions
  23. public void assertItemsEqual(ICollection given, ICollection expected)
  24. {
  25. if (given is Hashtable && expected is Hashtable)
  26. {
  27. Assert.AreEqual(JObject.FromObject(expected).ToString(), JObject.FromObject(given).ToString());
  28. return;
  29. }
  30. Assert.IsNotNull(expected);
  31. Assert.IsNotNull(given);
  32. var e = expected.OfType<object>().ToArray();
  33. var g = given.OfType<object>().ToArray();
  34. Assert.AreEqual(e.Length, g.Length, $"The collections differ in length expected {e.Length} but got {g.Length}");
  35. for (int i = 0; i < e.Length; i++)
  36. {
  37. /*if (g[i] is NDArray && e[i] is NDArray)
  38. assertItemsEqual((g[i] as NDArray).GetData<object>(), (e[i] as NDArray).GetData<object>());
  39. else*/
  40. if (e[i] is ICollection && g[i] is ICollection)
  41. assertEqual(g[i], e[i]);
  42. else
  43. Assert.AreEqual(e[i], g[i], $"Items differ at index {i}, expected {e[i]} but got {g[i]}");
  44. }
  45. }
  46. public void assertAllEqual(ICollection given, ICollection expected)
  47. {
  48. assertItemsEqual(given, expected);
  49. }
  50. public void assertFloat32Equal(float expected, float actual, string msg)
  51. {
  52. float eps = 1e-6f;
  53. Assert.IsTrue(Math.Abs(expected - actual) < eps * Math.Max(1.0f, Math.Abs(expected)), $"{msg}: expected {expected} vs actual {actual}");
  54. }
  55. public void assertFloat64Equal(double expected, double actual, string msg)
  56. {
  57. double eps = 1e-16f;
  58. Assert.IsTrue(Math.Abs(expected - actual) < eps * Math.Max(1.0f, Math.Abs(expected)), $"{msg}: expected {expected} vs actual {actual}");
  59. }
  60. public void assertEqual(object given, object expected)
  61. {
  62. /*if (given is NDArray && expected is NDArray)
  63. {
  64. assertItemsEqual((given as NDArray).GetData<object>(), (expected as NDArray).GetData<object>());
  65. return;
  66. }*/
  67. if (given is Hashtable && expected is Hashtable)
  68. {
  69. Assert.AreEqual(JObject.FromObject(expected).ToString(), JObject.FromObject(given).ToString());
  70. return;
  71. }
  72. if (given is ICollection && expected is ICollection)
  73. {
  74. assertItemsEqual(given as ICollection, expected as ICollection);
  75. return;
  76. }
  77. if (given is float && expected is float)
  78. {
  79. assertFloat32Equal((float)expected, (float)given, "");
  80. return;
  81. }
  82. if (given is double && expected is double)
  83. {
  84. assertFloat64Equal((double)expected, (double)given, "");
  85. return;
  86. }
  87. Assert.AreEqual(expected, given);
  88. }
  89. public void assertEquals(object given, object expected)
  90. {
  91. assertEqual(given, expected);
  92. }
  93. public void assert(object given)
  94. {
  95. if (given is bool)
  96. Assert.IsTrue((bool)given);
  97. Assert.IsNotNull(given);
  98. }
  99. public void assertIsNotNone(object given)
  100. {
  101. Assert.IsNotNull(given);
  102. }
  103. public void assertFalse(bool cond)
  104. {
  105. Assert.IsFalse(cond);
  106. }
  107. public void assertTrue(bool cond)
  108. {
  109. Assert.IsTrue(cond);
  110. }
  111. public void assertAllClose(NDArray array1, NDArray array2, double eps = 1e-5)
  112. {
  113. Assert.IsTrue(np.allclose(array1, array2, rtol: eps));
  114. }
  115. public void assertAllClose(double value, NDArray array2, double eps = 1e-5)
  116. {
  117. var array1 = np.ones_like(array2) * value;
  118. // Assert.IsTrue(np.allclose(array1, array2, rtol: eps));
  119. }
  120. public void assertProtoEquals(object toProto, object o)
  121. {
  122. throw new NotImplementedException();
  123. }
  124. #endregion
  125. #region tensor evaluation and test session
  126. private Session _cached_session = null;
  127. private Graph _cached_graph = null;
  128. private object _cached_config = null;
  129. private bool _cached_force_gpu = false;
  130. private void _ClearCachedSession()
  131. {
  132. if (self._cached_session != null)
  133. {
  134. self._cached_session.Dispose();
  135. self._cached_session = null;
  136. }
  137. }
  138. //protected object _eval_helper(Tensor[] tensors)
  139. //{
  140. // if (tensors == null)
  141. // return null;
  142. // return nest.map_structure(self._eval_tensor, tensors);
  143. //}
  144. protected object _eval_tensor(object tensor)
  145. {
  146. if (tensor == null)
  147. return None;
  148. //else if (callable(tensor))
  149. // return self._eval_helper(tensor())
  150. else
  151. {
  152. try
  153. {
  154. //TODO:
  155. // if sparse_tensor.is_sparse(tensor):
  156. // return sparse_tensor.SparseTensorValue(tensor.indices, tensor.values,
  157. // tensor.dense_shape)
  158. //return (tensor as Tensor).numpy();
  159. }
  160. catch (Exception)
  161. {
  162. throw new ValueError("Unsupported type: " + tensor.GetType());
  163. }
  164. return null;
  165. }
  166. }
  167. /// <summary>
  168. /// This function is used in many original tensorflow unit tests to evaluate tensors
  169. /// in a test session with special settings (for instance constant folding off)
  170. ///
  171. /// </summary>
  172. public T evaluate<T>(Tensor tensor)
  173. {
  174. object result = null;
  175. // if context.executing_eagerly():
  176. // return self._eval_helper(tensors)
  177. // else:
  178. {
  179. var sess = tf.Session();
  180. var ndarray = tensor.eval(sess);
  181. if (typeof(T) == typeof(double))
  182. {
  183. double x = ndarray;
  184. result = x;
  185. }
  186. else if (typeof(T) == typeof(int))
  187. {
  188. int x = ndarray;
  189. result = x;
  190. }
  191. else
  192. {
  193. result = ndarray;
  194. }
  195. return (T)result;
  196. }
  197. }
  198. ///Returns a TensorFlow Session for use in executing tests.
  199. public Session cached_session(
  200. Graph graph = null, object config = null, bool use_gpu = false, bool force_gpu = false)
  201. {
  202. // This method behaves differently than self.session(): for performance reasons
  203. // `cached_session` will by default reuse the same session within the same
  204. // test.The session returned by this function will only be closed at the end
  205. // of the test(in the TearDown function).
  206. // Use the `use_gpu` and `force_gpu` options to control where ops are run.If
  207. // `force_gpu` is True, all ops are pinned to `/ device:GPU:0`. Otherwise, if
  208. // `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as
  209. // possible.If both `force_gpu and `use_gpu` are False, all ops are pinned to
  210. // the CPU.
  211. // Example:
  212. // python
  213. // class MyOperatorTest(test_util.TensorFlowTestCase) :
  214. // def testMyOperator(self):
  215. // with self.cached_session() as sess:
  216. // valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
  217. // result = MyOperator(valid_input).eval()
  218. // self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
  219. // invalid_input = [-1.0, 2.0, 7.0]
  220. // with self.assertRaisesOpError("negative input not supported"):
  221. // MyOperator(invalid_input).eval()
  222. // Args:
  223. // graph: Optional graph to use during the returned session.
  224. // config: An optional config_pb2.ConfigProto to use to configure the
  225. // session.
  226. // use_gpu: If True, attempt to run as many ops as possible on GPU.
  227. // force_gpu: If True, pin all ops to `/device:GPU:0`.
  228. // Yields:
  229. // A Session object that should be used as a context manager to surround
  230. // the graph building and execution code in a test case.
  231. // TODO:
  232. // if context.executing_eagerly():
  233. // return self._eval_helper(tensors)
  234. // else:
  235. {
  236. var sess = self._get_cached_session(
  237. graph, config, force_gpu, crash_if_inconsistent_args: true);
  238. using var cached = self._constrain_devices_and_set_default(sess, use_gpu, force_gpu);
  239. return cached;
  240. }
  241. }
  242. //Returns a TensorFlow Session for use in executing tests.
  243. public Session session(Graph graph = null, object config = null, bool use_gpu = false, bool force_gpu = false)
  244. {
  245. //Note that this will set this session and the graph as global defaults.
  246. //Use the `use_gpu` and `force_gpu` options to control where ops are run.If
  247. //`force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if
  248. //`use_gpu` is True, TensorFlow tries to run as many ops on the GPU as
  249. //possible.If both `force_gpu and `use_gpu` are False, all ops are pinned to
  250. //the CPU.
  251. //Example:
  252. //```python
  253. //class MyOperatorTest(test_util.TensorFlowTestCase):
  254. // def testMyOperator(self):
  255. // with self.session(use_gpu= True):
  256. // valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
  257. // result = MyOperator(valid_input).eval()
  258. // self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
  259. // invalid_input = [-1.0, 2.0, 7.0]
  260. // with self.assertRaisesOpError("negative input not supported"):
  261. // MyOperator(invalid_input).eval()
  262. //```
  263. //Args:
  264. // graph: Optional graph to use during the returned session.
  265. // config: An optional config_pb2.ConfigProto to use to configure the
  266. // session.
  267. // use_gpu: If True, attempt to run as many ops as possible on GPU.
  268. // force_gpu: If True, pin all ops to `/device:GPU:0`.
  269. //Yields:
  270. // A Session object that should be used as a context manager to surround
  271. // the graph building and execution code in a test case.
  272. Session s = null;
  273. //if (context.executing_eagerly())
  274. // yield None
  275. //else
  276. //{
  277. s = self._create_session(graph, config, force_gpu);
  278. //}
  279. return s.as_default();
  280. }
  281. private Session _constrain_devices_and_set_default(Session sess, bool use_gpu, bool force_gpu)
  282. {
  283. // Set the session and its graph to global default and constrain devices."""
  284. if (tf.executing_eagerly())
  285. return null;
  286. else {
  287. sess.graph.as_default();
  288. sess.as_default();
  289. {
  290. if (force_gpu)
  291. {
  292. // TODO:
  293. // Use the name of an actual device if one is detected, or
  294. // '/device:GPU:0' otherwise
  295. /* var gpu_name = gpu_device_name();
  296. if (!gpu_name)
  297. gpu_name = "/device:GPU:0"
  298. using (sess.graph.device(gpu_name)) {
  299. yield return sess;
  300. }*/
  301. return sess;
  302. }
  303. else if (use_gpu)
  304. return sess;
  305. else
  306. using (sess.graph.device("/device:CPU:0"))
  307. return sess;
  308. }
  309. }
  310. }
  311. // See session() for details.
  312. private Session _create_session(Graph graph, object cfg, bool forceGpu)
  313. {
  314. var prepare_config = new Func<object, object>((config) =>
  315. {
  316. // """Returns a config for sessions.
  317. // Args:
  318. // config: An optional config_pb2.ConfigProto to use to configure the
  319. // session.
  320. // Returns:
  321. // A config_pb2.ConfigProto object.
  322. //TODO: config
  323. // # use_gpu=False. Currently many tests rely on the fact that any device
  324. // # will be used even when a specific device is supposed to be used.
  325. // allow_soft_placement = not force_gpu
  326. // if config is None:
  327. // config = config_pb2.ConfigProto()
  328. // config.allow_soft_placement = allow_soft_placement
  329. // config.gpu_options.per_process_gpu_memory_fraction = 0.3
  330. // elif not allow_soft_placement and config.allow_soft_placement:
  331. // config_copy = config_pb2.ConfigProto()
  332. // config_copy.CopyFrom(config)
  333. // config = config_copy
  334. // config.allow_soft_placement = False
  335. // # Don't perform optimizations for tests so we don't inadvertently run
  336. // # gpu ops on cpu
  337. // config.graph_options.optimizer_options.opt_level = -1
  338. // # Disable Grappler constant folding since some tests & benchmarks
  339. // # use constant input and become meaningless after constant folding.
  340. // # DO NOT DISABLE GRAPPLER OPTIMIZERS WITHOUT CONSULTING WITH THE
  341. // # GRAPPLER TEAM.
  342. // config.graph_options.rewrite_options.constant_folding = (
  343. // rewriter_config_pb2.RewriterConfig.OFF)
  344. // config.graph_options.rewrite_options.pin_to_host_optimization = (
  345. // rewriter_config_pb2.RewriterConfig.OFF)
  346. return config;
  347. });
  348. //TODO: use this instead of normal session
  349. //return new ErrorLoggingSession(graph = graph, config = prepare_config(config))
  350. return new Session(graph);//, config = prepare_config(config))
  351. }
  352. private Session _get_cached_session(
  353. Graph graph = null,
  354. object config = null,
  355. bool force_gpu = false,
  356. bool crash_if_inconsistent_args = true)
  357. {
  358. // See cached_session() for documentation.
  359. if (self._cached_session == null)
  360. {
  361. var sess = self._create_session(graph, config, force_gpu);
  362. self._cached_session = sess;
  363. self._cached_graph = graph;
  364. self._cached_config = config;
  365. self._cached_force_gpu = force_gpu;
  366. return sess;
  367. } else {
  368. if (crash_if_inconsistent_args && !self._cached_graph.Equals(graph))
  369. throw new ValueError(@"The graph used to get the cached session is
  370. different than the one that was used to create the
  371. session. Maybe create a new session with
  372. self.session()");
  373. if (crash_if_inconsistent_args && !self._cached_config.Equals(config)) {
  374. throw new ValueError(@"The config used to get the cached session is
  375. different than the one that was used to create the
  376. session. Maybe create a new session with
  377. self.session()");
  378. }
  379. if (crash_if_inconsistent_args && !self._cached_force_gpu.Equals(force_gpu)) {
  380. throw new ValueError(@"The force_gpu value used to get the cached session is
  381. different than the one that was used to create the
  382. session. Maybe create a new session with
  383. self.session()");
  384. }
  385. return _cached_session;
  386. }
  387. }
  388. [TestCleanup]
  389. public void Cleanup()
  390. {
  391. _ClearCachedSession();
  392. }
  393. #endregion
  394. public void AssetSequenceEqual<T>(T[] a, T[] b)
  395. {
  396. Assert.IsTrue(Enumerable.SequenceEqual(a, b));
  397. }
  398. }
  399. }