Skip to content

Commit

Permalink
Fix memory leak in TensorflowTransform (#4223)
Browse files Browse the repository at this point in the history
* Fix memory leak by freeing input tensors after executing the graph

* Fix memory leak by freeing the graph after each session

* Get input tensors from runner
  • Loading branch information
KsenijaS authored and codemzs committed Sep 29, 2019
1 parent 7fd670f commit a072b5e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/Microsoft.ML.Dnn/DnnUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,11 @@ public Runner AddInput(Tensor value, int index)
return this;
}

public List<Tensor> GetInputValues()
{
return _inputValues;
}

public Runner AddOutputs(string output)
{
_outputs.Add(ParseOutput(output));
Expand Down
13 changes: 12 additions & 1 deletion src/Microsoft.ML.TensorFlow/TensorflowTransform.cs
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,11 @@ private void Dispose(bool disposing)
{
Session.close(); // invoked Dispose()
}

if (Session != null && Session.graph != IntPtr.Zero)
{
Session.graph.Dispose();
}
}
finally
{
Expand Down Expand Up @@ -645,7 +650,7 @@ private void UpdateCacheIfNeeded(long position, ITensorValueGetter[] srcTensorGe
Runner runner = new Runner(_parent.Session);

// Feed inputs to the graph.
for (int i = 0; i < _parent.Inputs.Length; i++)
for (int i = 0; i < _parent.Inputs.Length; i++)
{
var tensor = srcTensorGetters[i].GetTensor();
runner.AddInput(_parent.Inputs[i], tensor);
Expand All @@ -658,6 +663,12 @@ private void UpdateCacheIfNeeded(long position, ITensorValueGetter[] srcTensorGe
// Execute the graph.
var tensors = runner.Run();

List<Tensor> inputTensors = runner.GetInputValues();
foreach (Tensor inputTensor in inputTensors)
{
inputTensor.Dispose();
}

Contracts.Assert(tensors.Length > 0);

for (int j = 0; j < activeOutputColNames.Length; j++)
Expand Down

0 comments on commit a072b5e

Please sign in to comment.