Skip to content

Commit 22d56ab

Browse files
committed
add _pop_tape.
1 parent 6327880 commit 22d56ab

3 files changed

Lines changed: 32 additions & 14 deletions

File tree

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

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,14 @@ private void _push_tape()
4848
_recording = true;
4949
}
5050

51+
private void _pop_tape()
52+
{
53+
if (!_recording)
54+
throw new ValueError("Tape is not recording.");
55+
_tape.pop_tape(_tape);
56+
_recording = false;
57+
}
58+
5159
/// <summary>
5260
/// Marks this tensor to be watched by the given tape.
5361
/// </summary>
@@ -59,12 +67,19 @@ public void watch(Tensor x)
5967

6068
public Tensor gradient(Tensor target, Tensor sources)
6169
{
62-
using (var status = new Status())
70+
if(_recording)
6371
{
64-
c_api.TFE_TapeGradient(_tape, new IntPtr[] { target }, IntPtr.Zero, status);
72+
if (!_persistent)
73+
_pop_tape();
6574
}
66-
67-
return null;
75+
76+
using var status = new Status();
77+
var et = c_api.TFE_TapeGradient(_tape,
78+
new IntPtr[] { (target as EagerTensor).EagerTensorHandle }, 1,
79+
new IntPtr[] { (sources as EagerTensor).EagerTensorHandle }, 1,
80+
status);
81+
status.Check(true);
82+
return et;
6883
}
6984

7085
public void Dispose()

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ public void watch(EagerTensor x)
2020
c_api.TFE_TapeWatch(_handle, x.EagerTensorHandle);
2121
}
2222

23+
public void pop_tape(Tape tape)
24+
{
25+
c_api.TFE_TapeSetRemove(tape);
26+
}
27+
2328
public static bool IsDtypeTrainable(DataType dtype)
2429
{
2530
switch (dtype)

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

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -715,17 +715,15 @@ public static Tensor mul(Tensor x, Tensor y, string name = null)
715715
{
716716
if (tf.context.executing_eagerly())
717717
{
718-
using (var status = new Status())
718+
using var status = new Status();
719+
var _result = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
720+
"Mul", name, new IntPtr[]
719721
{
720-
var _result = c_api.TFE_FastPathExecute(tf.context, tf.context.device_name,
721-
"Mul", name, new IntPtr[]
722-
{
723-
(x as EagerTensor).EagerTensorHandle,
724-
(y as EagerTensor).EagerTensorHandle
725-
}, 2, status);
726-
status.Check(true);
727-
return new EagerTensor(_result);
728-
}
722+
(x as EagerTensor).EagerTensorHandle,
723+
(y as EagerTensor).EagerTensorHandle
724+
}, 2, status);
725+
status.Check(true);
726+
return new EagerTensor(_result);
729727
}
730728

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

0 commit comments

Comments
 (0)