Correct way of feeding inputs or model disposing
Hello, what is the correct way of feeding loaded model? I am using this code but it seems that there are memory leaks because after 15 calls of the DoSomeMagic method I am almost run out of memory (15 GB) and everything becomes more slower. Profiler says that something is holding a lot of single[,] arrays.
public void DoSomeMagic (string path)
{
var model = File.ReadAllBytes(path);
using (var graph = new TFGraph())
{
graph.Import(model, "");
using (var session = new TFSession(graph))
{
var c = 400000;
Parallel.For(0, c, i =>
{
var vector = GetFeatureVector(i); // returns float[1,600]
var runner = session.GetRunner();
runner.Fetch(graph["output_node"][0]);
runner.AddInput(graph["input_node"][0], vector);
var output = runner.Run();
var p = (float[,])output[0].GetValue();
// process output here ...
});
}
}
}
My guess is that the TFTensors here aren't being disposed (specifically "output" produced by runner.Run). TFTensors are disposable objects like TFGraph and TFSession.
Neither calling output[0].Dispose() unfortunately does not help.
Then the next thing to check might be the input - symptom-wise it does seem like the inputs and outputs (which are both TFTensors) aren't being disposed. Try placing both the input and output in using statements (right now it looks like the input is being converted into a TFTensor implicitly)
If you post a complete sample, I can take a look using the profiler to find what is retaining the data.
you are also calling "GetFeatureVector(i)" 400,000 times per call. That method might generate some garbage too.
Hello, I am sorry, I forgot to reply. runner.AddInput(graph["input_node"][0], vector); does implicit conversion to TFTensor and memory leak will arise. So TFTensor vector = GetFeatureVector(i) ... vector.Dispose() resolves the problem.
I would also appriciate a hint to correct feeding, because this code is really slow. Just calling GetFeatureVector takes something about 30 seconds on my compter, but the rest - feeding model with just three layers of 200 neurons takes 1 minute. Could it be caused by repeatedly sending data to GPU?
Bummer. This is an unintended consequence of the implicit conversion, what I should probably do in this scenario is add an overload that takes an Array, instead of a TFTensor, an then do the conversion and disposal there, to avoid tripping people.
My current plan to solve this is roughly this.
Drop the implicit conversion from arrays to tensors as those objects hold pointers to big blobs of data.
Evaluate every overload that takes a TFTensor and provide an overload for Array that creates and disposes the intermediate tftensor.
This should preserve source code compatibility and ensure that heavy objects are released as soon as possible