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

1 year ago
1 year ago
1 year ago
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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 = (double)x;
  158. var b = (double)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. ICollection expected,
  169. ICollection<T> given,
  170. double eps = 1e-6,
  171. float float_eps = 1e-6f)
  172. {
  173. // TODO: check if any of arguments is not double and change toletance
  174. // remove givenAsDouble and cast expected instead
  175. var givenAsDouble = given.Select(x => Convert.ToDouble(x)).ToArray();
  176. CollectionAssert.AreEqual(expected, givenAsDouble, new CollectionComparer(eps));
  177. }
  178. public void assertProtoEquals(object toProto, object o)
  179. {
  180. throw new NotImplementedException();
  181. }
  182. #endregion
  183. #region tensor evaluation and test session
  184. private Session? _cached_session = null;
  185. private Graph? _cached_graph = null;
  186. private object? _cached_config = null;
  187. private bool _cached_force_gpu = false;
  188. private void _ClearCachedSession()
  189. {
  190. if (self._cached_session != null)
  191. {
  192. self._cached_session.Dispose();
  193. self._cached_session = null;
  194. }
  195. }
  196. //protected object _eval_helper(Tensor[] tensors)
  197. //{
  198. // if (tensors == null)
  199. // return null;
  200. // return nest.map_structure(self._eval_tensor, tensors);
  201. //}
  202. protected object? _eval_tensor(object tensor)
  203. {
  204. if (tensor == null)
  205. return None;
  206. //else if (callable(tensor))
  207. // return self._eval_helper(tensor())
  208. else
  209. {
  210. try
  211. {
  212. //TODO:
  213. // if sparse_tensor.is_sparse(tensor):
  214. // return sparse_tensor.SparseTensorValue(tensor.indices, tensor.values,
  215. // tensor.dense_shape)
  216. //return (tensor as Tensor).numpy();
  217. }
  218. catch (Exception)
  219. {
  220. throw new ValueError("Unsupported type: " + tensor.GetType());
  221. }
  222. return null;
  223. }
  224. }
  225. /// <summary>
  226. /// This function is used in many original tensorflow unit tests to evaluate tensors
  227. /// in a test session with special settings (for instance constant folding off)
  228. ///
  229. /// </summary>
  230. public T evaluate<T>(Tensor tensor)
  231. {
  232. object? result = null;
  233. // if context.executing_eagerly():
  234. // return self._eval_helper(tensors)
  235. // else:
  236. {
  237. var sess = tf.get_default_session();
  238. var ndarray = tensor.eval(sess);
  239. if (typeof(T) == typeof(double)
  240. || typeof(T) == typeof(float)
  241. || typeof(T) == typeof(int))
  242. {
  243. result = Convert.ChangeType(ndarray, typeof(T));
  244. }
  245. else if (typeof(T) == typeof(double[]))
  246. {
  247. result = ndarray.ToMultiDimArray<double>();
  248. }
  249. else if (typeof(T) == typeof(float[]))
  250. {
  251. result = ndarray.ToMultiDimArray<float>();
  252. }
  253. else if (typeof(T) == typeof(int[]))
  254. {
  255. result = ndarray.ToMultiDimArray<int>();
  256. }
  257. else
  258. {
  259. result = ndarray;
  260. }
  261. return (T)result;
  262. }
  263. }
  264. ///Returns a TensorFlow Session for use in executing tests.
  265. public Session? cached_session(
  266. Graph? graph = null, object? config = null, bool use_gpu = false, bool force_gpu = false)
  267. {
  268. // This method behaves differently than self.session(): for performance reasons
  269. // `cached_session` will by default reuse the same session within the same
  270. // test.The session returned by this function will only be closed at the end
  271. // of the test(in the TearDown function).
  272. // Use the `use_gpu` and `force_gpu` options to control where ops are run.If
  273. // `force_gpu` is True, all ops are pinned to `/ device:GPU:0`. Otherwise, if
  274. // `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as
  275. // possible.If both `force_gpu and `use_gpu` are False, all ops are pinned to
  276. // the CPU.
  277. // Example:
  278. // python
  279. // class MyOperatorTest(test_util.TensorFlowTestCase) :
  280. // def testMyOperator(self):
  281. // with self.cached_session() as sess:
  282. // valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
  283. // result = MyOperator(valid_input).eval()
  284. // self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
  285. // invalid_input = [-1.0, 2.0, 7.0]
  286. // with self.assertRaisesOpError("negative input not supported"):
  287. // MyOperator(invalid_input).eval()
  288. // Args:
  289. // graph: Optional graph to use during the returned session.
  290. // config: An optional config_pb2.ConfigProto to use to configure the
  291. // session.
  292. // use_gpu: If True, attempt to run as many ops as possible on GPU.
  293. // force_gpu: If True, pin all ops to `/device:GPU:0`.
  294. // Yields:
  295. // A Session object that should be used as a context manager to surround
  296. // the graph building and execution code in a test case.
  297. // TODO:
  298. // if context.executing_eagerly():
  299. // return self._eval_helper(tensors)
  300. // else:
  301. {
  302. var sess = self._get_cached_session(
  303. graph, config, force_gpu, crash_if_inconsistent_args: true);
  304. using var cached = self._constrain_devices_and_set_default(sess, use_gpu, force_gpu);
  305. return cached;
  306. }
  307. }
  308. //Returns a TensorFlow Session for use in executing tests.
  309. public Session session(Graph? graph = null, object? config = null, bool use_gpu = false, bool force_gpu = false)
  310. {
  311. //Note that this will set this session and the graph as global defaults.
  312. //Use the `use_gpu` and `force_gpu` options to control where ops are run.If
  313. //`force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if
  314. //`use_gpu` is True, TensorFlow tries to run as many ops on the GPU as
  315. //possible.If both `force_gpu and `use_gpu` are False, all ops are pinned to
  316. //the CPU.
  317. //Example:
  318. //```python
  319. //class MyOperatorTest(test_util.TensorFlowTestCase):
  320. // def testMyOperator(self):
  321. // with self.session(use_gpu= True):
  322. // valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
  323. // result = MyOperator(valid_input).eval()
  324. // self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
  325. // invalid_input = [-1.0, 2.0, 7.0]
  326. // with self.assertRaisesOpError("negative input not supported"):
  327. // MyOperator(invalid_input).eval()
  328. //```
  329. //Args:
  330. // graph: Optional graph to use during the returned session.
  331. // config: An optional config_pb2.ConfigProto to use to configure the
  332. // session.
  333. // use_gpu: If True, attempt to run as many ops as possible on GPU.
  334. // force_gpu: If True, pin all ops to `/device:GPU:0`.
  335. //Yields:
  336. // A Session object that should be used as a context manager to surround
  337. // the graph building and execution code in a test case.
  338. Session? s = null;
  339. //if (context.executing_eagerly())
  340. // yield None
  341. //else
  342. //{
  343. s = self._create_session(graph, config, force_gpu);
  344. //}
  345. return s.as_default();
  346. }
  347. private Session? _constrain_devices_and_set_default(Session sess, bool use_gpu, bool force_gpu)
  348. {
  349. // Set the session and its graph to global default and constrain devices."""
  350. if (tf.executing_eagerly())
  351. return null;
  352. else
  353. {
  354. sess.graph.as_default();
  355. sess.as_default();
  356. {
  357. if (force_gpu)
  358. {
  359. // TODO:
  360. // Use the name of an actual device if one is detected, or
  361. // '/device:GPU:0' otherwise
  362. /* var gpu_name = gpu_device_name();
  363. if (!gpu_name)
  364. gpu_name = "/device:GPU:0"
  365. using (sess.graph.device(gpu_name)) {
  366. yield return sess;
  367. }*/
  368. return sess;
  369. }
  370. else if (use_gpu)
  371. return sess;
  372. else
  373. using (sess.graph.device("/device:CPU:0"))
  374. return sess;
  375. }
  376. }
  377. }
  378. // See session() for details.
  379. private Session _create_session(Graph? graph, object? cfg, bool forceGpu)
  380. {
  381. var prepare_config = new Func<object, object>((config) =>
  382. {
  383. // """Returns a config for sessions.
  384. // Args:
  385. // config: An optional config_pb2.ConfigProto to use to configure the
  386. // session.
  387. // Returns:
  388. // A config_pb2.ConfigProto object.
  389. //TODO: config
  390. // # use_gpu=False. Currently many tests rely on the fact that any device
  391. // # will be used even when a specific device is supposed to be used.
  392. // allow_soft_placement = not force_gpu
  393. // if config is None:
  394. // config = config_pb2.ConfigProto()
  395. // config.allow_soft_placement = allow_soft_placement
  396. // config.gpu_options.per_process_gpu_memory_fraction = 0.3
  397. // elif not allow_soft_placement and config.allow_soft_placement:
  398. // config_copy = config_pb2.ConfigProto()
  399. // config_copy.CopyFrom(config)
  400. // config = config_copy
  401. // config.allow_soft_placement = False
  402. // # Don't perform optimizations for tests so we don't inadvertently run
  403. // # gpu ops on cpu
  404. // config.graph_options.optimizer_options.opt_level = -1
  405. // # Disable Grappler constant folding since some tests & benchmarks
  406. // # use constant input and become meaningless after constant folding.
  407. // # DO NOT DISABLE GRAPPLER OPTIMIZERS WITHOUT CONSULTING WITH THE
  408. // # GRAPPLER TEAM.
  409. // config.graph_options.rewrite_options.constant_folding = (
  410. // rewriter_config_pb2.RewriterConfig.OFF)
  411. // config.graph_options.rewrite_options.pin_to_host_optimization = (
  412. // rewriter_config_pb2.RewriterConfig.OFF)
  413. return config;
  414. });
  415. //TODO: use this instead of normal session
  416. //return new ErrorLoggingSession(graph = graph, config = prepare_config(config))
  417. return new Session(graph);//, config = prepare_config(config))
  418. }
  419. private Session _get_cached_session(
  420. Graph? graph = null,
  421. object? config = null,
  422. bool force_gpu = false,
  423. bool crash_if_inconsistent_args = true)
  424. {
  425. // See cached_session() for documentation.
  426. if (self._cached_session == null)
  427. {
  428. var sess = self._create_session(graph, config, force_gpu);
  429. self._cached_session = sess;
  430. self._cached_graph = graph;
  431. self._cached_config = config;
  432. self._cached_force_gpu = force_gpu;
  433. return sess;
  434. }
  435. else
  436. {
  437. if (crash_if_inconsistent_args && self._cached_graph != null && !self._cached_graph.Equals(graph))
  438. throw new ValueError(@"The graph used to get the cached session is
  439. different than the one that was used to create the
  440. session. Maybe create a new session with
  441. self.session()");
  442. if (crash_if_inconsistent_args && self._cached_config != null && !self._cached_config.Equals(config))
  443. {
  444. throw new ValueError(@"The config used to get the cached session is
  445. different than the one that was used to create the
  446. session. Maybe create a new session with
  447. self.session()");
  448. }
  449. if (crash_if_inconsistent_args && !self._cached_force_gpu.Equals(force_gpu))
  450. {
  451. throw new ValueError(@"The force_gpu value used to get the cached session is
  452. different than the one that was used to create the
  453. session. Maybe create a new session with
  454. self.session()");
  455. }
  456. return self._cached_session;
  457. }
  458. }
  459. [TestCleanup]
  460. public void Cleanup()
  461. {
  462. _ClearCachedSession();
  463. }
  464. #endregion
  465. public void AssetSequenceEqual<T>(T[] a, T[] b)
  466. {
  467. Assert.IsTrue(Enumerable.SequenceEqual(a, b));
  468. }
  469. }
  470. }