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

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