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

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

tensorflow框架的.NET版本,提供了丰富的特性和API,可以借此很方便地在.NET平台下搭建深度学习训练与推理流程。