From 847e1a3b15115a04c87c0760297f044f0555d970 Mon Sep 17 00:00:00 2001 From: Minh Vu Date: Sun, 3 May 2026 11:09:58 -0700 Subject: [PATCH] Gate close_session empty_cache on device memory pressure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: Follow-up to the previous close_session change. ``torch.cuda.empty_cache()`` forces a CUDA synchronization that stalls all streams in the process. With many concurrent inference sessions, calling it on every close produces visible compute-utilization gaps — sessions that finish around the same time stack their syncs, and during each empty_cache window the device cannot start new work for any other in-flight session. This diff gates the call on device memory pressure: ``empty_cache()`` only fires when device memory usage is at or above ``_MAX_MEMORY_PCT`` (default 85). Below that threshold, the caching allocator's freed blocks stay available for the next session and the CUDA sync is skipped entirely. This preserves the original goal of the previous diff (preventing unbounded growth of reserved memory) without paying the sync cost on every close. ``run_gc_collect=False`` continues to skip both ``gc.collect()`` and ``empty_cache()`` (unchanged contract). CPU-only test paths are also unchanged: ``mem_get_info`` raises ``RuntimeError`` with no active CUDA context, which falls through to skip. Differential Revision: D103602738 fbshipit-source-id: 6c6ac7be208d607612dbe14767d83148f01ffc5e --- sam3/model/sam3_base_predictor.py | 38 +++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/sam3/model/sam3_base_predictor.py b/sam3/model/sam3_base_predictor.py index fad8ad6..b2435a3 100644 --- a/sam3/model/sam3_base_predictor.py +++ b/sam3/model/sam3_base_predictor.py @@ -19,6 +19,15 @@ from sam3.logger import get_logger logger = get_logger(__name__) +# torch.cuda.empty_cache() forces a CUDA synchronization that stalls all +# streams in the process. Calling it on every close_session produces visible +# compute-utilization gaps when many sessions are active concurrently. +# Gate the call on device memory pressure: only fire when usage crosses the +# threshold. The allocator's caching pool already covers the common case +# where freed blocks get reused by the next session — empty_cache is only +# needed to keep memory from growing unbounded. +_MAX_MEMORY_PCT = 85 + class Sam3BasePredictor: """ @@ -307,10 +316,11 @@ class Sam3BasePredictor: 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. + per-process pool, so reserved memory keeps climbing across + long-running workloads even though the Python-level objects are gone. + + ``empty_cache()`` itself triggers a CUDA sync, so it is gated on + device memory pressure — see ``_should_empty_cache``. """ session = self._all_inference_states.pop(session_id, None) if session is None: @@ -319,11 +329,29 @@ class Sam3BasePredictor: del session if run_gc_collect: gc.collect() - if torch.cuda.is_available(): + if torch.cuda.is_available() and self._should_empty_cache(): torch.cuda.empty_cache() logger.info(f"removed session {session_id}") return {"is_success": True} + def _should_empty_cache(self) -> bool: + """Whether close_session should call ``torch.cuda.empty_cache()``. + + Fires only when device memory usage is at or above + ``_MAX_MEMORY_PCT``. Below that threshold, the caching allocator's + freed blocks remain available for the next session and the CUDA + sync from empty_cache is avoided. + """ + try: + free, total = torch.cuda.mem_get_info() + except RuntimeError: + # No active CUDA context (e.g., CPU-only test env). + return False + if total <= 0: + return False + used_pct = (1.0 - free / total) * 100 + return used_pct >= _MAX_MEMORY_PCT + def _get_session(self, session_id): session = self._all_inference_states.get(session_id, None) if session is None: