Skip to content

Commit 6556c16

Browse files
committed
Add eager of truncated_normal, tanh and squeeze.
1 parent 784b1eb commit 6556c16

12 files changed

Lines changed: 169 additions & 36 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ public Tensor slice<Tb, Ts>(Tensor input, Tb[] begin, Ts[] size, string name = n
186186
=> array_ops.slice(input, begin, size, name: name);
187187

188188
public Tensor squeeze(Tensor input, int[] axis = null, string name = null, int squeeze_dims = -1)
189-
=> gen_array_ops.squeeze(input, axis, name);
189+
=> array_ops.squeeze(input, axis, name);
190190

191191
/// <summary>
192192
/// Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor.

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,24 @@ public Tensor normal(TensorShape shape,
3838
TF_DataType dtype = TF_DataType.TF_FLOAT,
3939
int? seed = null,
4040
string name = null) => random_ops.random_normal(shape, mean, stddev, dtype, seed, name);
41+
42+
/// <summary>
43+
/// Outputs random values from a truncated normal distribution.
44+
/// </summary>
45+
/// <param name="shape"></param>
46+
/// <param name="mean"></param>
47+
/// <param name="stddev"></param>
48+
/// <param name="dtype"></param>
49+
/// <param name="seed"></param>
50+
/// <param name="name"></param>
51+
/// <returns></returns>
52+
public Tensor truncated_normal(TensorShape shape,
53+
float mean = 0.0f,
54+
float stddev = 1.0f,
55+
TF_DataType dtype = TF_DataType.TF_FLOAT,
56+
int? seed = null,
57+
string name = null) => random_ops.truncated_normal(shape, mean, stddev, dtype, seed, name);
58+
4159
public Tensor categorical(
4260
Tensor logits,
4361
int num_samples,

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

Lines changed: 47 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,37 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Linq;
34
using System.Text;
5+
using static Tensorflow.Binding;
46

57
namespace Tensorflow.Eager
68
{
79
public class EagerOperation : Operation
810
{
9-
public int NumInputs;
11+
static Dictionary<string, OpDef> op_dict;
12+
public string Name { get; set; }
13+
public new int NumInputs;
1014
public IntPtr[] InputHandles { get; set; }
1115
public Tensor[] Inputs { get; set; }
12-
public int NumOutputs;
16+
public new int NumOutputs;
1317
public IntPtr[] OutputHandles { get; set; }
1418
public Tensor[] Outputs { get; set; }
15-
public int[] SkipInputIndices { get; set; }
19+
public BindingArray SkipInputIndicesArray { get; set; }
20+
public unsafe int[] SkipInputIndices => SkipInputIndicesArray.Data.Select(x => *(int*) x).ToArray();
21+
public BindingArray AttrsArray { get; set; }
1622

17-
public EagerOperation() : base(IntPtr.Zero) { }
23+
public EagerOperation() : base(IntPtr.Zero)
24+
{
25+
if (op_dict == null)
26+
op_dict = op_def_registry.get_registered_ops();
27+
}
1828

1929
public override InputList inputs
2030
{
2131
get
2232
{
2333
if (_inputs_val == null)
2434
{
25-
var retval = new Tensor[NumInputs];
26-
27-
for (int i = 0; i < NumInputs; i++)
28-
{
29-
30-
}
31-
3235
_inputs_val = new InputList(Inputs);
3336
}
3437

@@ -48,5 +51,38 @@ public override Tensor[] outputs
4851
return _outputs;
4952
}
5053
}
54+
55+
public override object get_attr(string attr_name)
56+
{
57+
object value = null;
58+
byte isList = 0;
59+
using var status = new Status();
60+
var attrType = c_api.TFE_OpNameGetAttrType(tf.context, Name, attr_name, ref isList, status);
61+
switch (attrType)
62+
{
63+
case TF_AttrType.TF_ATTR_BOOL:
64+
value = get_attr_bool(attr_name);
65+
break;
66+
default:
67+
break;
68+
}
69+
70+
return value;
71+
}
72+
73+
public bool get_attr_bool(string attr_name)
74+
{
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+
}
81+
82+
throw new ValueError($"Can't find attr: {attr_name}");
83+
}
84+
85+
public override string ToString()
86+
=> $"tf.EagerOperation {Name}";
5187
}
5288
}

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

Lines changed: 4 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-
int num_attrs,
28+
IntPtr attrs_handle,
2929
IntPtr output_grads,
3030
IntPtr skip_input_indices);
3131

@@ -72,6 +72,9 @@ public delegate void delete_backward_function_callback(string op_name,
7272
[DllImport(TensorFlowLibName)]
7373
public static extern TF_AttrType TFE_OpGetAttrType(IntPtr op, string attr_name, ref byte is_list, IntPtr status);
7474

75+
[DllImport(TensorFlowLibName)]
76+
public static extern TF_AttrType TFE_OpNameGetAttrType(IntPtr ct, string op_or_function_name, string attr_name, ref byte is_list, IntPtr status);
77+
7578
/// <summary>
7679
/// Returns the length (number of tensors) of the input argument `input_name`
7780
/// found in the provided `op`.

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

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using Google.Protobuf.WellKnownTypes;
2+
using NumSharp.Utilities;
23
using System;
34
using System.Collections.Generic;
45
using System.Linq;
@@ -72,40 +73,43 @@ public void watch(Tensor x)
7273

7374
public Tensor gradient(Tensor target, Tensor source)
7475
{
75-
if(_recording)
76+
if (_recording)
7677
{
7778
if (!_persistent)
7879
_pop_tape();
7980
}
8081

8182
var results = new[] { new EagerTensor() };
8283
Status status = c_api.TFE_TapeGradient(_tape,
83-
new [] { (target as EagerTensor).EagerTensorHandle }, 1,
84-
new [] { (source as EagerTensor).EagerTensorHandle }, 1,
84+
new[] { (target as EagerTensor).EagerTensorHandle }, 1,
85+
new[] { (source as EagerTensor).EagerTensorHandle }, 1,
8586
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
8687
status.Check(true);
8788
return results[0].Resolve();
8889
}
8990

90-
public unsafe (Tensor, Tensor) gradient(Tensor target, (ResourceVariable, ResourceVariable) sources)
91+
public (Tensor, Tensor) gradient(Tensor target, (ResourceVariable, ResourceVariable) sources)
92+
{
93+
var results = gradient(target as EagerTensor, new[] { sources.Item1, sources.Item2 });
94+
95+
return (results[0], results[1]);
96+
}
97+
98+
public EagerTensor[] gradient(EagerTensor target, ResourceVariable[] sources)
9199
{
92100
if (_recording)
93101
{
94102
if (!_persistent)
95103
_pop_tape();
96104
}
97105

98-
var results = new[] { new EagerTensor(), new EagerTensor() };
106+
var results = sources.Select(x => new EagerTensor()).ToArray();
99107
Status status = c_api.TFE_TapeGradient(_tape,
100-
new IntPtr[]
101-
{
102-
target as EagerTensor
108+
new IntPtr[]
109+
{
110+
target.EagerTensorHandle
103111
}, 1,
104-
new IntPtr[]
105-
{
106-
(sources.Item1.Handle as EagerTensor).EagerTensorHandle,
107-
(sources.Item2.Handle as EagerTensor).EagerTensorHandle
108-
}, 2,
112+
sources.Select(x => (x.Handle as EagerTensor).EagerTensorHandle).ToArray(), sources.Length,
109113
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
110114
status.Check(true);
111115

@@ -116,7 +120,7 @@ target as EagerTensor
116120
_tape = null;
117121
}
118122

119-
return (results[0].Resolve(), results[1].Resolve());
123+
return results.Select(x => x.Resolve()).ToArray();
120124
}
121125

122126
public void Dispose()

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -497,8 +497,8 @@ public static Tensor[] _SumGrad(Operation op, Tensor[] grads)
497497
if (tf.context.executing_eagerly())
498498
{
499499
// should add ones_rank_cache
500-
var new_shape_tensor = constant_op.constant(np.array(new int[] { 1 }) * rank, dtype: TF_DataType.TF_INT32);
501-
grad = array_ops.reshape(grad, new_shape_tensor);
500+
var new_shape = constant_op.constant(range(0, rank).Select(x => 1).ToArray(), dtype: TF_DataType.TF_INT32);
501+
grad = array_ops.reshape(grad, new_shape);
502502
}
503503
else
504504
{

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,13 @@ public OptimizerV2() : base()
3636
apply_state = new Dictionary<DeviceDType, Dictionary<string, Tensor>>();
3737
}
3838

39+
public void apply_gradients((Tensor, ResourceVariable) grads_and_vars,
40+
string name = null,
41+
bool experimental_aggregate_gradients = true)
42+
=> apply_gradients(new (Tensor, ResourceVariable)[] { grads_and_vars },
43+
name: name,
44+
experimental_aggregate_gradients: experimental_aggregate_gradients);
45+
3946
/// <summary>
4047
/// Apply gradients to variables.
4148
/// </summary>

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public partial class Operation : ITensorOrOperation
5757
public int _id_value { get; set; }
5858
public Operation op => this;
5959
public TF_DataType dtype => TF_DataType.DtInvalid;
60-
public string name => _handle == IntPtr.Zero ? null : c_api.StringPiece(c_api.TF_OperationName(_handle));
60+
public virtual string name => _handle == IntPtr.Zero ? null : c_api.StringPiece(c_api.TF_OperationName(_handle));
6161
public string OpType => _handle == IntPtr.Zero ? null : c_api.StringPiece(c_api.TF_OperationOpType(_handle));
6262

6363
public string Device => _handle == IntPtr.Zero ? null : c_api.StringPiece(c_api.TF_OperationDevice(_handle));
@@ -228,7 +228,7 @@ private object[] _reconstruct_sequence_inputs(OpDef op_def, Tensor[] inputs, Map
228228
public T get_attr<T>(string name)
229229
=> (T)get_attr(name);
230230

231-
public object get_attr(string name)
231+
public virtual object get_attr(string name)
232232
{
233233
AttrValue x = null;
234234

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,21 @@ public static Tensor slice<Tb, Ts>(Tensor input, Tb begin, Ts size, string name
645645
/// <returns> A `Tensor`. Has the same type as `input`.</returns>
646646
public static Tensor squeeze(Tensor input, int[] axis = null, string name = null)
647647
{
648+
if (tf.context.executing_eagerly())
649+
{
650+
var results = new[] { new EagerTensor() };
651+
Status status = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
652+
"Squeeze", name, new IntPtr[]
653+
{
654+
input as EagerTensor
655+
}, 1,
656+
op => wrap_tfe_src.SetOpAttrs(op,
657+
"squeeze_dims", axis),
658+
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
659+
status.Check(true);
660+
return results[0].Resolve();
661+
}
662+
648663
if (axis == null) axis = new int[0];
649664
var _op = _op_def_lib._apply_op_helper("Squeeze", name, args: new { input, squeeze_dims = axis });
650665

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

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,19 @@ public static Tensor tan(Tensor x, string name = null)
464464

465465
public static Tensor tanh(Tensor x, string name = null)
466466
{
467+
if (tf.context.executing_eagerly())
468+
{
469+
var results = new[] { new EagerTensor() };
470+
Status status = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
471+
"Tanh", name, new IntPtr[]
472+
{
473+
x as EagerTensor,
474+
}, 1, null,
475+
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
476+
status.Check(true);
477+
return results[0].Resolve();
478+
}
479+
467480
var _op = _op_def_lib._apply_op_helper("Tanh", name, args: new { x });
468481

469482
return _op.outputs[0];
@@ -477,7 +490,24 @@ public static Tensor tanh(Tensor x, string name = null)
477490
/// <param name="name"></param>
478491
/// <returns></returns>
479492
public static Tensor tanh_grad(Tensor y, Tensor dy, string name = null)
480-
=> _op_def_lib._apply_op_helper("TanhGrad", name: name, args: new { y, dy }).output;
493+
{
494+
if (tf.context.executing_eagerly())
495+
{
496+
var results = new[] { new EagerTensor() };
497+
Status status = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
498+
"TanhGrad", name, new IntPtr[]
499+
{
500+
y as EagerTensor,
501+
dy as EagerTensor
502+
}, 2, null,
503+
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
504+
status.Check(true);
505+
return results[0].Resolve();
506+
}
507+
508+
var _op = _op_def_lib._apply_op_helper("TanhGrad", name: name, args: new { y, dy }).output;
509+
return _op.outputs[0];
510+
}
481511

482512
public static Tensor floor(Tensor x, string name = null)
483513
{

0 commit comments

Comments
 (0)