torch.memory.inScope
function inScope(): booleanChecks if code is currently executing inside a memory scope.
Returns true if called from within a torch.scope() block, false otherwise.
Useful for conditional behavior based on whether automatic cleanup is active.
Use Cases:
- Determine if automatic cleanup will destroy tensors
- Conditionally escape tensors only when inside scope
- Debug scope nesting
- Implement scope-aware utilities
- Scope nesting: Returns
truefor any level of nesting - Synchronous: Constant-time operation
- No side effects: Doesn't change any state
Returns
boolean– true if inside a scope, false if at global levelExamples
// Global level
torch.memory.inScope(); // false
// Inside a scope
torch.scope(() => {
torch.memory.inScope(); // true
// Nested scopes
torch.scope(() => {
torch.memory.inScope(); // true
});
});
// Back to global
torch.memory.inScope(); // false
// Conditional tensor handling
function createTensor() {
const x = torch.randn([100, 100]);
if (torch.memory.inScope()) {
// Will be auto-cleaned, safe to return
return x;
} else {
// At global level, caller responsible for cleanup
return torch.escape(x);
}
}See Also
- [PyTorch N/A (torch.js specific)](https://pytorch.org/docs/stable/generated/N/A .html)
- scope - Create a memory scope
- scopeDepth - Get nesting depth
- escape - Mark tensor to survive scope