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

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