Skip to content

Commit 2faab21

Browse files
authored
Merge branch '1303' into temp
2 parents 8b14055 + 3eb8326 commit 2faab21

File tree

3 files changed

+9
-7
lines changed

3 files changed

+9
-7
lines changed

RELEASENOTES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ __Bug Fixes__:
1818

1919
- #1300 `Adadelta`, `Adam` and `AdamW` will no longer throw `NullReferenceException` when `maximize` is `true` and `grad` is `null`.
2020
- `torch.normal` will now correctly return a leaf tensor.
21+
- #1303 Allow dispose scopes to be disposed out of LIFO order.
2122

2223
# NuGet Version 0.102.4
2324

src/TorchSharp/DisposeScope.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ public DisposeScope(DisposeScopeManager disposeScopeManager)
2020
{
2121
_disposeScopeManager = disposeScopeManager ?? throw new ArgumentNullException(nameof(disposeScopeManager));
2222
if (disposeScopeManager.DisposeScopeStack.Count > 0) {
23-
OuterScope = disposeScopeManager.DisposeScopeStack.Peek();
23+
OuterScope = disposeScopeManager.DisposeScopeStack[
24+
disposeScopeManager.DisposeScopeStack.Count - 1];
2425
}
2526
}
2627

src/TorchSharp/DisposeScopeManager.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public class DisposeScopeManager
1818
internal ThreadDisposeScopeStatistics StatisticsInstance { get; } = new ThreadDisposeScopeStatistics();
1919

2020
internal static DisposeScopeManager ThreadSingleton => (_threadSingleton ??= new DisposeScopeManager());
21-
internal Stack<DisposeScope> DisposeScopeStack { get; } = new();
21+
internal List<DisposeScope> DisposeScopeStack { get; } = new();
2222

2323
public static ThreadDisposeScopeStatistics Statistics => ThreadSingleton.StatisticsInstance;
2424

@@ -30,7 +30,7 @@ public class DisposeScopeManager
3030
}
3131

3232
StatisticsInstance.CreatedInScopeCount++;
33-
var current = DisposeScopeStack.Peek();
33+
var current = DisposeScopeStack[DisposeScopeStack.Count - 1];
3434
current.Include(disposable);
3535
return current;
3636
}
@@ -42,15 +42,15 @@ internal static DisposeScope NewDisposeScope()
4242

4343
internal void RemoveDisposeScope(DisposeScope disposeScope)
4444
{
45-
Debug.Assert(DisposeScopeStack.Count > 0);
46-
Debug.Assert(DisposeScopeStack.Peek() == disposeScope);
47-
DisposeScopeStack.Pop();
45+
var index = DisposeScopeStack.LastIndexOf(disposeScope);
46+
if (index is not -1)
47+
DisposeScopeStack.RemoveAt(index);
4848
}
4949

5050
private DisposeScope InnerNewDisposeScope()
5151
{
5252
var disposeScope = new DisposeScope(this);
53-
DisposeScopeStack.Push(disposeScope);
53+
DisposeScopeStack.Add(disposeScope);
5454
return disposeScope;
5555
}
5656
}

0 commit comments

Comments
 (0)