Summary:
Enriches the existing ``Sam3BasePredictor.close_session`` response with a ``gpu_mem`` dict so clients can decide whether the device has headroom for their next session — no separate admission RPC needed. Every session-close naturally exposes the post-cleanup HBM state (snapshot taken AFTER any ``empty_cache`` call), which is exactly what the next session will face.
Why piggyback on close_session: clients already round-trip to the server at session boundaries; adding a separate admission-check endpoint would double the RPC traffic and require new dispatch logic on both sides. Folding the snapshot into close_session means the client gets a fresh GPU state read every time it finishes a session, free, with no new endpoint.
Wire shape (additive to the existing response, backward-compatible at the JSON layer):
```
close_session response:
{
"is_success": True,
"gpu_mem": {
"free_bytes": int, # raw torch.cuda.mem_get_info()
"total_bytes": int, # raw torch.cuda.mem_get_info()
"allocated_bytes": int, # torch.cuda.memory_allocated() — live tensor footprint
"reserved_bytes": int, # torch.cuda.memory_reserved() — caching-allocator pool
"free_pct": float, # convenience: free_bytes / total_bytes * 100
"active_session_count": int, # sessions still resident after this close
}
}
```
Old callers that only read ``is_success`` work unchanged — extra dict keys are ignored at the JSON layer.
How clients will use it (companion diff): each worker stores the snapshot from its most recent ``close_session`` response in a small per-process structure (e.g., a ``_HbmGate`` with an ``asyncio.Lock``). Before issuing the next ``start_session``, the worker checks the snapshot's ``free_pct``; if it's below a threshold, sleep briefly and re-check, bounded by a max wait. The throttle gate naturally happens at session boundaries instead of via a separate admission RPC.
Fail-open semantics: any error reading the device returns zero stats so a broken CUDA context (e.g., CPU-only test env) NEVER breaks the session-close response. ``memory_allocated`` and ``memory_reserved`` are cheap host-side bookkeeping reads (no CUDA sync) and complement ``mem_get_info`` by exposing the caching-allocator pool size vs the live tensor footprint.
Reference: T262964602 (SAM3 VH daily DataSwarm pipeline).
Differential Revision: D104592033
fbshipit-source-id: 495cb1c28ac634c882be2fd468eff7d1a75a8801
Summary:
- Add `clear_cache_threshold: int = 80` keyword param to `Sam3BasePredictor.close_session`. Lowered the module-level `_CLEAR_CACHE_THRESHOLD` constant (renamed from `_MAX_MEMORY_PCT = 85`, used as the default-of-default) to 80 so request-omitted calls match.
- `_should_empty_cache` now takes `clear_cache_threshold` as an explicit argument instead of reading the module constant — lets callers pick a tighter or looser threshold per session-close.
- `handle_request` forwards `request.get("clear_cache_threshold", _CLEAR_CACHE_THRESHOLD)` to `close_session`, so RPC clients can tune the empty_cache threshold via the request payload without redeploying the predictor.
Differential Revision: D103978013
fbshipit-source-id: 5f0db11b6a26b88a9be2ea4643c90c9b71338393
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
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
Summary: Fix SAM3 io_utils.py to handle extensionless video files from OIL (Object Image Library). Previously, the code would immediately raise NotImplementedError when encountering files without recognized video extensions. This change attempts to load such files as videos using the video loader, only raising an exception if the actual decoding fails. This enables SAM3 to process OIL-stored video paths that don't include file extensions.
Differential Revision: D99228861
fbshipit-source-id: c93d089ad4b7eac9e0eb629d7a71b021604db410