Skip to content

Commit c078ef6

Browse files
committed
add EagerTensorPass and TensorManager.
1 parent 6556c16 commit c078ef6

32 files changed

Lines changed: 646 additions & 184 deletions

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ public Tensor one_hot(Tensor indices, int depth,
217217
Tensor off_value = null,
218218
TF_DataType dtype = TF_DataType.DtInvalid,
219219
int axis = -1,
220-
string name = null) => array_ops.one_hot(indices, depth, dtype: dtype, axis: axis, name: name);
220+
string name = null) => array_ops.one_hot(indices, ops.convert_to_tensor(depth), dtype: dtype, axis: axis, name: name);
221221

222222
/// <summary>
223223
/// Pads a tensor

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ namespace Tensorflow
2121
{
2222
public partial class tensorflow
2323
{
24+
public MathApi math { get; } = new MathApi();
25+
public class MathApi
26+
{
27+
public Tensor log(Tensor x, string name = null)
28+
=> gen_math_ops.log(x, name);
29+
}
30+
2431
public Tensor abs(Tensor x, string name = null)
2532
=> math_ops.abs(x, name);
2633

@@ -254,7 +261,7 @@ public Tensor _clip_by_value(Tensor t, Tensor clip_value_min, Tensor clip_value_
254261
/// Any values less than <c>clip_value_min</c> are set to <c>clip_value_min</c>. Any values
255262
/// greater than <c>clip_value_max</c> are set to <c>clip_value_max</c>.
256263
/// </remarks>
257-
public Tensor clip_by_value (Tensor t, Tensor clip_value_min, Tensor clip_value_max, string name = "ClipByValue")
264+
public Tensor clip_by_value<T1, T2>(Tensor t, T1 clip_value_min, T2 clip_value_max, string name = "ClipByValue")
258265
=> clip_ops.clip_by_value(t, clip_value_min, clip_value_max, name);
259266

260267
public Tensor sub<Tx, Ty>(Tx a, Ty b, string name = null)

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

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

17+
using System;
1718
using Tensorflow.Operations;
1819
using Tensorflow.Operations.Activation;
1920
using static Tensorflow.Binding;
@@ -182,7 +183,13 @@ public Tensor sigmoid_cross_entropy_with_logits(Tensor labels, Tensor logits, st
182183
=> nn_impl.sigmoid_cross_entropy_with_logits(labels: labels, logits: logits, name: name);
183184

184185
public Tensor softmax(Tensor logits, int axis = -1, string name = null)
185-
=> gen_nn_ops.softmax(logits, name);
186+
{
187+
if (axis == -1)
188+
return gen_nn_ops.softmax(logits, name);
189+
else
190+
throw new NotImplementedException("");
191+
}
192+
186193

187194
/// <summary>
188195
/// Computes sparse softmax cross entropy between `logits` and `labels`.

‎src/TensorFlowNET.Core/Eager/EagerOperation.cs‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public class EagerOperation : Operation
1818
public Tensor[] Outputs { get; set; }
1919
public BindingArray SkipInputIndicesArray { get; set; }
2020
public unsafe int[] SkipInputIndices => SkipInputIndicesArray.Data.Select(x => *(int*) x).ToArray();
21-
public BindingArray AttrsArray { get; set; }
21+
public string[] AttrsArray { get; set; }
2222

2323
public EagerOperation() : base(IntPtr.Zero)
2424
{
@@ -70,14 +70,11 @@ public override object get_attr(string attr_name)
7070
return value;
7171
}
7272

73-
public bool get_attr_bool(string attr_name)
73+
public bool get_attr_bool(string attr_name)
7474
{
75-
for (int i = 0; i < AttrsArray.Data.Length; i = i + 2)
76-
{
77-
// var a = *(char*)AttrsArray.Data[i];
78-
if (op_dict[Name].Attr[i].Name == attr_name)
79-
return (int)AttrsArray.Data[i + 1] == 1;
80-
}
75+
for (int i = 0; i < AttrsArray.Length; i = i + 2)
76+
if (AttrsArray[i] == attr_name)
77+
return AttrsArray[i + 1] == "1";
8178

8279
throw new ValueError($"Can't find attr: {attr_name}");
8380
}

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using System;
33
using System.Collections.Generic;
44
using System.Text;
5+
using System.Threading;
56
using static Tensorflow.Binding;
67

78
namespace Tensorflow.Eager
@@ -49,13 +50,20 @@ public EagerTensor Resolve()
4950
print($"new TensorHandle {Id} {tfe_tensor_handle.ToString("x16")}");
5051
print($"new EagerTensor {Id} {EagerTensorHandle.ToString("x16")}");*/
5152

53+
if (tfe_tensor_handle == IntPtr.Zero && _id == 0)
54+
{
55+
}
56+
5257
GarbageCollector.Increase(_handle, GCItemType.TensorHandle);
5358
GarbageCollector.Increase(tfe_tensor_handle, GCItemType.LocalTensorHandle);
5459
GarbageCollector.Increase(EagerTensorHandle, GCItemType.EagerTensorHandle);
5560

5661
return this;
5762
}
5863

64+
public override IntPtr ToPointer()
65+
=> EagerTensorHandle;
66+
5967
protected override void DisposeUnmanagedResources(IntPtr handle)
6068
{
6169
GarbageCollector.Decrease(_handle);

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public partial class EagerTensor : Tensor
1313
public IntPtr EagerTensorHandle { get; set; }
1414
public override string Device => c_api.StringPiece(c_api.TFE_TensorHandleDeviceName(tfe_tensor_handle, status));
1515

16-
// public override int rank => c_api.TFE_TensorHandleNumDims(tfe_tensor_handle, status);
16+
public override int rank => c_api.TFE_TensorHandleNumDims(tfe_tensor_handle, status);
1717

1818
public static int GetRank(IntPtr handle)
1919
{

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public static extern void TFE_RegisterGradientFunction(gradient_function_callbac
2525
public delegate IntPtr gradient_function_callback(string op_name,
2626
IntPtr op_inputs,
2727
IntPtr op_outputs,
28-
IntPtr attrs_handle,
28+
string attrs_string,
2929
IntPtr output_grads,
3030
IntPtr skip_input_indices);
3131

@@ -402,6 +402,7 @@ public static extern IntPtr TFE_FastPathExecute(IntPtr ctx,
402402
string name,
403403
IntPtr[] inputs,
404404
int input_size,
405+
string attrs_string,
405406
TFE_FastPathExecute_SetOpAttrs set_op_attrs,
406407
IntPtr[] outputs,
407408
int output_size);

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,37 @@ public static void SetOpAttrs(TFE_Op op, params object[] attrs)
3131
}
3232
}
3333

34+
public static string SetOpAttrs2(params object[] attrs)
35+
{
36+
string attr_string = string.Empty;
37+
for(int i = 0; i < attrs.Length; i = i + 2)
38+
{
39+
object key = attrs[i];
40+
object value = attrs[i + 1];
41+
42+
switch (value)
43+
{
44+
case TF_DataType dtype:
45+
value = (int)dtype;
46+
break;
47+
case bool bVal:
48+
value = bVal ? 1 : 0;
49+
break;
50+
case int[] shape:
51+
value = shape.Length == 0 ? "null" : string.Join(" ", shape);
52+
break;
53+
default:
54+
break;
55+
}
56+
57+
attr_string += string.IsNullOrEmpty(attr_string) ?
58+
$"{key},{value}" :
59+
$",{key},{value}";
60+
}
61+
62+
return attr_string;
63+
}
64+
3465
/// <summary>
3566
/// This function will set the op attrs required. If an attr has the value of
3667
/// None, then it will read the AttrDef to get the default value and set that

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

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System;
44
using System.Collections.Generic;
55
using System.Linq;
6+
using System.Reflection;
67
using System.Runtime.InteropServices;
78
using System.Text;
89
using Tensorflow.Eager;
@@ -79,15 +80,26 @@ public Tensor gradient(Tensor target, Tensor source)
7980
_pop_tape();
8081
}
8182

82-
var results = new[] { new EagerTensor() };
83+
var results = EagerTensorPass.Create();
84+
var targets = EagerTensorPass.From(target);
85+
var sources = EagerTensorPass.From(source);
86+
8387
Status status = c_api.TFE_TapeGradient(_tape,
84-
new[] { (target as EagerTensor).EagerTensorHandle }, 1,
85-
new[] { (source as EagerTensor).EagerTensorHandle }, 1,
86-
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
88+
targets.Points, targets.Length,
89+
sources.Points, sources.Length,
90+
results.Points, results.Length);
8791
status.Check(true);
92+
8893
return results[0].Resolve();
8994
}
9095

96+
public Tensor gradient(Tensor target, ResourceVariable source)
97+
{
98+
var results = gradient(target as EagerTensor, new[] { source });
99+
100+
return results[0];
101+
}
102+
91103
public (Tensor, Tensor) gradient(Tensor target, (ResourceVariable, ResourceVariable) sources)
92104
{
93105
var results = gradient(target as EagerTensor, new[] { sources.Item1, sources.Item2 });
@@ -103,14 +115,14 @@ public EagerTensor[] gradient(EagerTensor target, ResourceVariable[] sources)
103115
_pop_tape();
104116
}
105117

106-
var results = sources.Select(x => new EagerTensor()).ToArray();
118+
var results = EagerTensorPass.Create(sources.Length);
119+
var target_inputs = EagerTensorPass.From(target);
120+
var source_inputs = EagerTensorPass.From(sources.Select(x => x.Handle).ToArray());
121+
107122
Status status = c_api.TFE_TapeGradient(_tape,
108-
new IntPtr[]
109-
{
110-
target.EagerTensorHandle
111-
}, 1,
112-
sources.Select(x => (x.Handle as EagerTensor).EagerTensorHandle).ToArray(), sources.Length,
113-
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
123+
target_inputs.Points, target_inputs.Length,
124+
source_inputs.Points, source_inputs.Length,
125+
results.Points, results.Length);
114126
status.Check(true);
115127

116128
if (!_persistent)
@@ -120,13 +132,15 @@ public EagerTensor[] gradient(EagerTensor target, ResourceVariable[] sources)
120132
_tape = null;
121133
}
122134

123-
return results.Select(x => x.Resolve()).ToArray();
135+
return results.Items.Select(x => x.Resolve()).ToArray();
124136
}
125137

126138
public void Dispose()
127139
{
128140
if (_recording)
129141
_pop_tape();
142+
143+
tf.tensorMgr.Reset();
130144
}
131145
}
132146
}

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

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -310,23 +310,26 @@ public static Tensor[] _MeanGrad(Operation op, Tensor[] grads)
310310
var input_shape = op.inputs[0]._shape_tuple();
311311
var output_shape = op.outputs[0]._shape_tuple();
312312

313+
Tensor result, factor_tensor;
313314
if(input_shape != null &&
314315
output_shape != null)
315316
{
316317
var input_size = np.prod(input_shape);
317318
var output_size = np.prod(output_shape);
318319
var factor = (int)input_size / Math.Max((int)output_size, 1);
319-
var factor_tensor = constant_op.constant((int)input_size, dtype: sum_grad.dtype);
320-
return new Tensor[] { math_ops.truediv(sum_grad, math_ops.cast(factor_tensor, sum_grad.dtype)), null };
320+
factor_tensor = constant_op.constant(factor, dtype: sum_grad.dtype);
321321
}
322322
else
323323
{
324324
var input_shape_tensor = array_ops.shape(op.inputs[0]);
325325
var output_shape_tensor = array_ops.shape(op.outputs[0]);
326326
var factor = _safe_shape_div(math_ops.reduce_prod(input_shape_tensor), math_ops.reduce_prod(output_shape_tensor));
327-
328-
return new Tensor[] { math_ops.truediv(sum_grad, math_ops.cast(factor, sum_grad.dtype)), null };
327+
throw new NotImplementedException("");
328+
factor_tensor = null;
329329
}
330+
331+
result = math_ops.truediv(sum_grad, math_ops.cast(factor_tensor, sum_grad.dtype));
332+
return new Tensor[] { result, null };
330333
}
331334

332335
/// <summary>
@@ -513,20 +516,23 @@ public static Tensor[] _SumGrad(Operation op, Tensor[] grads)
513516
input_shape = array_ops.shape(op.inputs[0]);
514517
return new Tensor[] { gen_array_ops.tile(grad, input_shape), null };
515518
}
516-
else
519+
else if (!input_0_shape.Contains(-1) && !tf.context.executing_eagerly())
517520
{
518-
521+
throw new NotImplementedException("");
519522
}
520523
}
521524
}
522525

523526
input_shape = array_ops.shape(op.inputs[0]);
524-
ops.colocate_with(input_shape);
525-
var output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]);
526-
var tile_scaling = _safe_shape_div(input_shape, output_shape_kept_dims);
527-
grad = gen_array_ops.reshape(grad, output_shape_kept_dims);
527+
if (!op.get_attr<bool>("keep_dims"))
528+
{
529+
ops.colocate_with(input_shape);
530+
var output_shape_kept_dims = math_ops.reduced_shape(input_shape, op.inputs[1]);
531+
// var tile_scaling = _safe_shape_div(input_shape, output_shape_kept_dims);
532+
grad = gen_array_ops.reshape(grad, output_shape_kept_dims);
533+
}
528534

529-
return new Tensor[] { gen_array_ops.tile(grad, tile_scaling), null };
535+
return new Tensor[] { gen_array_ops.broadcast_to(grad, input_shape), null };
530536
}
531537

532538
[RegisterGradient("RealDiv")]

0 commit comments

Comments
 (0)