Commit Graph
53 Commits
Author SHA1 Message Date
Minh Vu 2530a8a7af Drop per-session dict refs in close_session to fix monotonic GPU climb
Summary:
SAM3 IPNext replicas serving long-running session workloads exhibit a
monotonic climb in PyTorch's *allocated* GPU memory bucket (not the
cache bucket), to the point of OOM-ing single-call transients at
concurrency=1. Two recent client observations from the
video_product_highlight pipeline:

  jiid 37154706936429064 (2026-05-09): 4 SAM3 OOMs in the first 41
    seconds, AIMD shrunk concurrency 4→1, run failed at lifespan with
    3,332 stranded checkpoints and 0 final detection rows.
  jiid 41658306563594281 (2026-05-10): same fingerprint within 90s of
    startup; 474 OOM-retry events over 8h, run averaged 3 ads/min
    (vs ~7.5 ads/min on a fresh replica).

The OOM messages from these runs all show the same memory state:

  this process has 94.99 GiB memory in use.
  93.54 GiB allocated by PyTorch.
  577.70 MiB reserved by PyTorch but unallocated.

i.e., ``empty_cache`` *was* firing (reserved-but-unallocated is tiny),
but the *allocated* bucket — backed by live tensor objects — is sitting
at ~93 GiB. That's the signature of dict-keyed references staying
alive: every closed session's tensors are still in the allocated pool
because the dict that keys them is being held by something the close
path doesn't reach.

D103081459 (2026-04-29) added ``empty_cache`` after ``gc.collect()``,
which fixed the *cache*-side leak. D103602738 (2026-05-03) gated it on
device memory pressure. Neither addressed the allocated-side leak
because they relied on ``del session`` triggering refcount-zero on the
inference_state dict — which, in practice, doesn't happen reliably
across long-lived workers (closure capture, asyncio task references,
metrics buffers, or simple cycles can keep the wrapper dict alive past
the local ``del``).

Fix: explicitly call ``.clear()`` on both ``session["state"]`` and
``session`` before ``del session``. ``.clear()`` immediately drops
every dict-keyed reference, releasing the per-session tensors
regardless of whether the wrapper dict itself survives. ``init_state``
populates ``state`` with these heavy GPU-resident keys:

  - ``input_batch`` (BatchedDatapoint with ``img_batch`` = video frames
    on device, plus per-frame find_inputs)
  - ``constants["empty_geometric_prompt"]`` (zeroed device tensors)
  - ``feature_cache`` (per-frame feature maps, populated during
    propagation)
  - ``cached_frame_outputs`` (per-frame outputs, populated during
    propagation)
  - ``tracker_inference_states``, ``tracker_metadata`` (per-track
    state, populated during add_prompt + propagation)

A single ``state.clear()`` covers all of them and any future heavy
keys, so the fix doesn't need to enumerate them. Lists in the dict
hold ``None``s for per-frame slots and don't need separate handling.

___

overriding_review_checks_triggers_an_audit_and_retroactive_review
Oncall Short Name: creative_sticker_model

Differential Revision: D104607919

fbshipit-source-id: 6022802f07f51ee72c77ad008acdf94afe763433
2026-05-10 20:18:53 -07:00
Minh Vu 653a9609b9 Return gpu_mem snapshot in close_session response
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
2026-05-10 19:12:26 -07:00
generatedunixname1401739305002972 4bf4a8aaff Fix PYRE_MISSING_ANNOTATIONS issues in fbcode/deeplearning/projects/sam3_release/sam3/model/io_utils.py
Differential Revision: D104574586

fbshipit-source-id: 9492a0033999987f381fe83ef198ebc315f92217
2026-05-10 11:10:07 -07:00
generatedunixname1401739305002972 8d01d6ce78 Fix PYRE_MISSING_ANNOTATIONS issues in fbcode/deeplearning/projects/sam3_release/sam3/model/io_utils.py
Differential Revision: D104514357

fbshipit-source-id: 76846c2df7a5ade6e0002bb66fd2b7f574b152c5
2026-05-09 08:41:33 -07:00
generatedunixname2094418054467506 66b7482602 Fix python_unnecessary_generator_set_comprehension issues in deeplearning/.../data/sam3_video_dataset.py
Differential Revision: D103822905

fbshipit-source-id: 42d78b7b8b527c1de0f6b3375b568b70720a53f6
2026-05-08 14:16:32 -07:00
generatedunixname1401739305002972 ea46ebca5e Fix PYRE_MISSING_ANNOTATIONS issues in fbcode/deeplearning/projects/sam3_release/sam3/model/io_utils.py
Differential Revision: D103516284

fbshipit-source-id: 8fd9ffd8abd1dd59a4ccad9c1be39f8d7e1d01cd
2026-05-06 02:08:24 -07:00
Minh Vu cb1ff794d3 Make clear_cache_threshold a per-call param on close_session
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
2026-05-05 22:14:01 -07:00
Minh Vu 847e1a3b15 Gate close_session empty_cache on device memory pressure
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
2026-05-03 11:09:58 -07:00
generatedunixname1401739305002972 a51b9f498c Fix PYRE_MISSING_ANNOTATIONS issues in fbcode/deeplearning/projects/sam3_release/sam3/model/io_utils.py
Differential Revision: D103379401

fbshipit-source-id: b1f6613116dcec832dea098e67419e97d9a91f22
2026-05-01 15:54:41 -07:00
generatedunixname1401739305002972 5f8e0647a1 Fix PYRE_MISSING_ANNOTATIONS issues in fbcode/deeplearning/projects/sam3_release/sam3/model/io_utils.py
Differential Revision: D103174371

fbshipit-source-id: 3b418fc1689a3eee05cde64287a68ea02579f366
2026-04-30 10:01:09 -07:00