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

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