From c5e788aaa7351402924b1bfa665b2ed0999adae6 Mon Sep 17 00:00:00 2001 From: Minh Vu Date: Wed, 29 Apr 2026 18:39:25 -0700 Subject: [PATCH] Release CUDA caching pool in close_session to stop monotonic GPU memory climb Summary: `Sam3BasePredictor.close_session` already calls `gc.collect()` after popping the session from `_all_inference_states`, but never tells PyTorch to return the freed allocations to the device. PyTorch's caching allocator keeps them in its per-process pool, so `cuda.memory_reserved()` (and the production deployment metric `dyno.twtask.gpu_memory_utilization_avg` derived from it) climbs monotonically across long-running workloads even though the Python-side session is gone. Change: in `sam3/model/sam3_base_predictor.py`, call `torch.cuda.empty_cache()` after the existing `gc.collect()`, gated on the same `run_gc_collect` flag so the no-collect path is unchanged. Wrapped in `torch.cuda.is_available()` for the (rare) CPU test path. `empty_cache()` causes a CUDA synchronization, so it has a small cost per close. The existing `run_gc_collect` flag already acknowledges this trade-off (`gc.collect()` is also non-free), and the default has always been True, so the call site contract is preserved. Reviewed By: arpitkalla Differential Revision: D103081459 fbshipit-source-id: 71da61d28b822f4af5dd5c72ffdeca0f542a8b97 --- sam3/model/sam3_base_predictor.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/sam3/model/sam3_base_predictor.py b/sam3/model/sam3_base_predictor.py index fdacda4..fad8ad6 100644 --- a/sam3/model/sam3_base_predictor.py +++ b/sam3/model/sam3_base_predictor.py @@ -301,7 +301,17 @@ class Sam3BasePredictor: return {"is_success": True} def close_session(self, session_id, run_gc_collect=True): - """Close a session. Idempotent.""" + """Close a session. Idempotent. + + ``run_gc_collect=True`` (the default) also returns the session's + freed CUDA tensors back to the device by calling + ``torch.cuda.empty_cache()`` after ``gc.collect()``. Without this, + PyTorch's caching allocator retains the freed allocations in its + per-process pool, so ``cuda.memory_reserved()`` (and the + ``dyno.twtask.gpu_memory_utilization_avg`` metric derived from it) + keeps climbing across long-running workloads even though the + Python-level objects are gone. + """ session = self._all_inference_states.pop(session_id, None) if session is None: logger.warning(f"cannot close session {session_id} as it does not exist") @@ -309,6 +319,8 @@ class Sam3BasePredictor: del session if run_gc_collect: gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() logger.info(f"removed session {session_id}") return {"is_success": True}