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

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