Skip to content

Commit 8c2c18a

Browse files
committed
GradientTest.Gradients
1 parent c6169e8 commit 8c2c18a

9 files changed

Lines changed: 106 additions & 27 deletions

File tree

‎src/TensorFlowNET.Core/APIs/tf.gradients.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public static object gradients(Tensor[] ys,
2424
stop_gradients: stop_gradients);
2525
}
2626

27-
public static object gradients(Tensor ys,
27+
public static Tensor[] gradients(Tensor ys,
2828
Tensor[] xs,
2929
Tensor[] grad_ys = null,
3030
string name = "gradients",

‎src/TensorFlowNET.Core/Gradients/gradients_impl.py.cs‎

Lines changed: 57 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,15 @@ namespace Tensorflow
99
{
1010
public class gradients_impl
1111
{
12-
public static void gradients(Tensor[] ys,
12+
public static Tensor[] gradients(Tensor[] ys,
1313
Tensor[] xs,
1414
Tensor[] grad_ys = null,
1515
string name = "gradients",
1616
bool colocate_gradients_with_ops = false,
1717
bool gate_gradients = false,
1818
int? aggregation_method = null)
1919
{
20-
_GradientsHelper(ys, xs, grad_ys, name, colocate_gradients_with_ops, gate_gradients);
20+
return _GradientsHelper(ys, xs, grad_ys, name, colocate_gradients_with_ops, gate_gradients);
2121
}
2222

2323
public static Tensor[] _GradientsHelper(Tensor[] ys,
@@ -91,7 +91,9 @@ public static Tensor[] _GradientsHelper(Tensor[] ys,
9191
{
9292
// 'ready' handles the case where one output gradient relies on
9393
// another output's gradient.
94-
bool ready = !pending_count.ContainsKey(op.Name) || pending_count[op.Name] == 0;
94+
if (!pending_count.ContainsKey(op.Name))
95+
pending_count[op.Name] = 0;
96+
bool ready = pending_count[op.Name] == 0;
9597
if(ready && !to_ops_set.Contains(op) && reachable_to_ops.Contains(op))
9698
{
9799
to_ops_set.Add(op);
@@ -136,8 +138,12 @@ public static Tensor[] _GradientsHelper(Tensor[] ys,
136138

137139
}
138140
}
141+
else
142+
{
143+
in_grads = _NonEagerInputs(op, xs).Select(x => new Tensor(IntPtr.Zero)).ToArray();
144+
}
139145

140-
var inputs = (List<Tensor>)_NonEagerInputs(op, xs);
146+
var inputs = _NonEagerInputs(op, xs).ToList();
141147
foreach (var (t_in, in_grad) in Python.zip(inputs, in_grads))
142148
{
143149
if(in_grad != null)
@@ -155,14 +161,44 @@ public static Tensor[] _GradientsHelper(Tensor[] ys,
155161
return xs.Select(x => _GetGrad(grads, x)).ToArray();
156162
}
157163

164+
/// <summary>
165+
/// Update pending count for the inputs of op and enqueue ready ops.
166+
/// </summary>
167+
/// <param name="grads"></param>
168+
/// <param name="op"></param>
169+
/// <param name="queue"></param>
170+
/// <param name="pending_count"></param>
171+
/// <param name="loop_state"></param>
172+
/// <param name="xs"></param>
158173
private static void _UpdatePendingAndEnqueueReady(Dictionary<string, Tensor[][]> grads,
159174
Operation op,
160175
Queue<Operation> queue,
161176
Dictionary<string ,int> pending_count,
162177
object loop_state,
163178
Tensor[] xs)
164179
{
180+
foreach(var x in _NonEagerInputs(op, xs))
181+
{
182+
pending_count[x.op.Name] -= 1;
183+
var ready = pending_count[x.op.Name] == 0;
165184

185+
if(loop_state != null && !ready)
186+
{
187+
188+
}
189+
190+
if (ready)
191+
{
192+
if (control_flow_util.IsLoopExit(x.op))
193+
{
194+
195+
}
196+
else
197+
{
198+
queue.Enqueue(x.op);
199+
}
200+
}
201+
}
166202
}
167203

168204
private static void _VerifyGeneratedGradients(Tensor[] grads, Operation op)
@@ -227,7 +263,10 @@ private static Operation[] _StopOps(List<Operation> from_ops, List<Operation> st
227263
bool is_stop_op = true;
228264
foreach(var inp in _NonEagerInputs(op, xs))
229265
{
230-
if(pending_count.ContainsKey(op.Name) && pending_count[op.Name] > 0)
266+
if (!pending_count.ContainsKey(inp.op.Name))
267+
pending_count[inp.op.Name] = 0;
268+
269+
if (pending_count[inp.op.Name] > 0)
231270
{
232271
is_stop_op = false;
233272
break;
@@ -267,14 +306,14 @@ private static Tensor[][] _GetGrads(Dictionary<string, Tensor[][]> grads, Operat
267306
private static void _SetGrad(Dictionary<string, Tensor[][]> grads, Tensor t, Tensor grad)
268307
{
269308
var op = t.op;
270-
Tensor[][] op_grads = null;
271-
if (!grads.ContainsKey(op.Name))
309+
Tensor[][] op_grads = grads.ContainsKey(op.Name) ? grads[op.Name] : null;
310+
if (op_grads == null)
272311
{
273312
op_grads = op.outputs.Select(x => new Tensor[1]).ToArray();
274313
grads[op.Name] = op_grads;
275314
}
276315
var t_grads = op_grads[t.value_index];
277-
// t_grads[0] = grad;
316+
t_grads[0] = grad;
278317
}
279318

280319
/// <summary>
@@ -348,7 +387,7 @@ private static (Operation[], Dictionary<string, int>, object) _PendingCount(List
348387
// Clear the boolean so we won't add the inputs again.
349388
reached_ops.Remove(op);
350389
foreach (var inp in _NonEagerInputs(op, xs))
351-
queue.Enqueue((inp as Tensor).op);
390+
queue.Enqueue(inp.op);
352391
}
353392
}
354393
// X in between_ops iff X is on a path of zero or more backpropagatable tensors
@@ -363,19 +402,22 @@ private static (Operation[], Dictionary<string, int>, object) _PendingCount(List
363402
foreach(Tensor x in _NonEagerInputs(op, xs))
364403
{
365404
if (between_ops.Contains(x.op))
366-
if (pending_count.ContainsKey(x.op.Name))
367-
pending_count[x.op.Name] += 1;
368-
else
369-
pending_count[x.op.Name] = 1;
405+
{
406+
if (!pending_count.ContainsKey(x.op.Name))
407+
pending_count[x.op.Name] = 0;
408+
409+
pending_count[x.op.Name] += 1;
410+
}
370411
}
371412
}
372413

373414
return (reachable_to_ops.ToArray(), pending_count, loop_state);
374415
}
375416

376-
private static InputList _NonEagerInputs(Operation op, Tensor[] xs)
417+
private static IEnumerable<Tensor> _NonEagerInputs(Operation op, Tensor[] xs)
377418
{
378-
return op.inputs;
419+
for (int i = 0; i < op.inputs.Length; i++)
420+
yield return op.inputs[i];
379421
}
380422

381423
/// <summary>

‎src/TensorFlowNET.Core/Operations/InputList.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ namespace Tensorflow
99
public class InputList : IEnumerable
1010
{
1111
public Tensor[] _inputs;
12+
public int Length => _inputs.Length;
1213
public Tensor this[int index] => _inputs[index];
1314

1415
public InputList(Tensor[] inputs)

‎src/TensorFlowNET.Core/Operations/Operation.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ public partial class Operation
1414
public int _id => _id_value;
1515
private int _id_value;
1616

17+
public string type => OpType;
18+
1719
private Status status = new Status();
1820

1921
public string Name => c_api.StringPiece(c_api.TF_OperationName(_handle));
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace Tensorflow
6+
{
7+
public class control_flow_util
8+
{
9+
/// <summary>
10+
/// Return true if `op` is an Exit.
11+
/// </summary>
12+
/// <param name="op"></param>
13+
/// <returns></returns>
14+
public static bool IsLoopExit(Operation op)
15+
{
16+
return op.type == "Exit" || op.type == "RefExit";
17+
}
18+
}
19+
}

‎src/TensorFlowNET.Core/Operations/gen_math_ops.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ public static class gen_math_ops
1010
{
1111
public static OpDefLibrary _op_def_lib = new OpDefLibrary();
1212

13-
public static Tensor add(Tensor x, Tensor y)
13+
public static Tensor add(Tensor x, Tensor y, string name = "")
1414
{
15-
var _op = _op_def_lib._apply_op_helper("Add", args: new { x, y });
15+
var _op = _op_def_lib._apply_op_helper("Add", name, args: new { x, y });
1616

1717
return _op.outputs[0];
1818
}
@@ -24,9 +24,9 @@ public static Tensor sub(Tensor x, Tensor y)
2424
return _op.outputs[0];
2525
}
2626

27-
public static Tensor mul(Tensor x, Tensor y)
27+
public static Tensor mul(Tensor x, Tensor y, string name = "")
2828
{
29-
var _op = _op_def_lib._apply_op_helper("Mul", args: new { x, y });
29+
var _op = _op_def_lib._apply_op_helper("Mul", name, args: new { x, y });
3030

3131
return _op.outputs[0];
3232
}

‎src/TensorFlowNET.Core/Python.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,8 @@ public static void with<T>(IPython py, Action<T> action) where T : IPython
6161

6262
public static IEnumerable<(T, T)> zip<T>(IList<T> t1, IList<T> t2)
6363
{
64-
int index = 0;
65-
yield return (t1[index], t2[index]);
64+
for (int i = 0; i < t1.Count; i++)
65+
yield return (t1[i], t2[i]);
6666
}
6767
}
6868

‎src/TensorFlowNET.Core/Tensors/Tensor.Operators.cs‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,33 @@ namespace Tensorflow
66
{
77
public partial class Tensor
88
{
9-
public static Tensor operator +(Tensor t1, Tensor t2)
9+
public static Tensor operator +(Tensor x, Tensor y)
1010
{
11-
return gen_math_ops.add(t1, t2);
11+
Tensor t = null;
12+
13+
Python.with<ops.name_scope>(new ops.name_scope("", "add", new Tensor[] { x, y }), scope =>
14+
{
15+
t = gen_math_ops.add(x, y, scope);
16+
});
17+
18+
return t;
1219
}
1320

1421
public static Tensor operator -(Tensor t1, Tensor t2)
1522
{
1623
return gen_math_ops.sub(t1, t2);
1724
}
1825

19-
public static Tensor operator *(Tensor t1, Tensor t2)
26+
public static Tensor operator *(Tensor x, Tensor y)
2027
{
21-
return gen_math_ops.mul(t1, t2);
28+
Tensor t = null;
29+
30+
Python.with<ops.name_scope>(new ops.name_scope("", "mul", new Tensor[] { x, y }), scope =>
31+
{
32+
t = gen_math_ops.mul(x, y, name: scope);
33+
});
34+
35+
return t;
2236
}
2337

2438
public static Tensor operator /(Tensor t1, Tensor t2)

‎test/TensorFlowNET.UnitTest/GradientTest.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ public void Gradients()
1414
{
1515
var a = tf.constant(0.0);
1616
var b = 2.0 * a;
17-
var g = tf.gradients(a + b, new Tensor[] { a, b }, stop_gradients: new Tensor[] { a, b });
17+
var c = a + b;
18+
var g = tf.gradients(c, new Tensor[] { a, b }, stop_gradients: new Tensor[] { a, b });
1819
}
1920
}
2021
}

0 commit comments

Comments
 (0)