Skip to content

Commit 86618e4

Browse files
committed
SGD works.
1 parent 2062ad0 commit 86618e4

11 files changed

Lines changed: 238 additions & 32 deletions

File tree

‎src/TensorFlowNET.Core/Eager/c_api.eager.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ public partial class c_api
1212

1313
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
1414
public delegate IntPtr _gradient_function_callback(string op_name,
15-
BindingArray op_inputs,
15+
IntPtr op_inputs,
1616
BindingArray op_outputs,
1717
int num_attrs,
1818
BindingArray output_grads,
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace Tensorflow.Keras.Optimizers
6+
{
7+
public class DeviceDType : IEqualityComparer<DeviceDType>
8+
{
9+
public string Device { get; set; }
10+
public TF_DataType DType { get; set; }
11+
12+
public bool Equals(DeviceDType x, DeviceDType y)
13+
{
14+
return x.ToString() == y.ToString();
15+
}
16+
17+
public int GetHashCode(DeviceDType obj)
18+
{
19+
return 0;
20+
}
21+
22+
public override string ToString()
23+
=> $"{Device}, {DType}";
24+
}
25+
}

‎src/TensorFlowNET.Core/Keras/Optimizers/OptimizerV2.cs‎

Lines changed: 84 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
using Tensorflow.Keras.Utils;
66
using Tensorflow.Train;
77
using static Tensorflow.Binding;
8+
using Tensorflow;
9+
using Tensorflow.Eager;
810

911
namespace Tensorflow.Keras.Optimizers
1012
{
@@ -17,18 +19,32 @@ public class OptimizerV2 : Trackable, IOptimizer
1719
protected virtual string _name { get; }
1820

1921
ResourceVariable _iterations;
20-
List<ResourceVariable> _weight = new List<ResourceVariable>();
21-
Dictionary<string, float> _hyper = new Dictionary<string, float>();
22-
Dictionary<string, ResourceVariable> _hyper_variables = new Dictionary<string, ResourceVariable>();
22+
List<ResourceVariable> _weight;
23+
Dictionary<string, float> _hyper;
24+
Dictionary<string, ResourceVariable> _hyper_variables;
2325
protected bool _momentum;
2426
protected float _initial_decay = 0.0f;
27+
protected bool _use_locking = true;
28+
29+
Dictionary<DeviceDType, Dictionary<string, Tensor>> apply_state;
2530

2631
public OptimizerV2() : base()
2732
{
28-
33+
_weight = new List<ResourceVariable>();
34+
_hyper = new Dictionary<string, float>();
35+
_hyper_variables = new Dictionary<string, ResourceVariable>();
36+
apply_state = new Dictionary<DeviceDType, Dictionary<string, Tensor>>();
2937
}
3038

31-
public void apply_gradients(IEnumerable<(Tensor, ResourceVariable)> grads_and_vars)
39+
/// <summary>
40+
/// Apply gradients to variables.
41+
/// </summary>
42+
/// <param name="grads_and_vars"></param>
43+
/// <param name="name"></param>
44+
/// <param name="experimental_aggregate_gradients"></param>
45+
public void apply_gradients(IEnumerable<(Tensor, ResourceVariable)> grads_and_vars,
46+
string name = null,
47+
bool experimental_aggregate_gradients = true)
3248
{
3349
var var_list = grads_and_vars.Select(x => x.Item2).ToArray();
3450
tf_with(ops.name_scope(_name), delegate
@@ -38,49 +54,91 @@ public void apply_gradients(IEnumerable<(Tensor, ResourceVariable)> grads_and_va
3854
if (grads_and_vars == null || grads_and_vars.Count() == 0)
3955
return control_flow_ops.no_op();
4056

41-
//var apply_state =
42-
_prepare(var_list);
43-
44-
_aggregate_gradients(grads_and_vars);
57+
apply_state = _prepare(var_list);
58+
if(experimental_aggregate_gradients)
59+
{
60+
// var reduced_grads = _aggregate_gradients(grads_and_vars);
61+
_distributed_apply(grads_and_vars, name, apply_state);
62+
}
4563

4664
return null;
4765
});
4866
}
4967

50-
void _aggregate_gradients(IEnumerable<(Tensor, ResourceVariable)> grads_and_vars)
68+
void apply_grad_to_update_var(ResourceVariable var, EagerTensor grad)
69+
{
70+
_resource_apply_dense(var, grad, apply_state);
71+
}
72+
73+
protected virtual Operation _resource_apply_dense(ResourceVariable var,
74+
EagerTensor grad,
75+
Dictionary<DeviceDType, Dictionary<string, Tensor>> _apply_state)
76+
{
77+
throw new NotImplementedException("_resource_apply_dense");
78+
}
79+
80+
void _distributed_apply(IEnumerable<(Tensor, ResourceVariable)> grads_and_vars,
81+
string name,
82+
Dictionary<DeviceDType, Dictionary<string, Tensor>> _apply_state)
83+
{
84+
tf_with(ops.name_scope(name, "", new { skip_on_eager = true }), delegate
85+
{
86+
foreach(var (grad, var) in grads_and_vars)
87+
{
88+
tf_with(ops.name_scope("update"), delegate
89+
{
90+
apply_grad_to_update_var(var, grad as EagerTensor);
91+
});
92+
}
93+
94+
_iterations.assign_add(ops.convert_to_tensor(1, dtype: _iterations.dtype));
95+
});
96+
}
97+
98+
Tensor[] _aggregate_gradients(IEnumerable<(Tensor, ResourceVariable)> grads_and_vars)
99+
{
100+
return grads_and_vars.Select(x => x.Item1).ToArray();
101+
}
102+
103+
Dictionary<DeviceDType, Dictionary<string, Tensor>> _prepare(ResourceVariable[] var_list)
51104
{
52-
var lr_t = _hyper_variables["learning_rate"];
53-
foreach (var grad_and_var in grads_and_vars)
105+
var _apply_state = new Dictionary<DeviceDType, Dictionary<string, Tensor>>();
106+
var keys = var_list.Select(x => new DeviceDType
54107
{
55-
var grad = grad_and_var.Item1;
56-
var variable = grad_and_var.Item2;
57-
// variable.Handle - grad * lr_t.Handle;
108+
Device = x.Device,
109+
DType = x.dtype.as_base_dtype()
110+
}).Distinct(new DeviceDType()).ToArray();
111+
112+
foreach(var device_dtype in keys)
113+
{
114+
_apply_state[device_dtype] = new Dictionary<string, Tensor>();
115+
_prepare_local(device_dtype, _apply_state);
58116
}
117+
118+
return _apply_state;
59119
}
60120

61-
void _prepare(ResourceVariable[] var_list)
121+
protected virtual void _prepare_local(DeviceDType device_dtype,
122+
Dictionary<DeviceDType, Dictionary<string, Tensor>> _apply_state)
62123
{
63-
var keys = new HashSet<(string, TF_DataType)>();
64-
foreach(var variable in var_list)
124+
if (_hyper.ContainsKey("learning_rate"))
65125
{
66-
var lr_t = _prepare_local(variable.Device, variable.dtype.as_base_dtype());
67-
var momentum = _get_hyper("momentum", variable.dtype);
68-
array_ops.identity(momentum);
126+
var lr_t = array_ops.identity(_decayed_lr(device_dtype.DType));
127+
_apply_state[device_dtype]["lr_t"] = lr_t;
69128
}
70129
}
71130

72-
ResourceVariable _prepare_local(string var_device, TF_DataType var_dtype)
131+
Tensor _decayed_lr(TF_DataType var_dtype)
73132
{
74133
var lr_t = _get_hyper("learning_rate", var_dtype);
75-
if(_initial_decay > 0)
134+
if(_initial_decay > 0.0f)
76135
{
77-
136+
throw new NotImplementedException("");
78137
}
79-
80138
return lr_t;
81139
}
82140

83-
ResourceVariable _get_hyper(string name, TF_DataType dtype = TF_DataType.DtInvalid)
141+
protected ResourceVariable _get_hyper(string name, TF_DataType dtype = TF_DataType.DtInvalid)
84142
{
85143
var value = _hyper_variables[name];
86144
return math_ops.cast(value, dtype);

‎src/TensorFlowNET.Core/Keras/Optimizers/SGD.cs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Linq;
34
using System.Text;
5+
using Tensorflow.Eager;
46

57
namespace Tensorflow.Keras.Optimizers
68
{
@@ -24,5 +26,28 @@ public SGD(float learning_rate,
2426

2527
nesterov = nesterov;
2628
}
29+
30+
protected override void _prepare_local(DeviceDType device_dtype,
31+
Dictionary<DeviceDType, Dictionary<string, Tensor>> _apply_state)
32+
{
33+
base._prepare_local(device_dtype, _apply_state);
34+
35+
_apply_state[device_dtype]["momentum"] = array_ops.identity(
36+
_get_hyper("momentum", device_dtype.DType));
37+
}
38+
39+
protected override Operation _resource_apply_dense(ResourceVariable var, EagerTensor grad, Dictionary<DeviceDType, Dictionary<string, Tensor>> _apply_state)
40+
{
41+
if (_momentum)
42+
{
43+
throw new NotImplementedException("_resource_apply_dense");
44+
}
45+
var device_dtype = _apply_state.Keys.FirstOrDefault(x => x.Device == var.Device && x.DType == var.dtype.as_base_dtype());
46+
47+
return gen_training_ops.resource_apply_gradient_descent(var.Handle as EagerTensor,
48+
_apply_state[device_dtype]["lr_t"] as EagerTensor,
49+
grad,
50+
use_locking: _use_locking);
51+
}
2752
}
2853
}

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -894,6 +894,19 @@ public static Tensor reciprocal(Tensor x, string name = null)
894894

895895
public static Tensor floor_mod(Tensor x, Tensor y, string name = null)
896896
{
897+
if (tf.context.executing_eagerly())
898+
{
899+
using var status = new Status();
900+
EagerTensorHandle tensor = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
901+
"FloorMod", name, new IntPtr[]
902+
{
903+
x as EagerTensor,
904+
y as EagerTensor
905+
}, 2, null, status);
906+
status.Check(true);
907+
return tensor;
908+
}
909+
897910
var _op = _op_def_lib._apply_op_helper("FloorMod", name, args: new { x, y });
898911

899912
return _op.outputs[0];

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,32 @@ value as EagerTensor
4444
return null;
4545
}
4646

47+
/// <summary>
48+
/// Adds a value to the current value of a variable.
49+
/// </summary>
50+
/// <param name="resource"></param>
51+
/// <param name="value"></param>
52+
/// <param name="name"></param>
53+
/// <returns></returns>
54+
public static Operation assign_add_variable_op(Tensor resource, Tensor value, string name = null)
55+
{
56+
if (tf.context.executing_eagerly())
57+
{
58+
using var status = new Status();
59+
var tensor = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
60+
"AssignAddVariableOp", name,
61+
new IntPtr[]
62+
{
63+
resource as EagerTensor,
64+
value as EagerTensor
65+
}, 2, null, status);
66+
status.Check(true);
67+
return tensor;
68+
}
69+
70+
return null;
71+
}
72+
4773
public static Operation assign_variable_op(Tensor resource, Tensor value, string name = null)
4874
{
4975
if (tf.context.executing_eagerly())

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,9 @@ protected unsafe NDArray GetNDArray(TF_DataType dtype)
163163
case TF_DataType.TF_INT32:
164164
storage = new UnmanagedStorage(NPTypeCode.Int32);
165165
break;
166+
case TF_DataType.TF_INT64:
167+
storage = new UnmanagedStorage(NPTypeCode.Int64);
168+
break;
166169
case TF_DataType.TF_FLOAT:
167170
storage = new UnmanagedStorage(NPTypeCode.Float);
168171
break;

‎src/TensorFlowNET.Core/Tensors/constant_op.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,9 @@ private static EagerTensor convert_to_eager_tensor(object value, Context ctx, TF
124124
case TF_DataType.TF_FLOAT:
125125
value = Convert.ToSingle(value);
126126
break;
127+
case TF_DataType.TF_INT64:
128+
value = Convert.ToInt64(value);
129+
break;
127130
default:
128131
break;
129132
}

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ You may obtain a copy of the License at
1414
limitations under the License.
1515
******************************************************************************/
1616

17+
using System;
18+
using Tensorflow.Eager;
19+
using static Tensorflow.Binding;
20+
1721
namespace Tensorflow
1822
{
1923
public class gen_training_ops
@@ -55,5 +59,34 @@ public static Tensor apply_gradient_descent(RefVariable var, Tensor alpha, Tenso
5559

5660
return _op.outputs[0];
5761
}
62+
63+
public static Operation resource_apply_gradient_descent(EagerTensor var, EagerTensor alpha, EagerTensor delta, bool use_locking = false, string name = null)
64+
{
65+
if (tf.context.executing_eagerly())
66+
{
67+
using var status = new Status();
68+
var tensor = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
69+
"ResourceApplyGradientDescent", name, new IntPtr[]
70+
{
71+
var,
72+
alpha,
73+
delta
74+
}, 3,
75+
op => wrap_tfe_src.SetOpAttrs(op, "use_locking", use_locking),
76+
status);
77+
status.Check(true);
78+
return tensor;
79+
}
80+
81+
var _op = _op_def_lib._apply_op_helper("ResourceApplyGradientDescent", name, new
82+
{
83+
var,
84+
alpha,
85+
delta,
86+
use_locking
87+
});
88+
89+
return _op.outputs[0];
90+
}
5891
}
5992
}

‎src/TensorFlowNET.Core/Variables/ResourceVariable.Functions.cs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,5 +33,17 @@ public void assign_sub(Tensor delta, bool use_locking = false, string name = nul
3333
{
3434
gen_resource_variable_ops.assign_sub_variable_op(handle, delta, name: name);
3535
}
36+
37+
/// <summary>
38+
/// Adds a value to this variable.
39+
/// </summary>
40+
/// <param name="delta"></param>
41+
/// <param name="use_locking"></param>
42+
/// <param name="name"></param>
43+
/// <param name="read_value"></param>
44+
public void assign_add(Tensor delta, bool use_locking = false, string name = null, bool read_value = true)
45+
{
46+
gen_resource_variable_ops.assign_add_variable_op(handle, delta, name: name);
47+
}
3648
}
3749
}

0 commit comments

Comments
 (0)