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.

GradientTest.cs 29 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. using Microsoft.VisualStudio.TestTools.UnitTesting;
  2. using Tensorflow.NumPy;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using Tensorflow;
  7. using static Tensorflow.Binding;
  8. namespace TensorFlowNET.UnitTest.Gradient
  9. {
  10. [TestClass]
  11. public class GradientTest : GraphModeTestBase
  12. {
  13. [TestMethod]
  14. public void BroadcastToGrad()
  15. {
  16. var x = tf.constant(2, dtype: dtypes.float32);
  17. var y = tf.broadcast_to(x, (2, 4, 3));
  18. var grad = tf.gradients(y, x);
  19. var sess = tf.Session(graph);
  20. float result = sess.run(grad[0]);
  21. Assert.AreEqual(result, 24.0f);
  22. }
  23. [TestMethod]
  24. public void CumsumGrad()
  25. {
  26. var x = tf.constant(2, dtype: dtypes.float32);
  27. var y = tf.broadcast_to(x, (2, 4, 3));
  28. var z = tf.cumsum(y, axis: 1);
  29. var grad = tf.gradients(z, x);
  30. var sess = tf.Session(graph);
  31. float result = sess.run(grad[0]);
  32. Assert.AreEqual(result, 60.0f);
  33. }
  34. [TestMethod, Ignore]
  35. public void testGradients()
  36. {
  37. var inp = tf.constant(1.0, shape: new[] { 32, 100 }, name: "in");
  38. var w = tf.constant(1.0, shape: new[] { 100, 10 }, name: "w");
  39. var b = tf.Variable(1.0, shape: new[] { 10 }, name: "b");
  40. var xw = math_ops.matmul(inp, w, name: "xw");
  41. var h = nn_ops.bias_add(xw, b, name: "h");
  42. var w_grad = gradients_impl.gradients(new[] { h }, new[] { w })[0];
  43. self.assertEquals("MatMul", w_grad.op.type);
  44. // TODO: Operation._original_op
  45. //self.assertEquals(w_grad.op._original_op, xw.op);
  46. self.assertTrue((bool)w_grad.op.get_attr("transpose_a"));
  47. self.assertFalse((bool)w_grad.op.get_attr("transpose_b"));
  48. }
  49. [TestMethod]
  50. public void testBatchMatMulGradient()
  51. {
  52. var a = tf.constant(np.array(Enumerable.Range(1, 18).Select(elem => (float)elem).ToArray()), shape: new[] { 2, 3, 3 });
  53. var b = tf.divide(a, tf.constant(2.0f));
  54. var c = tf.batch_matmul(a, b);
  55. var g = tf.gradients(c, new[] { a, b }, stop_gradients: new[] { a, b });
  56. var checkG = new[]
  57. {
  58. 3.0f, 7.5f, 12.0f,
  59. 3.0f, 7.5f, 12.0f,
  60. 3.0f, 7.5f, 12.0f,
  61. 16.5f, 21.0f, 25.5f,
  62. 16.5f, 21.0f, 25.5f,
  63. 16.5f, 21.0f, 25.5f,
  64. 12.0f, 12.0f, 12.0f,
  65. 15.0f, 15.0f, 15.0f,
  66. 18.0f, 18.0f, 18.0f,
  67. 39.0f, 39.0f, 39.0f,
  68. 42.0f, 42.0f, 42.0f,
  69. 45.0f, 45.0f, 45.0f
  70. };
  71. var sess = tf.Session();
  72. var result = sess.run(g);
  73. var resultList = result[0].ToArray<float>().ToList();
  74. resultList.AddRange(result[1].ToArray<float>());
  75. Console.WriteLine(result.ToString());
  76. CollectionAssert.AreEqual(resultList.ToArray(), checkG);
  77. }
  78. [TestMethod]
  79. public void testSimpleGradients()
  80. {
  81. (T, T) evaluateDerivatives<T>(Func<Tensor, Tensor> f, T xval) where T : unmanaged
  82. {
  83. var x = tf.constant(xval);
  84. var y = f(x);
  85. var g = tf.gradients(y, x);
  86. var session = tf.Session();
  87. var result = session.run(new[] { y, g[0] });
  88. return (result[0].ToArray<T>()[0], result[1].ToArray<T>()[0]);
  89. }
  90. void test(string name, Func<Tensor, Tensor> tfF, Func<double, (double, double)> targetF, double[] values)
  91. {
  92. foreach (var x in values)
  93. {
  94. var (expectedY, expectedDY) = targetF(x);
  95. {
  96. var (actualY, actualDY) = evaluateDerivatives(tfF, x);
  97. self.assertFloat64Equal(expectedY, actualY, $"value {name}/float64 at {x}");
  98. self.assertFloat64Equal(expectedDY, actualDY, $"derivative {name}/float64 at {x}");
  99. }
  100. {
  101. var (actualY, actualDY) = evaluateDerivatives(tfF, (float)x);
  102. self.assertFloat32Equal((float)expectedY, actualY, $"value {name}/float32 at {x}");
  103. self.assertFloat32Equal((float)expectedDY, actualDY, $"derivative {name}/float32 at {x}");
  104. }
  105. }
  106. }
  107. test("tf.exp",
  108. x => tf.exp(5 * x),
  109. x => (Math.Exp(5.0 * x), 5.0 * Math.Exp(5.0 * x)),
  110. new[] { -1.0, 0.0, 1.0, 1.5 });
  111. test("tf.log",
  112. x => tf.log(x),
  113. x => (Math.Log(x), 1.0 / x),
  114. new[] { 0.5, 1.0, 1.5, 2.0 });
  115. test("tf.sqrt",
  116. x => tf.sqrt(x),
  117. x => (Math.Sqrt(x), 0.5 / Math.Sqrt(x)),
  118. new[] { 0.5, 1.0, 1.1, 1.5, 2.0 });
  119. test("tf.sin",
  120. x => tf.sin(x),
  121. x => (Math.Sin(x), Math.Cos(x)),
  122. new[] { -1.0, 0.0, 1.0, 1.5, 2.0 });
  123. test("tf.sinh",
  124. x => tf.sinh(x),
  125. x => (Math.Sinh(x), Math.Cosh(x)),
  126. new[] { -1.0, 0.0, 1.0, 1.5, 2.0 });
  127. test("tf.cos",
  128. x => tf.cos(x),
  129. x => (Math.Cos(x), -Math.Sin(x)),
  130. new[] { -1.0, 0.0, 1.0, 1.5, 2.0 });
  131. test("tf.cosh",
  132. x => tf.cosh(x),
  133. x => (Math.Cosh(x), Math.Sinh(x)),
  134. new[] { -1.0, 0.0, 1.0, 1.5, 2.0 });
  135. test("tf.tanh",
  136. x => tf.tanh(x),
  137. x => (Math.Tanh(x), 1.0 - Math.Pow(Math.Tanh(x), 2.0)),
  138. new[] { -1.0, 0.0, 1.0, 1.5, 2.0 });
  139. test("tf.maximum",
  140. x => tf.maximum(x, tf.constant(0.0, dtype: x.dtype)),
  141. x => (Math.Max(x, 0.0), (x > 0.0) ? 1.0 : 0.0),
  142. new[] { -1.0, 1.0 });
  143. test("tf.minimum",
  144. x => tf.minimum(x, tf.constant(0.0, dtype: x.dtype)),
  145. x => (Math.Min(x, 0.0), (x < 0.0) ? 1.0 : 0.0),
  146. new[] { -1.0, 1.0 });
  147. }
  148. [TestMethod]
  149. public void testReduceSumGradients()
  150. {
  151. /* python code
  152. import tensorflow.compat.v1 as tf
  153. tf.disable_v2_behavior()
  154. x = tf.placeholder(tf.float64, shape = (1, 1))
  155. m = tf.broadcast_to(x, (2, 3))
  156. g0 = tf.gradients(tf.reduce_sum(m), x)[0]
  157. g1 = tf.gradients(tf.reduce_sum(m, axis = 0)[0], x)[0]
  158. g2 = tf.gradients(tf.reduce_sum(m, axis = 1)[0], x)[0]
  159. with tf.compat.v1.Session() as sess:
  160. (r0, r1, r2) = sess.run((g0, g1, g2), {x: [[1.0]]})
  161. */
  162. var x = tf.placeholder(tf.float64, shape: new Shape(1, 1));
  163. var m = tf.broadcast_to(x, new Shape(2, 3));
  164. var g0 = tf.gradients(tf.reduce_sum(m), x)[0];
  165. var g1 = tf.gradients(tf.reduce_sum(m, axis: 0)[0], x)[0];
  166. var g2 = tf.gradients(tf.reduce_sum(m, axis: 1)[0], x)[0];
  167. var session = tf.Session();
  168. var (r0, r1, r2) = session.run((g0, g1, g2), new FeedItem(x, new[,] { { 1.0 } }));
  169. self.assertFloat64Equal(6.0, r0[0], $"tf.reduce_sum(...)");
  170. self.assertFloat64Equal(2.0, r1[0], $"tf.reduce_sum(..., axis = 0)");
  171. self.assertFloat64Equal(3.0, r2[0], $"tf.reduce_sum(..., axis = 1)");
  172. }
  173. [TestMethod]
  174. public void testTanhGradient()
  175. {
  176. var a = tf.constant(1f);
  177. var b = tf.tanh(a);
  178. var g = tf.gradients(b, a);
  179. var sess = tf.Session();
  180. var result = sess.run(g);
  181. var actual = result[0];
  182. Assert.AreEqual(actual, 0.41997434127f);
  183. }
  184. [TestMethod]
  185. public void testLgammaGrad()
  186. {
  187. var a = tf.constant(5f);
  188. var b = tf.lgamma(a);
  189. var g = tf.gradients(b, a);
  190. var sess = tf.Session();
  191. var result = sess.run(new object[] { g, b });
  192. var actualDeriv = result[0];
  193. var actual = result[1];
  194. Assert.AreEqual(actualDeriv, 1.5061177f);
  195. Assert.AreEqual(actual, 3.17805386f);
  196. }
  197. [TestMethod]
  198. public void testSliceGrad()
  199. {
  200. var a = tf.tanh(tf.constant(new[] { 2f, 3f }, shape: new[] { 2, 1 }));
  201. var b = tf.strided_slice(a,
  202. tf.constant(new[] { 0 }, tf.int32, new[] { 1 }),
  203. tf.constant(new[] { 1 }, tf.int32, new[] { 1 }),
  204. tf.constant(new[] { 1 }, tf.int32, new[] { 1 })
  205. );
  206. var g = tf.gradients(b, a);
  207. var sess = tf.Session();
  208. var result = sess.run(new object[] { g, b });
  209. var actualDeriv = np.squeeze(result[0]);
  210. var actual = np.squeeze(result[1]);
  211. Assert.AreEqual(actualDeriv, new float[] { 1, 0 });
  212. Assert.AreEqual(actual, 0.9640276f);
  213. }
  214. [TestMethod]
  215. public void testConcatGrad()
  216. {
  217. var a1 = tf.constant(new[] { 2f }, shape: new[] { 1 });
  218. var a2 = tf.constant(new[] { 3f }, shape: new[] { 1 });
  219. var a = tf.concat(new List<Tensor>(new[] { a1, a2 }), 0);
  220. var g = tf.gradients(a, a1);
  221. var sess = tf.Session();
  222. var result = sess.run(new object[] { g, a });
  223. var actualDeriv = result[0][0];
  224. var actual = result[1][0];
  225. Assert.AreEqual(actualDeriv, 1f);
  226. Assert.AreEqual(actual, 2f);
  227. }
  228. [TestMethod]
  229. public void testStopGradientFunction()
  230. {
  231. var ap = tf.constant(1f);
  232. var b = tf.tanh(ap) + array_ops.stop_gradient(ap);
  233. var g = tf.gradients(b, ap);
  234. var sess = tf.Session();
  235. var result = sess.run(g);
  236. var actual = result[0];
  237. Assert.AreEqual(actual, 0.41997434127f);
  238. }
  239. [Ignore("TODO")]
  240. [TestMethod]
  241. public void testUnusedOutput()
  242. {
  243. //def testUnusedOutput(self):
  244. // with ops.Graph().as_default():
  245. // w = constant(1.0, shape=[2, 2])
  246. // x = constant(1.0, shape=[2, 2])
  247. // wx = math_ops.matmul(w, x)
  248. // split_wx = array_ops.split(value=wx, num_or_size_splits=2, axis=0)
  249. // c = math_ops.reduce_sum(split_wx[1])
  250. // gw = gradients.gradients(c, [w])[0]
  251. // self.assertEquals("MatMul", gw.op.type)
  252. }
  253. [Ignore("TODO")]
  254. [TestMethod]
  255. public void testColocateGradients()
  256. {
  257. //def testColocateGradients(self):
  258. // with ops.Graph().as_default() as g:
  259. // w = constant(1.0, shape=[1, 1])
  260. // x = constant(1.0, shape=[1, 2])
  261. // with g.device("/device:GPU:0"):
  262. // wx = math_ops.matmul(w, x)
  263. // gw = gradients.gradients(wx, [w], colocate_gradients_with_ops=True)[0]
  264. // self.assertEqual(gw.op.colocation_groups(), wx.op.colocation_groups())
  265. }
  266. [Ignore("TODO")]
  267. [TestMethod]
  268. public void testColocateGradientsWithAggregation()
  269. {
  270. //def testColocateGradientsWithAggregation(self):
  271. // with ops.Graph().as_default() as g:
  272. // with g.device("/device:GPU:1"):
  273. // w = constant(1.0, shape=[1, 1])
  274. // x = constant(1.0, shape=[1, 2])
  275. // y = constant(1.0, shape=[1, 2])
  276. // wx = math_ops.matmul(w, x)
  277. // wy = math_ops.matmul(w, y)
  278. // with g.device("/device:GPU:0"):
  279. // z = wx + wy
  280. // gw1 = gradients.gradients(z, [w], colocate_gradients_with_ops=True)[0]
  281. // self.assertEqual(gw1.op.colocation_groups(), wx.op.colocation_groups())
  282. // gw2 = gradients.gradients(z, [w], colocate_gradients_with_ops=False)[0]
  283. // self.assertTrue(wx.op.colocation_groups() != gw2.op.colocation_groups())
  284. }
  285. [Ignore("TODO")]
  286. [TestMethod]
  287. public void testColocateGradientsWithAggregationInMultipleDevices()
  288. {
  289. //def testColocateGradientsWithAggregationInMultipleDevices(self):
  290. // with ops.Graph().as_default() as g:
  291. // with g.device("/device:GPU:1"):
  292. // w = constant(1.0, shape=[1, 1])
  293. // x = constant(1.0, shape=[1, 2])
  294. // y = constant(1.0, shape=[1, 2])
  295. // with g.device("/task:1"):
  296. // wx = math_ops.matmul(w, x)
  297. // with g.device("/task:2"):
  298. // wy = math_ops.matmul(w, y)
  299. // with g.device("/device:GPU:0"):
  300. // z = wx + wy
  301. // gw1 = gradients.gradients(z, [w], colocate_gradients_with_ops=True)[0]
  302. // self.assertEqual(gw1.op.colocation_groups(), w.op.colocation_groups())
  303. // gw2 = gradients.gradients(z, [w], colocate_gradients_with_ops=False)[0]
  304. // self.assertTrue(w.op.colocation_groups() != gw2.op.colocation_groups())
  305. }
  306. [Ignore("TODO")]
  307. [TestMethod]
  308. public void testColocateGradientsWithGateGradients()
  309. {
  310. //def testColocateGradientsWithGateGradients(self):
  311. // if not test_util.is_gpu_available():
  312. // self.skipTest("No GPU available")
  313. // with ops.Graph().as_default() as g:
  314. // with g.device("/device:CPU:0"):
  315. // x = constant(1.0, shape=[1, 1])
  316. // y = constant(1.0, shape=[1, 1])
  317. // s = x + y
  318. // with g.device("/device:GPU:0"):
  319. // z = math_ops.reduce_sum(s)
  320. // gz_x = gradients.gradients(z, [x], colocate_gradients_with_ops=True,
  321. // gate_gradients=True)[0]
  322. // with session.Session():
  323. // # Make sure the placer doesn't complain.
  324. // self.evaluate(gz_x)
  325. }
  326. [Ignore("TODO")]
  327. [TestMethod]
  328. public void testBoundaryStop()
  329. {
  330. //def testBoundaryStop(self):
  331. // # Test that we don't differentiate 'x'. The gradient function for 'x' is
  332. // # set explicitly to None so we will get an exception if the gradient code
  333. // # tries to differentiate 'x'.
  334. // with ops.Graph().as_default():
  335. // c = constant(1.0)
  336. // x = array_ops.identity(c)
  337. // y = x + 1.0
  338. // z = y + 1
  339. // grads = gradients.gradients(z, [x])
  340. // self.assertTrue(all(x is not None for x in grads))
  341. }
  342. [Ignore("TODO")]
  343. [TestMethod]
  344. public void testBoundaryContinue()
  345. {
  346. //@test_util.run_v1_only("b/120545219")
  347. //def testBoundaryContinue(self):
  348. // # Test that we differentiate both 'x' and 'y' correctly when x is a
  349. // # predecessor of y.
  350. // with self.cached_session():
  351. // x = constant(1.0)
  352. // y = x * 2.0
  353. // z = y * 3.0
  354. // grads = gradients.gradients(z, [x, y])
  355. // self.assertTrue(all(x is not None for x in grads))
  356. // self.assertEqual(6.0, grads[0].eval())
  357. }
  358. [Ignore("TODO")]
  359. [TestMethod]
  360. public void testAggregationMethodAccumulateN()
  361. {
  362. //@test_util.run_v1_only("b/120545219")
  363. //def testAggregationMethodAccumulateN(self):
  364. // with self.cached_session():
  365. // x = constant(1.0)
  366. // y = x * 2.0
  367. // z = y + y + y + y + y + y + y + y + y + y
  368. // grads = gradients.gradients(
  369. // z, [x, y],
  370. // aggregation_method=gradients.AggregationMethod.
  371. // EXPERIMENTAL_ACCUMULATE_N)
  372. // self.assertTrue(all(x is not None for x in grads))
  373. // self.assertEqual(20.0, grads[0].eval())
  374. // self.assertEqual(10.0, grads[1].eval())
  375. }
  376. [Ignore("TODO")]
  377. [TestMethod]
  378. public void testAggregationMethodAddN()
  379. {
  380. //@test_util.run_v1_only("b/120545219")
  381. //def testAggregationMethodAddN(self):
  382. // with self.cached_session():
  383. // x = constant(1.0)
  384. // y = x * 2.0
  385. // z = y + y + y + y + y + y + y + y + y + y
  386. // grads = gradients.gradients(
  387. // z, [x, y], aggregation_method=gradients.AggregationMethod.ADD_N)
  388. // self.assertTrue(all(x is not None for x in grads))
  389. // self.assertEqual(20.0, grads[0].eval())
  390. // self.assertEqual(10.0, grads[1].eval())
  391. }
  392. [Ignore("TODO")]
  393. [TestMethod]
  394. public void testAggregationMethodTree()
  395. {
  396. //@test_util.run_v1_only("b/120545219")
  397. //def testAggregationMethodTree(self):
  398. // with self.cached_session():
  399. // x = constant(1.0)
  400. // y = x * 2.0
  401. // z = y + y + y + y + y + y + y + y + y + y
  402. // grads = gradients.gradients(
  403. // z, [x, y],
  404. // aggregation_method=gradients.AggregationMethod.EXPERIMENTAL_TREE)
  405. // self.assertTrue(all(x is not None for x in grads))
  406. // self.assertEqual(20.0, grads[0].eval())
  407. // self.assertEqual(10.0, grads[1].eval())
  408. }
  409. [Ignore("TODO")]
  410. [TestMethod]
  411. public void testNoGradientForStringOutputs()
  412. {
  413. //def testNoGradientForStringOutputs(self):
  414. // with ops.Graph().as_default():
  415. // def _TestOpGrad(_, float_grad, string_grad):
  416. // """Gradient function for TestStringOutput."""
  417. // self.assertEquals(float_grad.dtype, dtypes.float32)
  418. // self.assertFalse(string_grad)
  419. // return float_grad
  420. // ops.RegisterGradient("TestStringOutput")(_TestOpGrad)
  421. // c = constant(1.0)
  422. // x, _ = test_ops.test_string_output(c)
  423. // z = x * 2.0
  424. // w = z * 3.0
  425. // grads = gradients.gradients(z, [c])
  426. // self.assertTrue(isinstance(grads[0], ops.Tensor))
  427. // grads = gradients.gradients(w, [c])
  428. // self.assertTrue(isinstance(grads[0], ops.Tensor))
  429. }
  430. [Ignore("TODO")]
  431. [TestMethod]
  432. public void testSingletonIndexedSlices()
  433. {
  434. //def testSingletonIndexedSlices(self):
  435. // with ops.Graph().as_default():
  436. // x = array_ops.placeholder(dtypes.float32)
  437. // y = array_ops.identity(x)
  438. // dy = ops.IndexedSlices(
  439. // array_ops.placeholder(dtypes.float32),
  440. // array_ops.placeholder(dtypes.int32))
  441. // dx, = gradients.gradients(y, x, grad_ys=dy)
  442. // # The IndexedSlices gradient of tf.identity is the identity map.
  443. // with self.cached_session() as sess:
  444. // vdx, vdy = sess.run(
  445. // [dx, dy], feed_dict={x: [1.0], dy.indices: [0], dy.values: [2.0]})
  446. // self.assertEqual(vdx, vdy)
  447. }
  448. [Ignore("TODO")]
  449. [TestMethod]
  450. public void testNonDifferentiableSwitchInWhileLoop()
  451. {
  452. //@test_util.run_v1_only("b/120545219")
  453. //def testNonDifferentiableSwitchInWhileLoop(self):
  454. // with ops.Graph().as_default():
  455. // v = array_ops.placeholder(dtypes.float32, [])
  456. // def _Step(i, a, ta):
  457. // a += math_ops.cast(v, dtypes.int32)
  458. // return (i + 1, a, ta.write(i, a))
  459. // n = 4
  460. // i, _, ta = control_flow_ops.while_loop(
  461. // lambda i, *_: i < n,
  462. // _Step, [0, 0, tensor_array_ops.TensorArray(
  463. // dtypes.int32, size=n)])
  464. // target = ta.read(i - 1)
  465. // grad, = gradients.gradients(target, v)
  466. // self.assertIsNone(grad)
  467. }
  468. [Ignore("TODO")]
  469. [TestMethod]
  470. public void testVariableReadValueGradient()
  471. {
  472. //def testVariableReadValueGradient(self):
  473. // with ops.Graph().as_default():
  474. // init = constant_op.constant(100.0)
  475. // var = variables.Variable(init)
  476. // gradient = gradients.gradients(var.read_value(), var)
  477. // self.assertIsNotNone(gradient)
  478. }
  479. [Ignore("TODO")]
  480. [TestMethod]
  481. public void testVariableAsGraphElementGradient()
  482. {
  483. //def testVariableAsGraphElementGradient(self):
  484. // with ops.Graph().as_default() as graph:
  485. // init = constant_op.constant(100.0)
  486. // var = variables.Variable(init)
  487. // gradient = gradients.gradients(graph.as_graph_element(var), var)
  488. // self.assertIsNotNone(gradient)
  489. }
  490. [Ignore("TODO")]
  491. [TestMethod]
  492. public void testVariableRefGradient()
  493. {
  494. //@test_util.run_v1_only("b/120545219")
  495. //def testVariableRefGradient(self):
  496. // with ops.Graph().as_default():
  497. // init = constant_op.constant(100.0)
  498. // var = variables.VariableV1(init)
  499. // gradient = gradients.gradients(var._ref(), var)
  500. // self.assertIsNotNone(gradient)
  501. }
  502. [Ignore("TODO")]
  503. [TestMethod]
  504. public void testDependentYs()
  505. {
  506. //@test_util.run_v1_only("b/120545219")
  507. //def testDependentYs(self):
  508. // with self.cached_session():
  509. // x = constant_op.constant(3.0)
  510. // y = math_ops.square(x)
  511. // y1 = math_ops.square(y)
  512. // y2 = math_ops.square(y1)
  513. // g = gradients.gradients([y, y2], x)
  514. // self.assertAllClose(17502.0, g[0].eval())
  515. // g = gradients.gradients(y + y2, x)
  516. // self.assertAllClose(17502.0, g[0].eval())
  517. // z = array_ops.identity(y)
  518. // z2 = array_ops.identity(y2)
  519. // g = gradients.gradients([z, z2], x)
  520. // self.assertAllClose(17502.0, g[0].eval())
  521. }
  522. [Ignore("TODO")]
  523. [TestMethod]
  524. public void testPartialDerivatives()
  525. {
  526. //@test_util.run_v1_only("b/120545219")
  527. //def testPartialDerivatives(self):
  528. // with self.cached_session():
  529. // x = constant_op.constant(1.)
  530. // y = 2 * x
  531. // z = x + y
  532. // totalg = gradients.gradients(z, [x, y])
  533. // self.assertEqual([3.0, 1.0], [g.eval() for g in totalg])
  534. // partialg = gradients.gradients(z, [x, y], stop_gradients=[x, y])
  535. // self.assertEqual([1.0, 1.0], [g.eval() for g in partialg])
  536. }
  537. [Ignore("TODO")]
  538. [TestMethod]
  539. public void testStopGradients()
  540. {
  541. //@test_util.run_v1_only("b/120545219")
  542. //def testStopGradients(self):
  543. // def _MakeGraph(rng, stop_gradients=()):
  544. // def _FunctionOf(xs, k=3):
  545. // return ops.convert_to_tensor(
  546. // sum(math_ops.matmul(rng.rand(k, k), x) for x in xs)
  547. // + rng.rand(k, k))
  548. // a = _FunctionOf([])
  549. // if "a" in stop_gradients: a = array_ops.stop_gradient(a)
  550. // b = _FunctionOf([a])
  551. // if "b" in stop_gradients: b = array_ops.stop_gradient(b)
  552. // c = _FunctionOf([a, b])
  553. // if "c" in stop_gradients: c = array_ops.stop_gradient(c)
  554. // d = _FunctionOf([b, c])
  555. // if "d" in stop_gradients: d = array_ops.stop_gradient(d)
  556. // return dict(a=a, b=b, c=c, d=d)
  557. // def _Gradients(ys, xs, **kwargs):
  558. // dydxs = gradients.gradients(ys, xs, **kwargs)
  559. // dydxs = [0. * x if dydx is None else dydx
  560. // for x, dydx in zip(xs, dydxs)]
  561. // return dydxs
  562. // seed = np.random.randint(1000)
  563. // cases = []
  564. // subsets = [""] + "a b c d ab ac ad bc bd cd abc abd acd bcd abcd".split()
  565. // graph = _MakeGraph(np.random.RandomState(seed))
  566. // for constants in subsets:
  567. // graph_with_stops = _MakeGraph(np.random.RandomState(seed), constants)
  568. // for variables_ in subsets:
  569. // # compute the gradient when stopped using tf.stop_gradients
  570. // grad1 = _Gradients([graph_with_stops["d"]],
  571. // [graph_with_stops[v] for v in variables_])
  572. // # compute the gradient when stopped using the stop_gradients kwarg
  573. // grad2 = _Gradients([graph["d"]],
  574. // [graph[v] for v in variables_],
  575. // stop_gradients=[graph[v] for v in constants])
  576. // cases.append(dict(grad1=grad1, grad2=grad2,
  577. // constants=constants, variables=variables_))
  578. // # evaluate all tensors in one call to session.run for speed
  579. // with self.cached_session() as sess:
  580. // results = sess.run([(case["grad1"], case["grad2"]) for case in cases])
  581. // for (npgrad1, npgrad2), case in zip(results, cases):
  582. // for a, b in zip(npgrad1, npgrad2):
  583. // np.testing.assert_allclose(a, b)
  584. }
  585. [Ignore("TODO")]
  586. [TestMethod]
  587. public void testUnconnectedGradientsNoneUnconnectedGradients()
  588. {
  589. //def testUnconnectedGradientsNoneUnconnectedGradients(self):
  590. // with ops.Graph().as_default():
  591. // x = constant(1.0, shape=[2, 2])
  592. // y = constant(3.0, shape=[3, 1])
  593. // grad = gradients.gradients(
  594. // [y], [x], unconnected_gradients="none")
  595. // self.assertIsNone(grad[0])
  596. }
  597. [Ignore("TODO")]
  598. [TestMethod]
  599. public void testUnconnectedGradientsZerosUnconnectedGradients()
  600. {
  601. //def testUnconnectedGradientsZerosUnconnectedGradients(self):
  602. // with ops.Graph().as_default():
  603. // x = constant(1.0, shape=[2, 2])
  604. // y = constant(3.0, shape=[3, 1])
  605. // grads = gradients.gradients(
  606. // [y], [x], unconnected_gradients="zero")
  607. // with self.cached_session() as sess:
  608. // self.assertAllEqual([[0.0, 0.0], [0.0, 0.0]], self.evaluate(grads)[0])
  609. }
  610. [Ignore("TODO")]
  611. [TestMethod]
  612. public void testUnconnectedGradientsZeroConnectedGradients()
  613. {
  614. //def testUnconnectedGradientsZeroConnectedGradients(self):
  615. // with ops.Graph().as_default():
  616. // x = constant(1.0)
  617. // y = x * 3.0
  618. // grad = gradients.gradients(
  619. // [y], [x], unconnected_gradients="zero")
  620. // with self.cached_session() as sess:
  621. // self.assertEquals(3.0, self.evaluate(grad)[0])
  622. }
  623. [Ignore("TODO")]
  624. [TestMethod]
  625. public void testUnknownUnconnectedGradientsValueGiven()
  626. {
  627. //def testUnknownUnconnectedGradientsValueGiven(self):
  628. // with ops.Graph().as_default():
  629. // x = constant(1.0)
  630. // y = constant(1.0)
  631. // with self.assertRaisesRegexp(
  632. // ValueError, "Unknown value for unconnected_gradients: 'nonsense'"):
  633. // gradients.gradients([y], [x], unconnected_gradients="nonsense")
  634. }
  635. /*
  636. */
  637. }
  638. }