Skip to content

Commit e266030

Browse files
committed
fix _SumGrad, broadcast_gradient_args and real_div.
1 parent ca6f8b2 commit e266030

7 files changed

Lines changed: 99 additions & 11 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
@@ -11,7 +11,7 @@ public partial class c_api
1111
public static extern void TFE_RegisterGradientFunction(_gradient_function_callback callbackPointer);
1212

1313
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
14-
public delegate IntPtr _gradient_function_callback(string op_name, int num_inputs, IntPtr[] op_inputs, int num_attrs, IntPtr[] output_grads);
14+
public delegate IntPtr _gradient_function_callback(string op_name, int num_inputs, IntPtr op_inputs, int num_attrs, int num_outputs, IntPtr output_grads);
1515

1616
[DllImport(TensorFlowLibName)]
1717
public static extern IntPtr VSpace_Handle(VSpace_callback_Ones ones, VSpace_callback_AggregateGrads aggregate_grads);

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

Lines changed: 25 additions & 2 deletions
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 NumSharp;
1718
using System;
1819
using System.Linq;
1920
using Tensorflow.Operations;
@@ -438,8 +439,18 @@ public static Tensor[] _SumGrad(Operation op, Tensor[] grads)
438439
var rank = input_0_shape.Length;
439440
if (Enumerable.SequenceEqual(Enumerable.Range(0, rank), axes.Data<int>()))
440441
{
441-
var new_shape = range(rank).Select(x => 1).ToArray();
442-
grad = array_ops.reshape(grad, new_shape);
442+
if (tf.context.executing_eagerly())
443+
{
444+
// should add ones_rank_cache
445+
var new_shape_tensor = constant_op.constant(np.array(new int[] { 1 }) * rank, dtype: TF_DataType.TF_INT32);
446+
grad = array_ops.reshape(grad, new_shape_tensor);
447+
}
448+
else
449+
{
450+
var new_shape = range(rank).Select(x => 1).ToArray();
451+
grad = array_ops.reshape(grad, new_shape);
452+
}
453+
443454
// If shape is not fully defined (but rank is), we use Shape.
444455
if (!input_0_shape.Contains(-1))
445456
input_shape = constant_op.constant(input_0_shape);
@@ -605,6 +616,18 @@ public static Tensor[] _PowGrad(Operation op, Tensor[] grads)
605616
var grad = grads[0];
606617
var x = op.inputs[0];
607618
var y = op.inputs[1];
619+
620+
if (tf.context.executing_eagerly())
621+
{
622+
x = math_ops.conj(x);
623+
y = math_ops.conj(y);
624+
return new Tensor[]
625+
{
626+
grad * y * math_ops.pow(x, y - 1),
627+
null
628+
};
629+
}
630+
608631
var z = op.outputs[0];
609632

610633
var (sx, sy) = SmartBroadcastGradientArgs(x, y);
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*****************************************************************************
2+
Copyright 2020 The TensorFlow.NET Authors. All Rights Reserved.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
******************************************************************************/
16+
17+
using System;
18+
using System.Collections.Generic;
19+
using System.Text;
20+
21+
namespace Tensorflow.Gradients
22+
{
23+
[RegisterGradient("resource_variable_grad")]
24+
public class resource_variable_grad
25+
{
26+
[RegisterGradient("ReadVariableOp")]
27+
public static Tensor[] _ReadGrad(Operation op, Tensor[] grads)
28+
{
29+
return new Tensor[] { grads[0] };
30+
}
31+
}
32+
}

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

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ value as EagerTensor
291291
/// <param name="s1">A `Tensor`. Must have the same type as `s0`.</param>
292292
/// <param name="name">A name for the operation (optional).</param>
293293
/// <returns>A tuple of `Tensor` objects (r0, r1).</returns>
294-
public static (Tensor, Tensor) broadcast_gradient_args(Tensor s0, Tensor s1, string name = "")
294+
public unsafe static (Tensor, Tensor) broadcast_gradient_args(Tensor s0, Tensor s1, string name = "")
295295
{
296296
if (tf.context.executing_eagerly())
297297
{
@@ -303,6 +303,7 @@ public static (Tensor, Tensor) broadcast_gradient_args(Tensor s0, Tensor s1, str
303303
s1 as EagerTensor
304304
}, 2, null, status);
305305
status.Check(true);
306+
return (new EagerTensor(*(IntPtr*)_result), new EagerTensor(*((IntPtr*)_result + 1)));
306307
}
307308

308309
var _op = _op_def_lib._apply_op_helper("BroadcastGradientArgs", name, new { s0, s1 });
@@ -318,6 +319,19 @@ public static Tensor reverse<T>(Tensor tensor, T axis, string name = null)
318319

319320
public static Tensor reshape<T1, T2>(T1 tensor, T2 shape, string name = null)
320321
{
322+
if (tf.context.executing_eagerly())
323+
{
324+
using var status = new Status();
325+
EagerTensorHandle _result = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
326+
"Reshape", name, new IntPtr[]
327+
{
328+
tensor as EagerTensor,
329+
shape as EagerTensor
330+
}, 2, null, status);
331+
status.Check(true);
332+
return _result;
333+
}
334+
321335
var _op = _op_def_lib._apply_op_helper("Reshape", name, new { tensor, shape });
322336
return _op.output;
323337
}
@@ -455,6 +469,19 @@ public static Tensor[] split(Tensor axis, Tensor value, int num_split, string na
455469

456470
public static Tensor tile<T>(Tensor input, T multiples, string name = null)
457471
{
472+
if (tf.context.executing_eagerly())
473+
{
474+
using var status = new Status();
475+
EagerTensorHandle tensor = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
476+
"Tile", name, new IntPtr[]
477+
{
478+
input as EagerTensor,
479+
multiples as EagerTensor
480+
}, 2, null, status);
481+
status.Check(true);
482+
return tensor;
483+
}
484+
458485
var _op = _op_def_lib._apply_op_helper("Tile", name, new { input, multiples });
459486
return _op.outputs[0];
460487
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -843,14 +843,14 @@ public static Tensor real_div(Tensor x, Tensor y, string name = null)
843843
if (tf.context.executing_eagerly())
844844
{
845845
using var status = new Status();
846-
var _result = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
846+
EagerTensorHandle tensor = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
847847
"RealDiv", name, new IntPtr[]
848848
{
849849
x as EagerTensor,
850850
y as EagerTensor
851851
}, 2, null, status);
852852
status.Check(true);
853-
return new EagerTensor(_result);
853+
return tensor;
854854
}
855855

856856
var _op = _op_def_lib._apply_op_helper("RealDiv", name, args: new { x, y });

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ limitations under the License.
1919
using System.Linq;
2020
using NumSharp.Utilities;
2121
using System.Text;
22+
using Tensorflow.Eager;
2223

2324
namespace Tensorflow
2425
{
@@ -39,6 +40,9 @@ public static class tensor_util
3940
/// <returns></returns>
4041
public static NDArray constant_value(Tensor tensor, bool partial = false)
4142
{
43+
if (tensor is EagerTensor)
44+
return tensor.numpy();
45+
4246
NDArray ret = _ConstantValue(tensor, partial);
4347
if (!(ret is null))
4448
tensor.graph.prevent_feeding(tensor);

‎src/TensorFlowNET.Core/tensorflow.cs‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,13 +62,15 @@ private unsafe void InitGradientEnvironment()
6262
});
6363

6464
ops.RegisterFromAssembly();
65-
c_api.TFE_RegisterGradientFunction((op_name, num_inputs, op_inputs, num_attrs, output_grads) =>
65+
c_api.TFE_RegisterGradientFunction((op_name, num_inputs, op_inputs, num_attrs, num_outputs, output_grads) =>
6666
{
67-
var output_grad_tensors = output_grads.Select(x => new EagerTensor(x)).ToArray();
68-
6967
var input_tensors = new EagerTensor[num_inputs];
7068
for (int i = 0; i < num_inputs; i++)
71-
input_tensors[i] = new EagerTensor(op_inputs[op_inputs.Length == 1 ? 0 : i]);
69+
input_tensors[i] = new EagerTensor(*((IntPtr*)op_inputs + i));
70+
71+
var output_grad_tensors = new EagerTensor[num_outputs];
72+
for (int i = 0; i < num_outputs; i++)
73+
output_grad_tensors[i] = new EagerTensor(*((IntPtr*)output_grads + i));
7274

7375
var gradients = ops.gradientFunctions[op_name](new EagerOperation
7476
{
@@ -77,7 +79,7 @@ private unsafe void InitGradientEnvironment()
7779
}, output_grad_tensors);
7880

7981
var ret_tensors = Marshal.AllocHGlobal(sizeof(IntPtr) * num_inputs);
80-
Marshal.Copy(gradients.Select(x => (x as EagerTensor).EagerTensorHandle).ToArray(), 0, ret_tensors, 2);
82+
Marshal.Copy(gradients.Select(x => x == null ? IntPtr.Zero : (x as EagerTensor).EagerTensorHandle).ToArray(), 0, ret_tensors, 2);
8183
// Marshal.FreeHGlobal(ret_tensors);
8284
return ret_tensors;
8385
});

0 commit comments

Comments
 (0)