Skip to content

Commit 5c891ea

Browse files
committed
make get_collection<T> generic.
1 parent c7993cd commit 5c891ea

17 files changed

Lines changed: 172 additions & 99 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public Tensor while_loop(Func<Tensor, Tensor> cond, Func<Tensor, Tensor> body, T
5454
maximum_iterations: maximum_iterations,
5555
return_same_structure: return_same_structure);
5656

57-
public _ControlDependenciesController control_dependencies(Operation[] control_inputs)
57+
public _ControlDependenciesController control_dependencies(ITensorOrOperation[] control_inputs)
5858
=> ops.control_dependencies(control_inputs);
5959
}
6060
}

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ public Tensor assign(RefVariable @ref, object value, bool validate_shape = true,
3636
public void device(string device_name)
3737
=> get_default_graph().device(device_name);
3838

39-
public object get_collection(string key, string scope = "")
40-
=> get_default_graph().get_collection(key, scope: scope);
39+
public List<T> get_collection<T>(string key, string scope = "")
40+
=> get_default_graph().get_collection<T>(key, scope: scope);
4141

4242
/// <summary>
4343
/// A context manager that lifts ops out of control-flow scopes and function-building graphs.
@@ -60,7 +60,7 @@ public ops.NameScope name_scope(string name, string default_name = "", object va
6060
/// </summary>
6161
/// <param name="name"></param>
6262
/// <returns></returns>
63-
public Tensor no_op(string name = null)
63+
public Operation no_op(string name = null)
6464
=> gen_control_flow_ops.no_op(name: name);
6565

6666
/// <summary>

‎src/TensorFlowNET.Core/Framework/meta_graph.py.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ public static (MetaGraphDef, Dictionary<string, RefVariable>) export_scoped_meta
180180
var graph = ops.get_default_graph();
181181

182182
var var_list = new Dictionary<string, RefVariable>();
183-
var variables = graph.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) as List<RefVariable>;
183+
var variables = graph.get_collection<RefVariable>(tf.GraphKeys.GLOBAL_VARIABLES);
184184

185185
if (variables != null)
186186
{

src/TensorFlowNET.Core/Gradients/control_flow_grad.py.cs renamed to src/TensorFlowNET.Core/Gradients/control_flow_grad.cs

Lines changed: 77 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,30 @@
1-
/*****************************************************************************
2-
Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
3-
4-
Licensed under the Apache License, Version 2.0 (the "License");
5-
you may not use this file except in compliance with the License.
6-
You may obtain a copy of the License at
7-
8-
http://www.apache.org/licenses/LICENSE-2.0
9-
10-
Unless required by applicable law or agreed to in writing, software
11-
distributed under the License is distributed on an "AS IS" BASIS,
12-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13-
See the License for the specific language governing permissions and
14-
limitations under the License.
1+
/*****************************************************************************
2+
Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
1515
******************************************************************************/
1616

1717
using System;
1818
using System.Linq;
1919
using Tensorflow.Operations;
20+
using static Tensorflow.Binding;
2021

2122
namespace Tensorflow.Gradients
2223
{
2324
/// <summary>
2425
/// Gradients for operators defined in control_flow_ops.py.cs
2526
/// </summary>
27+
[RegisterGradient("control_flow_grad")]
2628
public class control_flow_grad
2729
{
2830
/// <summary>
@@ -33,6 +35,7 @@ public class control_flow_grad
3335
/// on the second visit. A next_iteration is also added on second visit.
3436
/// </summary>
3537
/// <returns></returns>
38+
[RegisterGradient("Switch")]
3639
public Tensor[] _SwitchGrad(Tensor op, Tensor[] grads)
3740
{
3841
throw new NotImplementedException("_SwitchGrad");
@@ -83,68 +86,68 @@ public Tensor[] _SwitchGrad(Tensor op, Tensor[] grads)
8386
// false_grad = switch(grad[0], op.inputs[1])[0]
8487
// true_grad = switch(grad[1], op.inputs[1])[1]
8588
// return merge([false_grad, true_grad])[0], None
86-
}
87-
89+
}
90+
8891
/// <summary>
8992
/// Gradients for a Merge op are calculated using a Switch op.
9093
/// </summary>
91-
[RegisterGradient("Merge")]
94+
[RegisterGradient("Merge")]
9295
public static Tensor[] _MergeGrad(Operation op, Tensor[] grads)
9396
{
9497
var grad = grads[0];
95-
var _ = grads[1];
9698
var input_op = op.inputs[0].op;
9799
var graph = ops.get_default_graph();
98100
var op_ctxt = control_flow_util.GetOutputContext(input_op);
99101
var grad_ctxt = graph._get_control_flow_context();
100102
switch (op_ctxt)
101103
{
102-
case WhileContext cwhile:
103-
{
104-
return control_flow_ops._SwitchRefOrTensor(grad, grad_ctxt.pivot);
104+
case WhileContext cwhile:
105+
{
106+
return control_flow_ops._SwitchRefOrTensor(grad, grad_ctxt.pivot);
105107
}
106-
case CondContext ccond:
107-
{
108-
var pred = ccond.pred;
109-
if (grad_ctxt != null && grad_ctxt.grad_state != null)
110-
{
111-
//# This Merge node is part of a cond within a loop.
112-
//# The backprop needs to have the value of this predicate for every
113-
//# iteration. So we must have its values accumulated in the forward, and
114-
//# use the accumulated values as the predicate for this backprop switch.
115-
var grad_state = grad_ctxt.grad_state;
116-
var real_pred = grad_state.history_map[pred.name] as Tensor;
117-
if (real_pred == null)
118-
{
119-
//# Remember the value of pred for every iteration.
120-
grad_ctxt = grad_state.grad_context;
121-
grad_ctxt.Exit();
122-
var history_pred = grad_state.AddForwardAccumulator(pred);
123-
grad_ctxt.Enter();
124-
125-
//# Add the stack pop op. If pred.op is in a (outer) CondContext,
126-
//# the stack pop will be guarded with a switch.
127-
real_pred = grad_state.AddBackpropAccumulatedValue(history_pred, pred);
128-
grad_state.history_map[pred.name] = real_pred;
129-
}
130-
pred = real_pred;
131-
}
132-
var results = control_flow_ops._SwitchRefOrTensor(grad, pred, name: "cond_grad");
133-
return results;
108+
case CondContext ccond:
109+
{
110+
var pred = ccond.pred;
111+
if (grad_ctxt != null && grad_ctxt.grad_state != null)
112+
{
113+
//# This Merge node is part of a cond within a loop.
114+
//# The backprop needs to have the value of this predicate for every
115+
//# iteration. So we must have its values accumulated in the forward, and
116+
//# use the accumulated values as the predicate for this backprop switch.
117+
var grad_state = grad_ctxt.grad_state;
118+
var real_pred = grad_state.history_map[pred.name] as Tensor;
119+
if (real_pred == null)
120+
{
121+
//# Remember the value of pred for every iteration.
122+
grad_ctxt = grad_state.grad_context;
123+
grad_ctxt.Exit();
124+
var history_pred = grad_state.AddForwardAccumulator(pred);
125+
grad_ctxt.Enter();
126+
127+
//# Add the stack pop op. If pred.op is in a (outer) CondContext,
128+
//# the stack pop will be guarded with a switch.
129+
real_pred = grad_state.AddBackpropAccumulatedValue(history_pred, pred);
130+
grad_state.history_map[pred.name] = real_pred;
131+
}
132+
pred = real_pred;
133+
}
134+
var results = control_flow_ops._SwitchRefOrTensor(grad, pred, name: "cond_grad");
135+
return results;
134136
}
135-
default:
136-
{
137-
var num_inputs = op.inputs.Length;
138-
var cond = new Tensor[num_inputs];
139-
for (int i = 0; i < num_inputs; i++)
140-
cond[i] = math_ops.equal(op.outputs[1], i);
141-
var result = cond.Select(t => control_flow_ops._SwitchRefOrTensor(grad, t)[1]).ToArray();
142-
return result;
137+
default:
138+
{
139+
var num_inputs = op.inputs.Length;
140+
var cond = new Tensor[num_inputs];
141+
for (int i = 0; i < num_inputs; i++)
142+
cond[i] = math_ops.equal(op.outputs[1], i);
143+
var result = cond.Select(t => control_flow_ops._SwitchRefOrTensor(grad, t)[1]).ToArray();
144+
return result;
143145
}
144146
}
145147

146148
}
147149

150+
[RegisterGradient("RefMerge")]
148151
public Tensor[] _RefMergeGrad(Operation op, Tensor[] grads)
149152
{
150153
return _MergeGrad(op, grads);
@@ -153,6 +156,7 @@ public Tensor[] _RefMergeGrad(Operation op, Tensor[] grads)
153156
/// <summary>
154157
/// Gradients for an exit op are calculated using an Enter op.
155158
/// </summary>
159+
[RegisterGradient("Exit")]
156160
public Tensor[] _ExitGrad(Operation op, Tensor[] grads)
157161
{
158162
throw new NotImplementedException("_ExitGrad");
@@ -197,14 +201,16 @@ public Tensor[] _ExitGrad(Operation op, Tensor[] grads)
197201
///
198202
/// Note that the backprop next_iteration is added in switch grad.
199203
/// </summary>
200-
public (object, Tensor[]) _NextIterationGrad(object _, Tensor[] grad)
204+
[RegisterGradient("NextIteration")]
205+
public Tensor[] _NextIterationGrad(object _, Tensor[] grad)
201206
{
202-
return (_, grad);
207+
return grad;
203208
}
204209

205-
public (object, Tensor[]) _RefNextIterationGrad(object _, Tensor[] grad)
210+
[RegisterGradient("RefNextIteration")]
211+
public Tensor[] _RefNextIterationGrad(object _, Tensor[] grad)
206212
{
207-
return (_, grad);
213+
return grad;
208214
}
209215

210216
/// <summary>
@@ -213,7 +219,8 @@ public Tensor[] _ExitGrad(Operation op, Tensor[] grads)
213219
/// For loop variables, grad is the gradient so just add an exit.
214220
/// For loop invariants, we need to add an accumulator loop.
215221
/// </summary>
216-
public (object, Tensor[]) _EnterGrad(Tensor op, Tensor[] grad)
222+
[RegisterGradient("Enter")]
223+
public Tensor[] _EnterGrad(Tensor op, Tensor[] grad)
217224
{
218225
throw new NotImplementedException("_EnterGrad");
219226
// graph = ops.get_default_graph()
@@ -242,18 +249,21 @@ public Tensor[] _ExitGrad(Operation op, Tensor[] grads)
242249
// return result
243250
}
244251

245-
public (object, Tensor[]) _RefEnterGrad(Tensor op, Tensor[] grad)
252+
253+
[RegisterGradient("RefEnter")]
254+
public Tensor[] _RefEnterGrad(Tensor op, Tensor[] grad)
246255
{
247256
return _EnterGrad(op, grad);
248257
}
249258

250259
/// <summary>
251260
/// Stop backprop for the predicate of a while loop.
252261
/// </summary>
253-
public object _LoopCondGrad(object _)
262+
[RegisterGradient("LoopCond")]
263+
public Tensor[] _LoopCondGrad(Tensor op, Tensor[] grad)
254264
{
255265
return null;
256-
}
257-
258-
}
266+
}
267+
268+
}
259269
}

‎src/TensorFlowNET.Core/Gradients/gradients_util.cs‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,10 @@ public static Tensor[] _GradientsHelper(Tensor[] ys,
108108
{
109109
// generate gradient subgraph for op.
110110
var op = queue.Dequeue();
111+
if(tf.get_default_graph()._nodes_by_name.Count > 18505)
112+
{
111113

114+
}
112115
_maybe_colocate_with(op, gradient_uid, colocate_gradients_with_ops);
113116
//if (loop_state != null)
114117
//loop_state.EnterGradWhileContext(op, before: true);
@@ -157,8 +160,12 @@ public static Tensor[] _GradientsHelper(Tensor[] ys,
157160
// therefore dC/doutput[i] is 0.
158161
foreach (var (i, out_grad) in enumerate(out_grads))
159162
{
160-
if (out_grad == null)
163+
if (out_grad == null &&
164+
(grad_fn == null || _IsTrainable(op.outputs[i])))
161165
{
166+
// Only trainable outputs or outputs for a function call that
167+
// will use SymbolicGradient get a zero gradient. Gradient
168+
// functions should ignore the gradient for other outputs.
162169
if (loop_state != null)
163170
;
164171
else
@@ -170,7 +177,15 @@ public static Tensor[] _GradientsHelper(Tensor[] ys,
170177
{
171178
if (grad_fn != null)
172179
{
173-
in_grads = _MaybeCompile(grad_scope, op, out_grads.Select(x => x[0]).ToArray(), null, grad_fn);
180+
in_grads = _MaybeCompile(grad_scope,
181+
op,
182+
out_grads.Where(x => x != null).Select(x => x[0]).ToArray(),
183+
null,
184+
grad_fn);
185+
}
186+
else
187+
{
188+
throw new NotImplementedException("lambda: _SymGrad(op, out_grads)");
174189
}
175190
_VerifyGeneratedGradients(in_grads, op);
176191
if (gate_gradients && in_grads.Count(x => x != null) > 1)

‎src/TensorFlowNET.Core/Graphs/Graph.cs‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,10 @@ private ITensorOrOperation _as_graph_element_locked(object obj, bool allow_tenso
227227

228228
public void add_to_collection<T>(string name, T value)
229229
{
230+
if(name == "update_ops")
231+
{
232+
233+
}
230234
_check_not_finalized();
231235
if (_collections.ContainsKey(name))
232236
(_collections[name] as List<T>).Add(value);
@@ -442,17 +446,20 @@ public List<T> get_collection<T>(string name, string scope = null)
442446
case List<Tensor> list:
443447
t = list.Select(x => (T)(object)x).ToList();
444448
break;
449+
case List<Operation> list:
450+
t = list.Select(x => (T)(object)x).ToList();
451+
break;
445452
default:
446453
throw new NotImplementedException($"get_collection<{typeof(T).FullName}>");
447454
}
448455
return t;
449456
}
450457

451-
public object get_collection_ref(string name)
458+
public List<T> get_collection_ref<T>(string name)
452459
{
453460
if (!_collections.ContainsKey(name))
454-
_collections[name] = new List<object>();
455-
return _collections[name];
461+
_collections[name] = new List<T>();
462+
return _collections[name] as List<T>;
456463
}
457464

458465
public void prevent_feeding(Tensor tensor)

‎src/TensorFlowNET.Core/Layers/Layer.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ protected virtual void _add_elements_to_collection(Operation[] elements, string[
9090
{
9191
foreach(var name in collection_list)
9292
{
93-
var collection = ops.get_collection_ref(name) as List<object>;
93+
var collection = ops.get_collection_ref<Operation>(name);
9494

9595
foreach (var element in elements)
9696
if (!collection.Contains(element))

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,10 @@ public void _add_control_inputs(Operation[] ops)
5454

5555
public void _set_control_flow_context(ControlFlowContext ctx)
5656
{
57+
if(name == "define_loss/conv_sobj_branch/batch_normalization/cond/FusedBatchNorm_1")
58+
{
59+
60+
}
5761
_control_flow_context = ctx;
5862
}
5963

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,11 @@ public Operation(NodeDef node_def, Graph g, Tensor[] inputs = null, TF_DataType[
151151
}
152152
}
153153

154+
if(node_def.Name == "define_loss/conv_lobj_branch/batch_normalization/cond/FusedBatchNorm_1")
155+
{
156+
157+
}
158+
154159
// Dict mapping op name to file and line information for op colocation
155160
// context managers.
156161
_control_flow_context = graph._get_control_flow_context();

‎src/TensorFlowNET.Core/Train/AdamOptimizer.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,10 @@ public override void _prepare()
154154
var beta2 = _call_if_callable(_beta2);
155155
var epsilon = _call_if_callable(_epsilon);
156156

157-
_lr_t = ops.convert_to_tensor(lr, name: "learning_rate");
158-
_beta1_t = ops.convert_to_tensor(beta1, name: "beta1");
159-
_beta2_t = ops.convert_to_tensor(beta2, name: "beta2");
160-
_epsilon_t = ops.convert_to_tensor(epsilon, name: "epsilon");
157+
_lr_t = _lr_t ?? ops.convert_to_tensor(lr, name: "learning_rate");
158+
_beta1_t = _beta1_t ?? ops.convert_to_tensor(beta1, name: "beta1");
159+
_beta2_t = _beta2_t ?? ops.convert_to_tensor(beta2, name: "beta2");
160+
_epsilon_t = _epsilon_t ?? ops.convert_to_tensor(epsilon, name: "epsilon");
161161
}
162162
}
163163
}

0 commit comments

Comments
 (0)