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.

GradientsTest.cs 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Microsoft.VisualStudio.TestTools.UnitTesting;
  5. using Tensorflow;
  6. using static Tensorflow.Python;
  7. namespace TensorFlowNET.UnitTest.gradients_test
  8. {
  9. [TestClass]
  10. public class GradientsTest : PythonTest
  11. {
  12. [Ignore("TODO")]
  13. [TestMethod]
  14. public void testGradients()
  15. {
  16. with(tf.Graph().as_default(), g =>
  17. {
  18. var inp = tf.constant(1.0, shape: new[] { 32, 100 }, name: "in");
  19. var w = tf.constant(1.0, shape: new[] { 100, 10 }, name: "w");
  20. var b = tf.constant(1.0, shape: new[] { 10 }, name: "b");
  21. var xw = math_ops.matmul(inp, w, name: "xw");
  22. var h = nn_ops.bias_add(xw, b, name: "h");
  23. var w_grad = gradients_impl.gradients(new[] { h }, new[] { w })[0];
  24. self.assertEquals("MatMul", w_grad.op.type);
  25. // TODO: Operation._original_op
  26. //self.assertEquals(w_grad.op._original_op, xw.op);
  27. self.assertTrue((bool)w_grad.op.get_attr("transpose_a"));
  28. self.assertFalse((bool)w_grad.op.get_attr("transpose_b"));
  29. });
  30. }
  31. [Ignore("TODO")]
  32. [TestMethod]
  33. public void testUnusedOutput()
  34. {
  35. //def testUnusedOutput(self):
  36. // with ops.Graph().as_default():
  37. // w = constant(1.0, shape=[2, 2])
  38. // x = constant(1.0, shape=[2, 2])
  39. // wx = math_ops.matmul(w, x)
  40. // split_wx = array_ops.split(value=wx, num_or_size_splits=2, axis=0)
  41. // c = math_ops.reduce_sum(split_wx[1])
  42. // gw = gradients.gradients(c, [w])[0]
  43. // self.assertEquals("MatMul", gw.op.type)
  44. }
  45. [Ignore("TODO")]
  46. [TestMethod]
  47. public void testColocateGradients()
  48. {
  49. //def testColocateGradients(self):
  50. // with ops.Graph().as_default() as g:
  51. // w = constant(1.0, shape=[1, 1])
  52. // x = constant(1.0, shape=[1, 2])
  53. // with g.device("/device:GPU:0"):
  54. // wx = math_ops.matmul(w, x)
  55. // gw = gradients.gradients(wx, [w], colocate_gradients_with_ops=True)[0]
  56. // self.assertEqual(gw.op.colocation_groups(), wx.op.colocation_groups())
  57. }
  58. [Ignore("TODO")]
  59. [TestMethod]
  60. public void testColocateGradientsWithAggregation()
  61. {
  62. //def testColocateGradientsWithAggregation(self):
  63. // with ops.Graph().as_default() as g:
  64. // with g.device("/device:GPU:1"):
  65. // w = constant(1.0, shape=[1, 1])
  66. // x = constant(1.0, shape=[1, 2])
  67. // y = constant(1.0, shape=[1, 2])
  68. // wx = math_ops.matmul(w, x)
  69. // wy = math_ops.matmul(w, y)
  70. // with g.device("/device:GPU:0"):
  71. // z = wx + wy
  72. // gw1 = gradients.gradients(z, [w], colocate_gradients_with_ops=True)[0]
  73. // self.assertEqual(gw1.op.colocation_groups(), wx.op.colocation_groups())
  74. // gw2 = gradients.gradients(z, [w], colocate_gradients_with_ops=False)[0]
  75. // self.assertTrue(wx.op.colocation_groups() != gw2.op.colocation_groups())
  76. }
  77. [Ignore("TODO")]
  78. [TestMethod]
  79. public void testColocateGradientsWithAggregationInMultipleDevices()
  80. {
  81. //def testColocateGradientsWithAggregationInMultipleDevices(self):
  82. // with ops.Graph().as_default() as g:
  83. // with g.device("/device:GPU:1"):
  84. // w = constant(1.0, shape=[1, 1])
  85. // x = constant(1.0, shape=[1, 2])
  86. // y = constant(1.0, shape=[1, 2])
  87. // with g.device("/task:1"):
  88. // wx = math_ops.matmul(w, x)
  89. // with g.device("/task:2"):
  90. // wy = math_ops.matmul(w, y)
  91. // with g.device("/device:GPU:0"):
  92. // z = wx + wy
  93. // gw1 = gradients.gradients(z, [w], colocate_gradients_with_ops=True)[0]
  94. // self.assertEqual(gw1.op.colocation_groups(), w.op.colocation_groups())
  95. // gw2 = gradients.gradients(z, [w], colocate_gradients_with_ops=False)[0]
  96. // self.assertTrue(w.op.colocation_groups() != gw2.op.colocation_groups())
  97. }
  98. [Ignore("TODO")]
  99. [TestMethod]
  100. public void testColocateGradientsWithGateGradients()
  101. {
  102. //def testColocateGradientsWithGateGradients(self):
  103. // if not test_util.is_gpu_available():
  104. // self.skipTest("No GPU available")
  105. // with ops.Graph().as_default() as g:
  106. // with g.device("/device:CPU:0"):
  107. // x = constant(1.0, shape=[1, 1])
  108. // y = constant(1.0, shape=[1, 1])
  109. // s = x + y
  110. // with g.device("/device:GPU:0"):
  111. // z = math_ops.reduce_sum(s)
  112. // gz_x = gradients.gradients(z, [x], colocate_gradients_with_ops=True,
  113. // gate_gradients=True)[0]
  114. // with session.Session():
  115. // # Make sure the placer doesn't complain.
  116. // self.evaluate(gz_x)
  117. }
  118. [Ignore("TODO")]
  119. [TestMethod]
  120. public void testBoundaryStop()
  121. {
  122. //def testBoundaryStop(self):
  123. // # Test that we don't differentiate 'x'. The gradient function for 'x' is
  124. // # set explicitly to None so we will get an exception if the gradient code
  125. // # tries to differentiate 'x'.
  126. // with ops.Graph().as_default():
  127. // c = constant(1.0)
  128. // x = array_ops.identity(c)
  129. // y = x + 1.0
  130. // z = y + 1
  131. // grads = gradients.gradients(z, [x])
  132. // self.assertTrue(all(x is not None for x in grads))
  133. }
  134. [Ignore("TODO")]
  135. [TestMethod]
  136. public void testBoundaryContinue()
  137. {
  138. //@test_util.run_v1_only("b/120545219")
  139. //def testBoundaryContinue(self):
  140. // # Test that we differentiate both 'x' and 'y' correctly when x is a
  141. // # predecessor of y.
  142. // with self.cached_session():
  143. // x = constant(1.0)
  144. // y = x * 2.0
  145. // z = y * 3.0
  146. // grads = gradients.gradients(z, [x, y])
  147. // self.assertTrue(all(x is not None for x in grads))
  148. // self.assertEqual(6.0, grads[0].eval())
  149. }
  150. [Ignore("TODO")]
  151. [TestMethod]
  152. public void testAggregationMethodAccumulateN()
  153. {
  154. //@test_util.run_v1_only("b/120545219")
  155. //def testAggregationMethodAccumulateN(self):
  156. // with self.cached_session():
  157. // x = constant(1.0)
  158. // y = x * 2.0
  159. // z = y + y + y + y + y + y + y + y + y + y
  160. // grads = gradients.gradients(
  161. // z, [x, y],
  162. // aggregation_method=gradients.AggregationMethod.
  163. // EXPERIMENTAL_ACCUMULATE_N)
  164. // self.assertTrue(all(x is not None for x in grads))
  165. // self.assertEqual(20.0, grads[0].eval())
  166. // self.assertEqual(10.0, grads[1].eval())
  167. }
  168. [Ignore("TODO")]
  169. [TestMethod]
  170. public void testAggregationMethodAddN()
  171. {
  172. //@test_util.run_v1_only("b/120545219")
  173. //def testAggregationMethodAddN(self):
  174. // with self.cached_session():
  175. // x = constant(1.0)
  176. // y = x * 2.0
  177. // z = y + y + y + y + y + y + y + y + y + y
  178. // grads = gradients.gradients(
  179. // z, [x, y], aggregation_method=gradients.AggregationMethod.ADD_N)
  180. // self.assertTrue(all(x is not None for x in grads))
  181. // self.assertEqual(20.0, grads[0].eval())
  182. // self.assertEqual(10.0, grads[1].eval())
  183. }
  184. [Ignore("TODO")]
  185. [TestMethod]
  186. public void testAggregationMethodTree()
  187. {
  188. //@test_util.run_v1_only("b/120545219")
  189. //def testAggregationMethodTree(self):
  190. // with self.cached_session():
  191. // x = constant(1.0)
  192. // y = x * 2.0
  193. // z = y + y + y + y + y + y + y + y + y + y
  194. // grads = gradients.gradients(
  195. // z, [x, y],
  196. // aggregation_method=gradients.AggregationMethod.EXPERIMENTAL_TREE)
  197. // self.assertTrue(all(x is not None for x in grads))
  198. // self.assertEqual(20.0, grads[0].eval())
  199. // self.assertEqual(10.0, grads[1].eval())
  200. }
  201. [Ignore("TODO")]
  202. [TestMethod]
  203. public void testNoGradientForStringOutputs()
  204. {
  205. //def testNoGradientForStringOutputs(self):
  206. // with ops.Graph().as_default():
  207. // def _TestOpGrad(_, float_grad, string_grad):
  208. // """Gradient function for TestStringOutput."""
  209. // self.assertEquals(float_grad.dtype, dtypes.float32)
  210. // self.assertFalse(string_grad)
  211. // return float_grad
  212. // ops.RegisterGradient("TestStringOutput")(_TestOpGrad)
  213. // c = constant(1.0)
  214. // x, _ = test_ops.test_string_output(c)
  215. // z = x * 2.0
  216. // w = z * 3.0
  217. // grads = gradients.gradients(z, [c])
  218. // self.assertTrue(isinstance(grads[0], ops.Tensor))
  219. // grads = gradients.gradients(w, [c])
  220. // self.assertTrue(isinstance(grads[0], ops.Tensor))
  221. }
  222. [Ignore("TODO")]
  223. [TestMethod]
  224. public void testSingletonIndexedSlices()
  225. {
  226. //def testSingletonIndexedSlices(self):
  227. // with ops.Graph().as_default():
  228. // x = array_ops.placeholder(dtypes.float32)
  229. // y = array_ops.identity(x)
  230. // dy = ops.IndexedSlices(
  231. // array_ops.placeholder(dtypes.float32),
  232. // array_ops.placeholder(dtypes.int32))
  233. // dx, = gradients.gradients(y, x, grad_ys=dy)
  234. // # The IndexedSlices gradient of tf.identity is the identity map.
  235. // with self.cached_session() as sess:
  236. // vdx, vdy = sess.run(
  237. // [dx, dy], feed_dict={x: [1.0], dy.indices: [0], dy.values: [2.0]})
  238. // self.assertEqual(vdx, vdy)
  239. }
  240. [Ignore("TODO")]
  241. [TestMethod]
  242. public void testNonDifferentiableSwitchInWhileLoop()
  243. {
  244. //@test_util.run_v1_only("b/120545219")
  245. //def testNonDifferentiableSwitchInWhileLoop(self):
  246. // with ops.Graph().as_default():
  247. // v = array_ops.placeholder(dtypes.float32, [])
  248. // def _Step(i, a, ta):
  249. // a += math_ops.cast(v, dtypes.int32)
  250. // return (i + 1, a, ta.write(i, a))
  251. // n = 4
  252. // i, _, ta = control_flow_ops.while_loop(
  253. // lambda i, *_: i < n,
  254. // _Step, [0, 0, tensor_array_ops.TensorArray(
  255. // dtypes.int32, size=n)])
  256. // target = ta.read(i - 1)
  257. // grad, = gradients.gradients(target, v)
  258. // self.assertIsNone(grad)
  259. }
  260. [Ignore("TODO")]
  261. [TestMethod]
  262. public void testVariableReadValueGradient()
  263. {
  264. //def testVariableReadValueGradient(self):
  265. // with ops.Graph().as_default():
  266. // init = constant_op.constant(100.0)
  267. // var = variables.Variable(init)
  268. // gradient = gradients.gradients(var.read_value(), var)
  269. // self.assertIsNotNone(gradient)
  270. }
  271. [Ignore("TODO")]
  272. [TestMethod]
  273. public void testVariableAsGraphElementGradient()
  274. {
  275. //def testVariableAsGraphElementGradient(self):
  276. // with ops.Graph().as_default() as graph:
  277. // init = constant_op.constant(100.0)
  278. // var = variables.Variable(init)
  279. // gradient = gradients.gradients(graph.as_graph_element(var), var)
  280. // self.assertIsNotNone(gradient)
  281. }
  282. [Ignore("TODO")]
  283. [TestMethod]
  284. public void testVariableRefGradient()
  285. {
  286. //@test_util.run_v1_only("b/120545219")
  287. //def testVariableRefGradient(self):
  288. // with ops.Graph().as_default():
  289. // init = constant_op.constant(100.0)
  290. // var = variables.VariableV1(init)
  291. // gradient = gradients.gradients(var._ref(), var)
  292. // self.assertIsNotNone(gradient)
  293. }
  294. [Ignore("TODO")]
  295. [TestMethod]
  296. public void testDependentYs()
  297. {
  298. //@test_util.run_v1_only("b/120545219")
  299. //def testDependentYs(self):
  300. // with self.cached_session():
  301. // x = constant_op.constant(3.0)
  302. // y = math_ops.square(x)
  303. // y1 = math_ops.square(y)
  304. // y2 = math_ops.square(y1)
  305. // g = gradients.gradients([y, y2], x)
  306. // self.assertAllClose(17502.0, g[0].eval())
  307. // g = gradients.gradients(y + y2, x)
  308. // self.assertAllClose(17502.0, g[0].eval())
  309. // z = array_ops.identity(y)
  310. // z2 = array_ops.identity(y2)
  311. // g = gradients.gradients([z, z2], x)
  312. // self.assertAllClose(17502.0, g[0].eval())
  313. }
  314. [Ignore("TODO")]
  315. [TestMethod]
  316. public void testPartialDerivatives()
  317. {
  318. //@test_util.run_v1_only("b/120545219")
  319. //def testPartialDerivatives(self):
  320. // with self.cached_session():
  321. // x = constant_op.constant(1.)
  322. // y = 2 * x
  323. // z = x + y
  324. // totalg = gradients.gradients(z, [x, y])
  325. // self.assertEqual([3.0, 1.0], [g.eval() for g in totalg])
  326. // partialg = gradients.gradients(z, [x, y], stop_gradients=[x, y])
  327. // self.assertEqual([1.0, 1.0], [g.eval() for g in partialg])
  328. }
  329. [Ignore("TODO")]
  330. [TestMethod]
  331. public void testStopGradients()
  332. {
  333. //@test_util.run_v1_only("b/120545219")
  334. //def testStopGradients(self):
  335. // def _MakeGraph(rng, stop_gradients=()):
  336. // def _FunctionOf(xs, k=3):
  337. // return ops.convert_to_tensor(
  338. // sum(math_ops.matmul(rng.rand(k, k), x) for x in xs)
  339. // + rng.rand(k, k))
  340. // a = _FunctionOf([])
  341. // if "a" in stop_gradients: a = array_ops.stop_gradient(a)
  342. // b = _FunctionOf([a])
  343. // if "b" in stop_gradients: b = array_ops.stop_gradient(b)
  344. // c = _FunctionOf([a, b])
  345. // if "c" in stop_gradients: c = array_ops.stop_gradient(c)
  346. // d = _FunctionOf([b, c])
  347. // if "d" in stop_gradients: d = array_ops.stop_gradient(d)
  348. // return dict(a=a, b=b, c=c, d=d)
  349. // def _Gradients(ys, xs, **kwargs):
  350. // dydxs = gradients.gradients(ys, xs, **kwargs)
  351. // dydxs = [0. * x if dydx is None else dydx
  352. // for x, dydx in zip(xs, dydxs)]
  353. // return dydxs
  354. // seed = np.random.randint(1000)
  355. // cases = []
  356. // subsets = [""] + "a b c d ab ac ad bc bd cd abc abd acd bcd abcd".split()
  357. // graph = _MakeGraph(np.random.RandomState(seed))
  358. // for constants in subsets:
  359. // graph_with_stops = _MakeGraph(np.random.RandomState(seed), constants)
  360. // for variables_ in subsets:
  361. // # compute the gradient when stopped using tf.stop_gradients
  362. // grad1 = _Gradients([graph_with_stops["d"]],
  363. // [graph_with_stops[v] for v in variables_])
  364. // # compute the gradient when stopped using the stop_gradients kwarg
  365. // grad2 = _Gradients([graph["d"]],
  366. // [graph[v] for v in variables_],
  367. // stop_gradients=[graph[v] for v in constants])
  368. // cases.append(dict(grad1=grad1, grad2=grad2,
  369. // constants=constants, variables=variables_))
  370. // # evaluate all tensors in one call to session.run for speed
  371. // with self.cached_session() as sess:
  372. // results = sess.run([(case["grad1"], case["grad2"]) for case in cases])
  373. // for (npgrad1, npgrad2), case in zip(results, cases):
  374. // for a, b in zip(npgrad1, npgrad2):
  375. // np.testing.assert_allclose(a, b)
  376. }
  377. [Ignore("TODO")]
  378. [TestMethod]
  379. public void testUnconnectedGradientsNoneUnconnectedGradients()
  380. {
  381. //def testUnconnectedGradientsNoneUnconnectedGradients(self):
  382. // with ops.Graph().as_default():
  383. // x = constant(1.0, shape=[2, 2])
  384. // y = constant(3.0, shape=[3, 1])
  385. // grad = gradients.gradients(
  386. // [y], [x], unconnected_gradients="none")
  387. // self.assertIsNone(grad[0])
  388. }
  389. [Ignore("TODO")]
  390. [TestMethod]
  391. public void testUnconnectedGradientsZerosUnconnectedGradients()
  392. {
  393. //def testUnconnectedGradientsZerosUnconnectedGradients(self):
  394. // with ops.Graph().as_default():
  395. // x = constant(1.0, shape=[2, 2])
  396. // y = constant(3.0, shape=[3, 1])
  397. // grads = gradients.gradients(
  398. // [y], [x], unconnected_gradients="zero")
  399. // with self.cached_session() as sess:
  400. // self.assertAllEqual([[0.0, 0.0], [0.0, 0.0]], self.evaluate(grads)[0])
  401. }
  402. [Ignore("TODO")]
  403. [TestMethod]
  404. public void testUnconnectedGradientsZeroConnectedGradients()
  405. {
  406. //def testUnconnectedGradientsZeroConnectedGradients(self):
  407. // with ops.Graph().as_default():
  408. // x = constant(1.0)
  409. // y = x * 3.0
  410. // grad = gradients.gradients(
  411. // [y], [x], unconnected_gradients="zero")
  412. // with self.cached_session() as sess:
  413. // self.assertEquals(3.0, self.evaluate(grad)[0])
  414. }
  415. [Ignore("TODO")]
  416. [TestMethod]
  417. public void testUnknownUnconnectedGradientsValueGiven()
  418. {
  419. //def testUnknownUnconnectedGradientsValueGiven(self):
  420. // with ops.Graph().as_default():
  421. // x = constant(1.0)
  422. // y = constant(1.0)
  423. // with self.assertRaisesRegexp(
  424. // ValueError, "Unknown value for unconnected_gradients: 'nonsense'"):
  425. // gradients.gradients([y], [x], unconnected_gradients="nonsense")
  426. }
  427. /*
  428. */
  429. }
  430. }