Manage memory in TorchSharp
mainTorchSharp provides three approaches to memory management for CPU and GPU tensors. Choosing the right approach depends on your memory constraints:
- Automatic disposal via Garbage Collection (GC): The simplest method where tensors are implicitly disposed via .NET finalizers. This is recommended for small models but may fail for large models because the .NET GC is unaware of the memory pressure on CPU or GPU resources.
- Explicit disposal: Using
using var(C#) oruse(F#) to manage the lifetime of every tensor. This is more cumbersome but provides higher memory ceilings and is often required for training on a GPU. - Dispose Scopes: Using
torch.NewDisposeScope()(details in subsequent sections) for more structured management.
General Tips:
- If experiencing memory issues, try reducing the batch size.
- Even when using explicit disposal, it is good practice to call
GC.Collect()after each mini-batch to catch overlooked or inconveniently managed temporaries.