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 20 kB

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