Skip to content

Commit dd1cf25

Browse files
committed
Fix AdamOptimizer in Graph mode.
1 parent 81215df commit dd1cf25

9 files changed

Lines changed: 108 additions & 471 deletions

File tree

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,16 @@ public static Tensor log(Tensor x, string name = null)
268268

269269
public static Tensor rank(Tensor input, string name = null)
270270
{
271+
if (tf.context.executing_eagerly())
272+
{
273+
var results = tf.Runner.TFE_FastPathExecute(tf.context, tf.context.device_name,
274+
"Rank", name,
275+
null,
276+
input);
277+
278+
return results[0];
279+
}
280+
271281
var _op = tf._op_def_lib._apply_op_helper("Rank", name: name, args: new { input });
272282

273283
return _op.outputs[0];

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -567,7 +567,7 @@ private static Tensor _ReductionDims(Tensor x, Tensor axis)
567567
}
568568
else
569569
{
570-
if(x is Tensor)
570+
if(x.rank > -1)
571571
return constant_op.constant(np.arange(x.rank));
572572

573573
var rank = array_ops.rank(x);

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ private Operation _apply_sparse_shared(Tensor grad, RefVariable var, Tensor indi
109109
return control_flow_ops.group(new[] { var_update, m_t, v_t });
110110
}
111111

112-
protected override void _create_slots(RefVariable[] var_list)
112+
protected override void _create_slots(ResourceVariable[] var_list)
113113
{
114114
var first_var = var_list.OrderBy(x => x.Name).First();
115115
_create_non_slot_variable(initial_value: _beta1, name: "beta1_power", colocate_with: first_var);

‎src/TensorFlowNET.Core/Training/Optimizer.cs‎

Lines changed: 33 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ public Optimizer(Tensor learning_rate, bool use_locking, string name = null)
107107
/// </returns>
108108
public Operation minimize(Tensor loss,
109109
RefVariable global_step = null,
110-
List<RefVariable> var_list=null,
110+
List<ResourceVariable> var_list=null,
111111
GateGradientType gate_gradients = GateGradientType.GATE_OP,
112112
int? aggregation_method=null,
113113
bool colocate_gradients_with_ops = false, string name=null, Tensor grad_loss=null)
@@ -142,17 +142,17 @@ public Operation minimize(Tensor loss,
142142
/// <returns>
143143
/// An `Operation` that applies the specified gradients. If `global_step`
144144
/// was not None, that operation also increments `global_step`.</returns>
145-
public Operation apply_gradients(Tuple<Tensor, RefVariable>[] grads_and_vars, RefVariable global_step = null, string name = null)
145+
public Operation apply_gradients(Tuple<Tensor, ResourceVariable>[] grads_and_vars, RefVariable global_step = null, string name = null)
146146
{
147147
// No DistributionStrategy case.
148-
var converted_grads_and_vars = new List<(Tensor, RefVariable, _OptimizableVariable)>();
148+
var converted_grads_and_vars = new List<(Tensor, ResourceVariable, _OptimizableVariable)>();
149149
foreach (var (g, v) in grads_and_vars)
150150
{
151151
if(g != null)
152152
{
153153
// Convert the grad to Tensor or IndexedSlices if necessary.
154154
var gR = ops.convert_to_tensor_or_indexed_slices(g);
155-
var p = _get_processor(v);
155+
var p = optimizer._get_processor(v);
156156
converted_grads_and_vars.Add((gR, v, p));
157157
}
158158
}
@@ -230,7 +230,7 @@ public Operation apply_gradients(Tuple<Tensor, RefVariable>[] grads_and_vars, Re
230230
/// silently ignored).
231231
/// </summary>
232232
/// <param name="var_list"></param>
233-
protected virtual void _create_slots(RefVariable[] var_list)
233+
protected virtual void _create_slots(ResourceVariable[] var_list)
234234
{
235235

236236
}
@@ -276,6 +276,12 @@ public virtual Operation _finish(Operation[] update_ops, string name_scope)
276276
return control_flow_ops.group(update_ops, name_scope);
277277
}
278278

279+
public virtual Operation _apply_dense(Tensor grad, ResourceVariable var)
280+
{
281+
var alpha = math_ops.cast(LearningRateTensor, var.dtype.as_base_dtype());
282+
return gen_training_ops.resource_apply_gradient_descent(var.Handle, alpha, grad, use_locking: _use_locking).op;
283+
}
284+
279285
public virtual Operation _apply_dense(Tensor grad, RefVariable var)
280286
{
281287
var alpha = math_ops.cast(LearningRateTensor, var.dtype.as_base_dtype());
@@ -298,6 +304,16 @@ public virtual Operation _apply_sparse_duplicate_indices(IndexedSlices grad, Ref
298304
return _apply_sparse(gradient_no_duplicate_indices, var);
299305
}
300306

307+
public virtual Operation _apply_sparse_duplicate_indices(IndexedSlices grad, ResourceVariable var)
308+
{
309+
var (summed_values, unique_indices) = _deduplicate_indexed_slices(values: grad.values, indices: grad.indices);
310+
var gradient_no_duplicate_indices = new IndexedSlices(
311+
indices: unique_indices,
312+
values: summed_values,
313+
dense_shape: grad.dense_shape);
314+
return _apply_sparse(gradient_no_duplicate_indices, var);
315+
}
316+
301317
public virtual Operation _apply_sparse(IndexedSlices grad, RefVariable var)
302318
{
303319
throw new NotImplementedException("_apply_sparse");
@@ -344,18 +360,6 @@ protected IVariableV1 _get_non_slot_variable(string name, Graph graph = null)
344360
return non_slot;
345361
}
346362

347-
private _OptimizableVariable _get_processor(RefVariable v)
348-
{
349-
if(v is RefVariable)
350-
{
351-
return new _RefVariableProcessor(v);
352-
}
353-
else
354-
{
355-
throw new NotImplementedException("_get_processor");
356-
}
357-
}
358-
359363
/// <summary>
360364
/// Compute gradients of `loss` for the variables in `var_list`.
361365
/// </summary>
@@ -365,35 +369,37 @@ private _OptimizableVariable _get_processor(RefVariable v)
365369
/// A list of (gradient, variable) pairs. Variable is always present, but
366370
/// gradient can be `None`.
367371
/// </returns>
368-
public Tuple<Tensor, RefVariable>[] compute_gradients(Tensor loss,
369-
List<RefVariable> var_list = null,
372+
public Tuple<Tensor, ResourceVariable>[] compute_gradients(Tensor loss,
373+
List<ResourceVariable> var_list = null,
370374
int? aggregation_method = null,
371375
GateGradientType gate_gradients = GateGradientType.GATE_OP,
372376
bool colocate_gradients_with_ops = false,
373377
Tensor grad_loss = null)
374378
{
375379
// Scale loss if using a "mean" loss reduction and multiple replicas.
376380
loss = _scale_loss(loss);
377-
#pragma warning disable CS0219 // Variable is assigned but its value is never used
378-
int num_towers = 1;
379-
#pragma warning restore CS0219 // Variable is assigned but its value is never used
380381

381382
if(var_list == null)
382383
{
383-
var vars = ops.get_collection<RefVariable>(tf.GraphKeys.TRAINABLE_RESOURCE_VARIABLES);
384+
var vars = ops.get_collection<ResourceVariable>(tf.GraphKeys.TRAINABLE_RESOURCE_VARIABLES);
384385
var tmp = variables.trainable_variables();
385386
switch (tmp)
386387
{
387-
case List<RefVariable> values:
388+
case List<ResourceVariable> values:
389+
var_list = values.Concat(vars).ToList();
390+
break;
391+
/*case List<RefVariable> values:
388392
var_list = values.Concat(vars).ToList();
389393
break;
390394
case List<IVariableV1> values:
391395
var_list = values.Select(x => x as RefVariable).Concat(vars).ToList();
392-
break;
396+
break;*/
397+
default:
398+
throw new NotImplementedException("");
393399
}
394400
}
395401

396-
var_list = var_list.Concat(ops.get_collection<RefVariable>(tf.GraphKeys._STREAMING_MODEL_PORTS)).ToList();
402+
var_list = var_list.Concat(ops.get_collection<ResourceVariable>(tf.GraphKeys._STREAMING_MODEL_PORTS)).ToList();
397403
var processors = var_list.Select(v => optimizer._get_processor(v)).ToList();
398404
var var_refs = processors.Select(x => x.target()).ToArray();
399405

@@ -406,7 +412,7 @@ public Tuple<Tensor, RefVariable>[] compute_gradients(Tensor loss,
406412
grads = control_flow_ops.tuple(grads);
407413

408414
var grads_and_vars = zip(grads, var_list)
409-
.Select(x => new Tuple<Tensor, RefVariable>(x.Item1, x.Item2))
415+
.Select(x => new Tuple<Tensor, ResourceVariable>(x.Item1, x.Item2))
410416
.ToArray();
411417

412418
return grads_and_vars;

‎src/TensorFlowNET.Core/Training/gen_training_ops.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ public static Tensor apply_gradient_descent(RefVariable var, Tensor alpha, Tenso
5959
return _op.outputs[0];
6060
}
6161

62-
public static Operation resource_apply_gradient_descent(EagerTensor var, EagerTensor alpha, EagerTensor delta, bool use_locking = false, string name = null)
62+
public static Operation resource_apply_gradient_descent(Tensor var, Tensor alpha, Tensor delta, bool use_locking = false, string name = null)
6363
{
6464
if (tf.context.executing_eagerly())
6565
{
@@ -79,7 +79,7 @@ public static Operation resource_apply_gradient_descent(EagerTensor var, EagerTe
7979
use_locking
8080
});
8181

82-
return _op.outputs[0];
82+
return _op;
8383
}
8484
}
8585
}

‎src/TensorFlowNET.Core/Training/optimizer.py.cs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ public static _OptimizableVariable _get_processor(RefVariable v)
2424
{
2525
return new _RefVariableProcessor(v);
2626
}
27+
28+
public static _OptimizableVariable _get_processor(ResourceVariable v)
29+
{
30+
return new _DenseResourceVariableProcessor(v);
31+
}
2732
}
2833

2934
public class _RefVariableProcessor : _OptimizableVariable
@@ -56,4 +61,35 @@ public Operation update_op(Optimizer optimizer, Tensor g)
5661
return update_op;
5762
}
5863
}
64+
65+
public class _DenseResourceVariableProcessor : _OptimizableVariable
66+
{
67+
private ResourceVariable _v;
68+
69+
public _DenseResourceVariableProcessor(ResourceVariable v)
70+
{
71+
_v = v;
72+
}
73+
74+
public Tensor target()
75+
{
76+
return _v.Handle;
77+
}
78+
79+
public Operation update_op(Optimizer optimizer, Tensor g)
80+
{
81+
Operation update_op = null;
82+
83+
if (g.Tag == null)
84+
{
85+
update_op = optimizer._apply_dense(g, _v);
86+
}
87+
else if (g.Tag is IndexedSlices)
88+
{
89+
return optimizer._apply_sparse_duplicate_indices(g, _v);
90+
}
91+
92+
return update_op;
93+
}
94+
}
5995
}

0 commit comments

Comments
 (0)