Skip to content

Commit 4a74d8d

Browse files
committed
add a GarbageCollector to address cross-runtime GC issue.
1 parent 6c83176 commit 4a74d8d

34 files changed

Lines changed: 960 additions & 324 deletions

‎src/TensorFlowNET.Console/MemoryLeakTesting.cs‎

Lines changed: 0 additions & 42 deletions
This file was deleted.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Diagnostics;
4+
using System.Text;
5+
using static Tensorflow.Binding;
6+
7+
namespace Tensorflow
8+
{
9+
public class MemoryMonitor
10+
{
11+
public void WarmUp()
12+
{
13+
print(tf.VERSION);
14+
}
15+
16+
public void Execute(int epoch, int iterate, Action<int> process)
17+
{
18+
/*GC.Collect();
19+
GC.WaitForPendingFinalizers();
20+
GC.Collect();*/
21+
22+
print($"{process.Method.Name} started...");
23+
for (int i = 0; i < epoch; i++)
24+
{
25+
var initialMemory = Process.GetCurrentProcess().PrivateMemorySize64;// GC.GetTotalMemory(true);
26+
process(iterate);
27+
var finalMemory = Process.GetCurrentProcess().PrivateMemorySize64; //GC.GetTotalMemory(true);
28+
print($"Epoch {i}: {Format(finalMemory - initialMemory)}.");
29+
}
30+
31+
GC.Collect();
32+
GC.WaitForPendingFinalizers();
33+
GC.Collect();
34+
35+
print($"Total {process.Method.Name} usage {Format(Process.GetCurrentProcess().PrivateMemorySize64)}");
36+
}
37+
38+
private string Format(long usage)
39+
{
40+
if (usage < 0)
41+
return $"-{Format(0 - usage)}";
42+
43+
if (usage <= 1024 && usage >= 0)
44+
return $"{usage} Bytes";
45+
else if (usage > 1024 && usage <= 1024 * 1024)
46+
return $"{usage / 1024} KB";
47+
else
48+
return $"{usage / 1024 / 1024} MB";
49+
}
50+
}
51+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
using static Tensorflow.Binding;
5+
6+
namespace Tensorflow
7+
{
8+
class MemoryTestingCases
9+
{
10+
/// <summary>
11+
///
12+
/// </summary>
13+
public Action<int> Constant
14+
=> (iterate) =>
15+
{
16+
for (int i = 0; i < iterate; i++)
17+
{
18+
var tensor = tf.constant(3112.0f);
19+
}
20+
};
21+
public Action<int> Variable
22+
=> (iterate) =>
23+
{
24+
for (int i = 0; i < iterate; i++)
25+
{
26+
var tensor = tf.Variable(3112.0f);
27+
}
28+
};
29+
30+
public Action<int> MathAdd
31+
=> (iterate) =>
32+
{
33+
var x = tf.constant(3112.0f);
34+
var y = tf.constant(3112.0f);
35+
36+
for (int i = 0; i < iterate; i++)
37+
{
38+
var z = x + y;
39+
}
40+
};
41+
42+
public Action<int> Gradient
43+
=> (iterate) =>
44+
{
45+
for(int i = 0; i< iterate; i++)
46+
{
47+
var w = tf.constant(3112.0f);
48+
using var tape = tf.GradientTape();
49+
tape.watch(w);
50+
var loss = w * w;
51+
var grad = tape.gradient(loss, w);
52+
}
53+
};
54+
}
55+
}

‎src/TensorFlowNET.Console/Program.cs‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,24 @@ class Program
77
static void Main(string[] args)
88
{
99
// boot .net core 10.5M.
10-
var memoryTest = new MemoryLeakTesting();
10+
var mm = new MemoryMonitor();
1111
// warm up tensorflow.net 28.5M.
12-
memoryTest.WarmUp();
13-
// 1 million float tensor 34.5M.
14-
memoryTest.TensorCreation();
12+
mm.WarmUp();
13+
var cases = new MemoryTestingCases();
14+
15+
int batchSize = 1000;
16+
17+
// 1 million float tensor 58.5M.
18+
// mm.Execute(10, 100 * batchSize, cases.Constant);
19+
20+
// 100K float variable 80.5M.
21+
//mm.Execute(10, 10 * batchSize, cases.Variable);
22+
23+
// 1 million math add 36.5M.
24+
// mm.Execute(10, 100 * batchSize, cases.MathAdd);
25+
26+
// 100K gradient 211M.
27+
mm.Execute(100, 1 * batchSize, cases.Gradient);
1528

1629
Console.WriteLine("Finished.");
1730
Console.ReadLine();

‎src/TensorFlowNET.Core/APIs/c_api.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ namespace Tensorflow
4343
/// </summary>
4444
public partial class c_api
4545
{
46-
public const string TensorFlowLibName = "tensorflow";
46+
public const string TensorFlowLibName = @"D:\SciSharp\tensorflow-google\bazel-bin\tensorflow\tensorflow.dll";
4747

4848
public static string StringPiece(IntPtr handle)
4949
{

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@ namespace Tensorflow.Eager
77
public class EagerOperation : Operation
88
{
99
public int NumInputs;
10+
public IntPtr[] InputHandles { get; set; }
1011
public Tensor[] Inputs { get; set; }
1112
public int NumOutputs;
13+
public IntPtr[] OutputHandles { get; set; }
1214
public Tensor[] Outputs { get; set; }
1315
public int[] SkipInputIndices { get; set; }
1416

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

Lines changed: 41 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,47 +2,66 @@
22
using System;
33
using System.Collections.Generic;
44
using System.Text;
5-
using static Tensorflow.Binding;
5+
using Tensorflow.Gradients;
66

77
namespace Tensorflow.Eager
88
{
99
public partial class EagerTensor : Tensor
1010
{
11-
public EagerTensor(IntPtr handle) : base(handle)
11+
public EagerTensor() : base(IntPtr.Zero)
1212
{
13-
EagerTensorHandle = handle;
14-
tfe_tensor_handle = c_api.EagerTensor_Handle(handle);
15-
_handle = c_api.TFE_TensorHandleResolve(tfe_tensor_handle, status);
16-
}
17-
18-
/*public EagerTensor(int value, string device_name) : base(value)
19-
{
20-
tfe_tensor_handle = c_api.TFE_NewTensorHandle(_handle, status);
21-
EagerTensorHandle = c_api.TFE_EagerTensorFromHandle(tf.context, tfe_tensor_handle);
13+
EagerTensorHandle = c_api.TFE_NewEagerTensor();
14+
// _id = c_api.TFE_EagerTensorId(EagerTensorHandle);
15+
// print($"new EagerTensorHandle {EagerTensorHandle.ToString("x16")} {Id}");
2216
}
2317

24-
public EagerTensor(long value, string device_name) : base(value)
18+
public EagerTensor(IntPtr handle) : base(IntPtr.Zero)
2519
{
26-
tfe_tensor_handle = c_api.TFE_NewTensorHandle(_handle, status);
27-
EagerTensorHandle = c_api.TFE_EagerTensorFromHandle(tf.context, tfe_tensor_handle);
20+
EagerTensorHandle = handle;
21+
Resolve();
22+
// print($"new EagerTensorHandle {EagerTensorHandle.ToString("x16")} {Id}");
2823
}
2924

30-
public EagerTensor(float value, string device_name) : base(value)
31-
{
32-
tfe_tensor_handle = c_api.TFE_NewTensorHandle(_handle, status);
33-
EagerTensorHandle = c_api.TFE_EagerTensorFromHandle(tf.context, tfe_tensor_handle);
34-
}*/
35-
3625
public EagerTensor(string value, string device_name) : base(value)
3726
{
27+
EagerTensorHandle = c_api.TFE_NewEagerTensor();
3828
tfe_tensor_handle = c_api.TFE_NewTensorHandle(_handle, status);
39-
EagerTensorHandle = c_api.TFE_EagerTensorFromHandle(tf.context, tfe_tensor_handle);
29+
c_api.TFE_SetEagerTensorHandle(EagerTensorHandle, tfe_tensor_handle);
30+
Resolve();
31+
// print($"new EagerTensorHandle {EagerTensorHandle.ToString("x16")} {Id}");
4032
}
4133

4234
public EagerTensor(NDArray value, string device_name) : base(value)
4335
{
36+
EagerTensorHandle = c_api.TFE_NewEagerTensor();
4437
tfe_tensor_handle = c_api.TFE_NewTensorHandle(_handle, status);
45-
EagerTensorHandle = c_api.TFE_EagerTensorFromHandle(tf.context, tfe_tensor_handle);
38+
c_api.TFE_SetEagerTensorHandle(EagerTensorHandle, tfe_tensor_handle);
39+
Resolve();
40+
// print($"new EagerTensorHandle {EagerTensorHandle.ToString("x16")} {Id}");
41+
}
42+
43+
public EagerTensor Resolve()
44+
{
45+
if (tfe_tensor_handle == IntPtr.Zero)
46+
tfe_tensor_handle = c_api.TFE_EagerTensorHandle(EagerTensorHandle);
47+
48+
if (_handle == IntPtr.Zero)
49+
_handle = c_api.TFE_TensorHandleResolve(tfe_tensor_handle, status);
50+
51+
_id = c_api.TFE_EagerTensorId(EagerTensorHandle);
52+
53+
GarbageCollector.Increase(_handle, GCItemType.TensorHandle);
54+
GarbageCollector.Increase(tfe_tensor_handle, GCItemType.LocalTensorHandle);
55+
GarbageCollector.Increase(EagerTensorHandle, GCItemType.EagerTensorHandle);
56+
57+
return this;
58+
}
59+
60+
protected override void DisposeUnmanagedResources(IntPtr handle)
61+
{
62+
GarbageCollector.Decrease(_handle);
63+
GarbageCollector.Decrease(tfe_tensor_handle);
64+
GarbageCollector.Decrease(EagerTensorHandle);
4665
}
4766
}
4867
}

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,25 @@ 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);
17+
18+
public static int GetRank(IntPtr handle)
19+
{
20+
var tfe_tensor_handle = c_api.TFE_EagerTensorHandle(handle);
21+
using var status = new Status();
22+
return c_api.TFE_TensorHandleNumDims(tfe_tensor_handle, status);
23+
}
24+
25+
public static int[] GetDims(IntPtr handle)
26+
{
27+
var tfe_tensor_handle = c_api.TFE_EagerTensorHandle(handle);
28+
using var status = new Status();
29+
var dims = new int[c_api.TFE_TensorHandleNumDims(tfe_tensor_handle, status)];
30+
for (int i = 0; i < dims.Length; i++)
31+
dims[i] = c_api.TFE_TensorHandleDim(tfe_tensor_handle, i, status);
32+
return dims;
33+
}
34+
1635
public override string ToString()
1736
{
1837
switch (rank)

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

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,18 +33,17 @@ public EagerTensor[] execute(Context ctx, string op_name, int num_outputs,
3333
{
3434
ctx.ensure_initialized();
3535

36-
using var status = new Status();
37-
38-
BindingArray results = c_api.TFE_QuickExecute(ctx,
36+
var results = Enumerable.Range(0, num_outputs).Select(x => new EagerTensor()).ToArray();
37+
Status status = c_api.TFE_QuickExecute(ctx,
3938
ctx.device_name,
4039
op_name,
4140
inputs.Select(x => x.EagerTensorHandle).ToArray(),
4241
inputs.Length,
4342
op => wrap_tfe_src.SetOpAttrs(op, attrs),
44-
status);
43+
results.Select(x => x.EagerTensorHandle).ToArray(), results.Length);
4544
status.Check(true);
4645

47-
return results.Data().Select(x => new EagerTensor(x)).ToArray();
46+
return results.Select(x => x.Resolve()).ToArray();
4847
}
4948

5049
public (TF_DataType, EagerTensor[]) args_to_matching_eager(Context ctx, TF_DataType default_dtype = TF_DataType.DtInvalid, object[] args = null)

0 commit comments

Comments
 (0)