dotnet/TorchSharp

ToTensor extension method creates an orphaned tensor (Memory Leak)

mvphelps opened this issue · 0 comments

When invoking .ToTensor(), the method creates two tensors. The first one is sometimes overwritten and the reference is lost. Since it won't get Dispose(), this is a memory leak.

Reproduced in TestDisposeScopesStatisticsTensorUnscoped

[Fact]
public void ToTensorCreatesOrphanedTensor()
{
    //Defect: This needs fixing but is unrelated to the commit that discovered
    //it - adding better lifetime statistics. ToTensor() leaks 1 tensor
    // //every time it is called.
    var stats = DisposeScopeManager.Statistics;
    stats.Reset();
    var a1 = 1.ToTensor();
    //Should be 1 ideally. If it remains two...
    Assert.Equal(2, stats.CreatedOutsideScopeCount);
    // ... this should be 1
    Assert.Equal(0, stats.DisposedOutsideScopeCount);
    a1.Dispose();
    //... and this should also be 2
    Assert.Equal(1, stats.DisposedOutsideScopeCount);
}

See also TestDisposeScopesStatisticsTensorScoped.ToTensorCreatesOrphanedTensorButDisposeScopeCleansItUp