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

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