Skip to content

Commit a745021

Browse files
committed
add SlotCreator class.
1 parent efa28d4 commit a745021

7 files changed

Lines changed: 201 additions & 5 deletions

File tree

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,10 @@ public static ITensorOrOperation shape_safe_assign_variable_handle(Tensor handle
1616
value_tensor,
1717
name: name);
1818
}
19+
20+
public static bool is_resource_variable(VariableV1 var)
21+
{
22+
return var is ResourceVariable;
23+
}
1924
}
2025
}

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Linq;
34
using System.Text;
45
using Tensorflow.Framework;
56
using static Tensorflow.Python;
@@ -63,6 +64,19 @@ private Operation _apply_sparse_shared(Tensor grad, RefVariable var, Tensor indi
6364
return control_flow_ops.group(new[] { var_update, m_t, v_t });
6465
}
6566

67+
protected override void _create_slots(RefVariable[] var_list)
68+
{
69+
var first_var = var_list.OrderBy(x => x.name).First();
70+
_create_non_slot_variable(initial_value: _beta1, name: "beta1_power", colocate_with: first_var);
71+
_create_non_slot_variable(initial_value: _beta2, name: "beta2_power", colocate_with: first_var);
72+
73+
// Create slots for the first and second moments.
74+
foreach(var v in var_list)
75+
{
76+
_zero_slot(v, "m", Name);
77+
}
78+
}
79+
6680
private (RefVariable, RefVariable) _get_beta_accumulators()
6781
{
6882
ops.init_scope();

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

Lines changed: 72 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Linq;
44
using System.Text;
55
using Tensorflow.Framework;
6+
using Tensorflow.Train;
67
using static Tensorflow.Python;
78

89
namespace Tensorflow
@@ -13,7 +14,7 @@ namespace Tensorflow
1314
/// class directly, but instead instantiate one of its subclasses such as
1415
/// `GradientDescentOptimizer`, `AdagradOptimizer`, or `MomentumOptimizer`.
1516
/// </summary>
16-
public abstract class Optimizer
17+
public abstract class Optimizer : Trackable
1718
{
1819
// Values for gate_gradients.
1920
public static int GATE_NONE = 0;
@@ -27,6 +28,7 @@ public abstract class Optimizer
2728
public Dictionary<string, Dictionary<string, RefVariable>> _slots;
2829
public Dictionary<string, RefVariable> _non_slot_dict;
2930
public Dictionary<string, object> _deferred_slot_restorations;
31+
SlotCreator slot_creator = new SlotCreator();
3032

3133
public Optimizer(float learning_rate, bool use_locking, string name = null)
3234
{
@@ -187,9 +189,49 @@ public Operation apply_gradients(Tuple<Tensor, RefVariable>[] grads_and_vars, Re
187189
});
188190
}
189191

190-
private void _create_slots(RefVariable[] var_list)
192+
/// <summary>
193+
/// Create the beta1 and beta2 accumulators on the same device as the first
194+
/// variable. Sort the var_list to make sure this device is consistent across
195+
/// workers (these need to go on the same PS, otherwise some updates are
196+
/// silently ignored).
197+
/// </summary>
198+
/// <param name="var_list"></param>
199+
protected virtual void _create_slots(RefVariable[] var_list)
191200
{
201+
202+
}
192203

204+
/// <summary>
205+
/// Add an extra variable, not associated with a slot.
206+
/// </summary>
207+
/// <param name="initial_value"></param>
208+
/// <param name="name"></param>
209+
/// <param name="colocate_with"></param>
210+
protected RefVariable _create_non_slot_variable(float initial_value, string name, RefVariable colocate_with)
211+
{
212+
// Recommendation: Use OptimizerV2 if your optimizer uses non-slot variables.
213+
var graph = colocate_with.graph;
214+
var key = $"{name}.{graph.graph_key}";
215+
var v = _non_slot_dict.ContainsKey(key) ? _non_slot_dict[key] : null;
216+
if(v == null)
217+
{
218+
_maybe_initialize_trackable();
219+
v = variable_scope.default_variable_creator(
220+
initial_value, name: name, trainable: false,
221+
use_resource: resource_variable_ops.is_resource_variable(
222+
colocate_with));
223+
224+
// Restore this variable by name if necessary, but don't add a
225+
// Trackable dependency. Optimizers return the current graph's
226+
// non-slot variables from _checkpoint_dependencies explicitly rather
227+
// than unconditionally adding dependencies (since there may be multiple
228+
// non-slot variables with the same name in different graphs, trying to
229+
// save all of them would result in errors).
230+
_handle_deferred_dependencies(name, v);
231+
_non_slot_dict[key] = v;
232+
}
233+
234+
return v;
193235
}
194236

195237
public virtual Operation _finish(Operation[] update_ops, string name_scope)
@@ -341,5 +383,33 @@ protected T _call_if_callable<T>(T param)
341383
{
342384
return param;
343385
}
386+
387+
/// <summary>
388+
/// Find or create a slot initialized with 0.0.
389+
/// </summary>
390+
/// <param name="var"></param>
391+
/// <param name="slot_name"></param>
392+
/// <param name="op_name"></param>
393+
/// <returns></returns>
394+
protected RefVariable _zero_slot(RefVariable var, string slot_name, string op_name)
395+
{
396+
var named_slots = _slot_dict(slot_name);
397+
if (!named_slots.ContainsKey(_var_key(var)))
398+
{
399+
var new_slot_variable = slot_creator.create_zeros_slot(var, op_name);
400+
}
401+
return named_slots[_var_key(var)];
402+
}
403+
404+
protected Dictionary<string, RefVariable> _slot_dict(string slot_name)
405+
{
406+
var named_slots = _slots.ContainsKey(slot_name) ? _slots[slot_name] : null;
407+
if(named_slots == null)
408+
{
409+
_slots[slot_name] = new Dictionary<string, RefVariable>();
410+
}
411+
412+
return named_slots;
413+
}
344414
}
345415
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
using Tensorflow.Operations.Initializers;
5+
using static Tensorflow.Python;
6+
7+
namespace Tensorflow.Train
8+
{
9+
public class SlotCreator
10+
{
11+
/// <summary>
12+
/// Create a slot initialized to 0 with same shape as the primary object.
13+
/// </summary>
14+
/// <param name="primary"></param>
15+
/// <param name="name"></param>
16+
/// <param name="dtype"></param>
17+
/// <param name="colocate_with_primary"></param>
18+
/// <returns></returns>
19+
public RefVariable create_zeros_slot(RefVariable primary, string name, TF_DataType dtype = TF_DataType.DtInvalid, bool colocate_with_primary = true)
20+
{
21+
if (dtype == TF_DataType.DtInvalid)
22+
dtype = primary.dtype;
23+
var slot_shape = primary.shape;
24+
if (slot_shape.is_fully_defined())
25+
{
26+
var initializer = new Zeros();
27+
return create_slot_with_initializer(
28+
primary, initializer, slot_shape, dtype, name,
29+
colocate_with_primary: colocate_with_primary);
30+
}
31+
else
32+
{
33+
throw new NotImplementedException("create_zeros_slot is not fully defined.");
34+
}
35+
}
36+
37+
/// <summary>
38+
/// Creates a slot initialized using an `Initializer`.
39+
/// </summary>
40+
/// <returns></returns>
41+
public RefVariable create_slot_with_initializer(RefVariable primary, IInitializer initializer, TensorShape shape,
42+
TF_DataType dtype, string name, bool colocate_with_primary = true)
43+
{
44+
var validate_shape = shape.is_fully_defined();
45+
var prefix = primary.op.name;
46+
return with(new variable_scope(prefix + "/" + name), delegate
47+
{
48+
return _create_slot_var(primary, initializer, "", validate_shape, shape, dtype);
49+
});
50+
}
51+
52+
/// <summary>
53+
/// Helper function for creating a slot variable.
54+
/// </summary>
55+
/// <param name="primary"></param>
56+
/// <param name="val"></param>
57+
/// <param name="scope"></param>
58+
/// <param name="validate_shape"></param>
59+
/// <param name="shape"></param>
60+
/// <param name="dtype"></param>
61+
/// <returns></returns>
62+
private RefVariable _create_slot_var(VariableV1 primary, IInitializer val, string scope, bool validate_shape,
63+
TensorShape shape, TF_DataType dtype)
64+
{
65+
bool use_resource = primary is RefVariable;
66+
if (resource_variable_ops.is_resource_variable(primary))
67+
use_resource = true;
68+
69+
var slot = variable_scope.get_variable(
70+
scope,
71+
initializer: val,
72+
trainable: false,
73+
use_resource: use_resource,
74+
shape: shape,
75+
dtype: dtype,
76+
validate_shape: validate_shape);
77+
78+
return slot;
79+
}
80+
}
81+
}

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ namespace Tensorflow.Train
66
{
77
public abstract class Trackable
88
{
9+
protected int _self_update_uid;
10+
911
/// <summary>
1012
/// Restore-on-create for a variable be saved with this `Checkpointable`.
1113
/// </summary>
@@ -32,9 +34,29 @@ protected virtual RefVariable _add_variable_with_custom_getter(string name,
3234
return new_variable;
3335
}
3436

37+
/// <summary>
38+
/// Pop and load any deferred checkpoint restores into `trackable`.
39+
/// </summary>
40+
/// <param name="name"></param>
41+
/// <param name="trackable"></param>
42+
protected void _handle_deferred_dependencies(string name, RefVariable trackable)
43+
{
44+
_maybe_initialize_trackable();
45+
// TODO
46+
}
47+
3548
protected RefVariable _track_checkpointable(RefVariable checkpointable, string name, bool overwrite = false)
3649
{
3750
return checkpointable;
3851
}
52+
53+
/// <summary>
54+
/// Initialize dependency management.
55+
/// </summary>
56+
protected void _maybe_initialize_trackable()
57+
{
58+
// _self_unconditional_checkpoint_dependencies = []
59+
_self_update_uid = -1;
60+
}
3961
}
4062
}

‎src/TensorFlowNET.Core/Variables/variable_scope.py.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,11 @@ public void Dispose()
270270
}
271271

272272
// TODO for Switch/Case
273-
public static RefVariable get_variable(string embeddingMatrix, double[,] initializer, bool use_resource)
273+
public static RefVariable get_variable(string embeddingMatrix, IInitializer initializer, bool use_resource,
274+
TensorShape shape = null,
275+
TF_DataType dtype = TF_DataType.DtInvalid,
276+
bool trainable = false,
277+
bool validate_shape = true)
274278
{
275279
throw new NotImplementedException();
276280
}

‎test/TensorFlowNET.UnitTest/control_flow_ops_test/SwitchTestCase.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ public class SwitchTestCase : PythonTest
1616
public void testResourceReadInLoop()
1717
{
1818

19-
var embedding_matrix = variable_scope.get_variable(
20-
"embedding_matrix", initializer: new double[,] { { 2.0 }, { 3.0 } }, use_resource: true);
19+
//var embedding_matrix = variable_scope.get_variable(
20+
//"embedding_matrix", initializer: new double[,] { { 2.0 }, { 3.0 } }, use_resource: true);
2121

2222
Tensor cond(Tensor it, Tensor _)
2323
{

0 commit comments

Comments
 (0)