Skip to content

Commit 43ab3ca

Browse files
committed
_AddNGrad
1 parent f7e61b0 commit 43ab3ca

11 files changed

Lines changed: 128 additions & 70 deletions

File tree

‎src/TensorFlowNET.Core/Eager/EagerRunner.TFE_FastPathExecute.cs‎

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,8 @@ public Tensor[] TFE_FastPathExecute(Context ctx,
6464
}
6565
}
6666

67-
var flattened_inputs = args.Take(op_def.InputArg.Count)
68-
.Select(x => x as Tensor)
69-
.ToArray();
70-
var flattened_attrs = args.Skip(op_def.InputArg.Count).ToArray();
67+
var flattened_attrs = new List<object>(op_def.InputArg.Count);
68+
var flattened_inputs = new List<Tensor>(op_def.InputArg.Count);
7169

7270
c_api.TFE_OpSetDevice(op, device_name, status.Handle);
7371
status.Check(true);
@@ -80,31 +78,36 @@ public Tensor[] TFE_FastPathExecute(Context ctx,
8078
{
8179
int len = (args[kFastPathExecuteInputStartIndex + i] as object[]).Length;
8280
c_api.TFE_OpSetAttrInt(op, input_arg.NumberAttr, len);
81+
if (op_exec_info.run_callbacks)
82+
{
83+
flattened_attrs.Add(input_arg.NumberAttr);
84+
flattened_attrs.Add(len);
85+
}
8386
attr_list_sizes[input_arg.NumberAttr] = len;
84-
87+
8588
if (len > 0)
8689
{
8790
var fast_input_array = (object[])args[i];
8891
// First item adds the type attr.
89-
if (!AddInputToOp(fast_input_array[i], true, input_arg, op, status))
92+
if (!AddInputToOp(fast_input_array[i], true, input_arg, flattened_attrs, flattened_inputs, op, status))
9093
return null;
9194

9295
for (var j = 1; j < len; j++)
9396
{
9497
// Since the list is homogeneous, we don't need to re-add the attr.
95-
if (!AddInputToOp(fast_input_array[j], false, input_arg, op, status))
98+
if (!AddInputToOp(fast_input_array[j], false, input_arg, flattened_attrs, flattened_inputs, op, status))
9699
return null;
97100
}
98101
}
99102
}
100103
else if (!string.IsNullOrEmpty(input_arg.TypeListAttr))
101104
{
102-
105+
throw new NotImplementedException("");
103106
}
104107
else
105108
{
106109
// The item is a single item.
107-
AddInputToOp(args[i], true, input_arg, op, status);
110+
AddInputToOp(args[i], true, input_arg, flattened_attrs, flattened_inputs, op, status);
108111
}
109112
}
110113

@@ -133,7 +136,7 @@ public Tensor[] TFE_FastPathExecute(Context ctx,
133136
if (!RunCallbacks(
134137
op_exec_info,
135138
kFastPathExecuteInputStartIndex + op_def.InputArg.Count(),
136-
flattened_inputs, flattened_attrs, flat_result))
139+
flattened_inputs.ToArray(), flattened_attrs.ToArray(), flat_result))
137140
{
138141
return null;
139142
}
@@ -187,6 +190,8 @@ bool HasAccumulatorOrTape()
187190
bool AddInputToOp(object inputs,
188191
bool add_type_attr,
189192
ArgDef input_arg,
193+
List<object> flattened_attrs,
194+
List<Tensor> flattened_inputs,
190195
IntPtr op,
191196
Status status)
192197
{
@@ -197,6 +202,7 @@ bool AddInputToOp(object inputs,
197202
{
198203
case EagerTensor input:
199204
input_handle = input.EagerTensorHandle;
205+
flattened_inputs.Add(input);
200206
break;
201207
case EagerTensor[] input_list:
202208
input_handle = input_list[0].EagerTensorHandle;
@@ -211,6 +217,8 @@ bool AddInputToOp(object inputs,
211217
{
212218
var dtype = c_api.TFE_TensorHandleDataType(input_handle);
213219
c_api.TFE_OpSetAttrType(op, input_arg.TypeAttr, dtype);
220+
flattened_attrs.Add(input_arg.TypeAttr);
221+
flattened_attrs.Add(dtype);
214222
}
215223

216224
c_api.TFE_OpAddInput(op, input_handle, status.Handle);

‎src/TensorFlowNET.Core/Eager/EagerTensor.Creation.cs‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public EagerTensor(NDArray value, string device_name) : base(value)
3434

3535
public EagerTensor Resolve()
3636
{
37-
_id = get_uid();
37+
_id = ops.uid();
3838

3939
if (_handle == IntPtr.Zero)
4040
_handle = c_api.TFE_TensorHandleResolve(EagerTensorHandle, tf.status.Handle);
@@ -55,8 +55,5 @@ protected override void DisposeUnmanagedResources(IntPtr handle)
5555
//print($"deleting DeleteTensorHandle {Id} {EagerTensorHandle.ToString("x16")}");
5656
c_api.TFE_DeleteTensorHandle(EagerTensorHandle);
5757
}
58-
59-
static long _uid = 0;
60-
long get_uid() => _uid++;
6158
}
6259
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ namespace Tensorflow.Gradients
2424
/// </summary>
2525
public class GradientTape : IDisposable
2626
{
27-
static bool _recording;
28-
public static bool Recording => _recording;
27+
bool _recording;
28+
public bool Recording => _recording;
2929
bool _persistent;
3030
bool _watch_accessed_variables;
3131
ResourceVariable[] _watched_variables;

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,14 @@ public static int[] OpGradientUnusedInputIndices(string op_name)
1313
"FusedBatchNormGradV3" => new[] { 5 },
1414
"FusedBatchNormV2" => new[] { 2 },
1515
"FusedBatchNormV3" => new[] { 2 },
16+
"ReadVariableOp" => new int[0],
1617
_ => null
1718
};
1819

1920
public static int[] OpGradientUnusedOutputIndices(string op_name)
2021
=> op_name switch
2122
{
23+
"ReadVariableOp" => new int[0],
2224
"SoftmaxCrossEntropyWithLogits" => new[] { 0 },
2325
"TensorArrayConcat" => new[] { 0 },
2426
"TensorArrayConcatV2" => new[] { 0 },

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,22 @@ public static Tensor[] _AddGrad(Operation op, Tensor[] grads)
6464
return new Tensor[] { r1, r2 };
6565
}
6666

67+
/// <summary>
68+
/// Copies the gradient to all inputs.
69+
/// </summary>
70+
/// <param name="op"></param>
71+
/// <param name="grads"></param>
72+
/// <returns></returns>
73+
[RegisterGradient("AddN")]
74+
public static Tensor[] _AddNGrad(Operation op, Tensor[] grads)
75+
{
76+
var grad = grads[0];
77+
78+
return Enumerable.Range(0, len(op.inputs))
79+
.Select(x => grad)
80+
.ToArray();
81+
}
82+
6783
[RegisterGradient("Cumsum")]
6884
public static Tensor[] _CumsumGrad(Operation op, Tensor[] grads)
6985
{

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,13 +124,33 @@ public static Tensor[] concat_offset(Tensor concat_dim, Tensor[] shape, string n
124124
/// </remarks>
125125
public static Tensor diag(Tensor diagonal, string name = null)
126126
{
127+
if (tf.context.executing_eagerly())
128+
{
129+
var results = tf.Runner.TFE_FastPathExecute(tf.context, tf.context.device_name,
130+
"Diag", name,
131+
null,
132+
diagonal);
133+
134+
return results[0];
135+
}
136+
127137
var op = tf._op_def_lib._apply_op_helper("Diag", name: name, args: new { diagonal });
128138

129139
return op.output;
130140
}
131141

132142
public static Tensor expand_dims(Tensor input, int axis, string name = null)
133143
{
144+
if (tf.context.executing_eagerly())
145+
{
146+
var results = tf.Runner.TFE_FastPathExecute(tf.context, tf.context.device_name,
147+
"ExpandDims", name,
148+
null,
149+
input, tf.convert_to_tensor(axis));
150+
151+
return results[0];
152+
}
153+
134154
var _op = tf._op_def_lib._apply_op_helper("ExpandDims", name: name, args: new { input, dim = axis });
135155

136156
return _op.outputs[0];

‎src/TensorFlowNET.Core/Util/SafeTensorflowHandle.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,5 +39,8 @@ private protected SafeTensorflowHandle(IntPtr handle, bool ownsHandle)
3939
}
4040

4141
public override bool IsInvalid => handle == IntPtr.Zero;
42+
43+
public override string ToString()
44+
=> $"0x{handle.ToString("x16")}";
4245
}
4346
}

‎src/TensorFlowNET.Core/Util/UnorderedMap.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ public class UnorderedMap<Tk, Tv> : Dictionary<Tk, Tv>
2828
}
2929

3030
public void push_back(Tk key, Tv value)
31-
=> Add(key, value);
31+
=> this[key] = value;
3232

3333
public void emplace(Tk key, Tv value)
34-
=> Add(key, value);
34+
=> this[key] = value;
3535

3636
public bool find(Tk key)
3737
=> ContainsKey(key);

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

Lines changed: 16 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -22,56 +22,21 @@ namespace Tensorflow
2222
{
2323
public partial class ResourceVariable
2424
{
25-
public static Tensor operator +(ResourceVariable x, int y) => op_helper("add", x, y);
26-
public static Tensor operator +(ResourceVariable x, float y) => op_helper("add", x, y);
27-
public static Tensor operator +(ResourceVariable x, double y) => op_helper("add", x, y);
28-
public static Tensor operator +(ResourceVariable x, ResourceVariable y) => op_helper("add", x, y);
29-
public static Tensor operator -(ResourceVariable x, int y) => op_helper("sub", x, y);
30-
public static Tensor operator -(ResourceVariable x, float y) => op_helper("sub", x, y);
31-
public static Tensor operator -(ResourceVariable x, double y) => op_helper("sub", x, y);
32-
public static Tensor operator -(ResourceVariable x, Tensor y) => op_helper("sub", x, y);
33-
public static Tensor operator -(ResourceVariable x, ResourceVariable y) => op_helper("sub", x, y);
34-
35-
public static Tensor operator *(ResourceVariable x, ResourceVariable y) => op_helper("mul", x, y);
36-
public static Tensor operator *(ResourceVariable x, NDArray y) => op_helper("mul", x, y);
37-
38-
public static Tensor operator <(ResourceVariable x, Tensor y) => op_helper("less", x, y);
39-
40-
public static Tensor operator >(ResourceVariable x, Tensor y) => op_helper("greater", x, y);
41-
42-
private static Tensor op_helper<T>(string default_name, ResourceVariable x, T y)
43-
=> tf_with(ops.name_scope(null, default_name, new { x, y }), scope =>
44-
{
45-
string name = scope;
46-
var xVal = x.value();
47-
var yTensor = ops.convert_to_tensor(y, xVal.dtype.as_base_dtype(), "y");
48-
Tensor result = null;
49-
switch (default_name)
50-
{
51-
case "add":
52-
result = x.dtype == TF_DataType.TF_STRING ?
53-
gen_math_ops.add(xVal, yTensor, name) :
54-
gen_math_ops.add_v2(xVal, yTensor, name);
55-
break;
56-
case "sub":
57-
result = gen_math_ops.sub(xVal, yTensor, name);
58-
break;
59-
case "mul":
60-
result = gen_math_ops.mul(xVal, yTensor, name: name);
61-
break;
62-
case "less":
63-
result = gen_math_ops.less(xVal, yTensor, name);
64-
break;
65-
case "greater":
66-
result = gen_math_ops.greater(xVal, yTensor, name);
67-
break;
68-
default:
69-
throw new NotImplementedException("");
70-
}
71-
72-
// x.assign(result);
73-
// result.ResourceVar = x;
74-
return result;
75-
});
25+
public static Tensor operator +(ResourceVariable x, int y) => x.value() + y;
26+
public static Tensor operator +(ResourceVariable x, float y) => x.value() + y;
27+
public static Tensor operator +(ResourceVariable x, double y) => x.value() + y;
28+
public static Tensor operator +(ResourceVariable x, ResourceVariable y) => x.value() + y.value();
29+
public static Tensor operator -(ResourceVariable x, int y) => x.value() - y;
30+
public static Tensor operator -(ResourceVariable x, float y) => x.value() - y;
31+
public static Tensor operator -(ResourceVariable x, double y) => x.value() - y;
32+
public static Tensor operator -(ResourceVariable x, Tensor y) => x.value() - y;
33+
public static Tensor operator -(ResourceVariable x, ResourceVariable y) => x.value() - y.value();
34+
35+
public static Tensor operator *(ResourceVariable x, ResourceVariable y) => x.value() * y.value();
36+
public static Tensor operator *(ResourceVariable x, NDArray y) => x.value() * y;
37+
38+
public static Tensor operator <(ResourceVariable x, Tensor y) => x.value() < y;
39+
40+
public static Tensor operator >(ResourceVariable x, Tensor y) => x.value() > y;
7641
}
7742
}

‎src/TensorFlowNET.Core/ops.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ public static ITensorFlowObject init_scope2()
277277
return ops.control_dependencies(null);
278278
}
279279

280-
private static int uid_number = 0;
280+
private static int uid_number = -1;
281281

282282
/// <summary>
283283
/// A unique (within this program execution) integer.

0 commit comments

Comments
 (0)