SAM 3.1 Release (#503)
Summary: SAM 3.1 multiplex video tracking for the OSS sam3 repository. Features: - Multiplex architecture: batch N objects into fixed-capacity buckets for efficient multi-object tracking (16 objects per bucket) - Unified API: build_sam3_predictor(version="sam3.1") with auto-download from HuggingFace (facebook/sam3.1) - Flash Attention 3, torch.compile support (~31 FPS compiled on H100) - Text prompts, point prompts, box prompts, object removal, refinement - Clean inheritance: Sam3MultiplexBase extends Sam3VideoBase - Shared base predictor (Sam3BasePredictor) for both SAM3 and SAM3.1 Performance (H100, 5 objects, compiled): - SAM 3.1: ~31 FPS - Memory: ~17.7 GB Usage: from sam3 import build_sam3_predictor predictor = build_sam3_predictor() # auto-downloads SAM 3.1 from HF Pull Request resolved: https://github.com/facebookresearch/sam3/pull/503 Reviewed By: josephgreer Differential Revision: D98500763 Pulled By: arpitkalla fbshipit-source-id: e2b74568f24bb4ecfb3144a4e8ec559aae6db5e8
This commit is contained in:
committed by
meta-codesync[bot]
parent
86ed770940
commit
9f22cb976f
@@ -55,6 +55,13 @@ This breakthrough is driven by an innovative data engine that has automatically
|
|||||||
<img src="assets/player.gif" width=380 />
|
<img src="assets/player.gif" width=380 />
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
## Latest updates
|
||||||
|
|
||||||
|
**03/27/2026 -- SAM 3.1 Object Multiplex is released. It introduces a shared-memory approach for joint multi-object tracking that is significantly faster without sacrificing accuracy.**
|
||||||
|
|
||||||
|
- A new suite of improved model checkpoints (denoted as **SAM 3.1**) are released on [Hugging Face](https://huggingface.co/facebook/sam3.1). See [`RELEASE_SAM3p1.md`](RELEASE_SAM3p1.md) for full details.
|
||||||
|
* To use the new SAM 3.1 checkpoints, you need the latest model code from this repo. If you have installed an earlier version of this repo, pull the latest code from this repo (with `git pull`), and then reinstall the repo following [Installation](#installation) below.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
@@ -74,7 +81,7 @@ conda activate sam3
|
|||||||
2. **Install PyTorch with CUDA support:**
|
2. **Install PyTorch with CUDA support:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install torch==2.7.0 torchvision torchaudio --index-url https://download.pytorch.org/whl/cu126
|
pip install torch==2.10.0 torchvision --index-url https://download.pytorch.org/whl/cu128
|
||||||
```
|
```
|
||||||
|
|
||||||
3. **Clone the repository and install the package:**
|
3. **Clone the repository and install the package:**
|
||||||
@@ -95,6 +102,12 @@ pip install -e ".[notebooks]"
|
|||||||
pip install -e ".[train,dev]"
|
pip install -e ".[train,dev]"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
5. **Optional dependencies for faster inference**
|
||||||
|
```bash
|
||||||
|
pip install einops ninja && pip install flash-attn-3 --no-deps --index-url https://download.pytorch.org/whl/cu128
|
||||||
|
pip install git+https://github.com/ronghanghu/cc_torch.git
|
||||||
|
```
|
||||||
|
|
||||||
## Getting Started
|
## Getting Started
|
||||||
|
|
||||||
⚠️ Before using SAM 3, please request access to the checkpoints on the SAM 3
|
⚠️ Before using SAM 3, please request access to the checkpoints on the SAM 3
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# Release Notes
|
||||||
|
|
||||||
|
## SAM 3.1 — March 27, 2026
|
||||||
|
|
||||||
|
SAM 3.1 introduces **Object Multiplex**, a shared-memory approach for joint multi-object tracking that is significantly faster without sacrificing accuracy. This release also includes new model checkpoints and optimized inference.
|
||||||
|
|
||||||
|
### Object Multiplex
|
||||||
|
|
||||||
|
SAM 3's video pipeline processes each tracked object independently, which scales linearly with the number of objects. Object Multiplex groups objects into fixed-capacity buckets and processes them jointly, drastically reducing redundant computation. For technical details, see Appendix H (Object Multiplex) in the [SAM 3 paper](https://arxiv.org/abs/2511.16719).
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="assets/sam3.1_diagram.png" width="720" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
#### Key Improvements
|
||||||
|
- **~7x speedup** at 128 objects on a single H100 GPU compared to the SAM 3 November 2025 release
|
||||||
|
- Inference optimizations that significantly improve multi-object tracking efficiency:
|
||||||
|
- Reduced CPU-GPU synchronization in detection-tracker association and other heuristics
|
||||||
|
- Enhanced `torch.compile` support with improved operation fusion
|
||||||
|
- Batched postprocessing and vision encoder to increase GPU utilization
|
||||||
|
- Mixed results on SA-Co/VEval video benchmarks, with notable improvement on YT-Temporal-1B (+2.1 cgF1)
|
||||||
|
- Improved VOS performance on 6 out of 7 benchmarks, including +2.0 on the challenging MOSEv2
|
||||||
|
|
||||||
|
#### Inference Efficiency
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="assets/sam3.1_efficiency.png" width="720" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
#### Video PCS with Text Prompt
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
<table style="min-width: 80%; border: 2px solid #ddd; border-collapse: collapse">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th rowspan="3" style="border-right: 2px solid #ddd; padding: 12px 16px">Model</th>
|
||||||
|
<th colspan="6" style="text-align: center; border-right: 2px solid #ddd; padding: 10px 16px">SA-Co/VEval benchmark test split</th>
|
||||||
|
<th colspan="4" style="text-align: center; padding: 10px 16px">Public benchmarks</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">SA-V</th>
|
||||||
|
<th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">YT-Temporal-1B</th>
|
||||||
|
<th colspan="2" style="text-align: center; border-right: 2px solid #ddd; padding: 10px 16px">SmartGlasses</th>
|
||||||
|
<th style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">LVVIS</th>
|
||||||
|
<th style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">BURST</th>
|
||||||
|
<th style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">YTVIS21</th>
|
||||||
|
<th style="text-align: center; padding: 10px 16px">OVIS</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th style="text-align: center; padding: 10px 16px">cgF1</th>
|
||||||
|
<th style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">pHOTA</th>
|
||||||
|
<th style="text-align: center; padding: 10px 16px">cgF1</th>
|
||||||
|
<th style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">pHOTA</th>
|
||||||
|
<th style="text-align: center; padding: 10px 16px">cgF1</th>
|
||||||
|
<th style="text-align: center; border-right: 2px solid #ddd; padding: 10px 16px">pHOTA</th>
|
||||||
|
<th style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">test mAP</th>
|
||||||
|
<th style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">test HOTA</th>
|
||||||
|
<th style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">val mAP</th>
|
||||||
|
<th style="text-align: center; padding: 10px 16px">val mAP</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td style="border-right: 2px solid #ddd; padding: 10px 16px">SAM 3</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">30.3</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">58.0</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">50.8</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">69.9</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">36.4</td>
|
||||||
|
<td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 16px">63.6</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">36.3</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">44.5</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">57.4</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">60.5</td>
|
||||||
|
</tr>
|
||||||
|
<tr style="border-top: 2px solid #b19c9cff">
|
||||||
|
<td style="border-right: 2px solid #ddd; padding: 10px 16px">SAM 3.1</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">30.5</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">58.7</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">52.9</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">70.7</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">36.3</td>
|
||||||
|
<td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 16px">64.4</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">34.3</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">43.3</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">56.6</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">61.5</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
#### Video Object Segmentation (VOS)
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
<table style="min-width: 60%; border: 2px solid #ddd; border-collapse: collapse">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th rowspan="2" style="border-right: 2px solid #ddd; padding: 12px 16px">Model</th>
|
||||||
|
<th colspan="5" style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">J&F</th>
|
||||||
|
<th style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">G</th>
|
||||||
|
<th style="text-align: center; padding: 10px 16px">J&Ḟ</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th style="text-align: center; padding: 10px 16px">MOSEv1 val</th>
|
||||||
|
<th style="text-align: center; padding: 10px 16px">DAVIS17 val</th>
|
||||||
|
<th style="text-align: center; padding: 10px 16px">LVOSv2 val</th>
|
||||||
|
<th style="text-align: center; padding: 10px 16px">SA-V val</th>
|
||||||
|
<th style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">SA-V test</th>
|
||||||
|
<th style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">YTVOS19 val</th>
|
||||||
|
<th style="text-align: center; padding: 10px 16px">MOSEv2 val</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td style="border-right: 2px solid #ddd; padding: 10px 16px">SAM 3</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">78.4</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">92.2</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">88.5</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">83.5</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">84.4</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">89.7</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">60.3</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="border-right: 2px solid #ddd; padding: 10px 16px">SAM 3.1</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">79.6</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">92.7</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">89.2</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">83.8</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">85.1</td>
|
||||||
|
<td style="text-align: center; border-right: 1px solid #eee; padding: 10px 16px">89.3</td>
|
||||||
|
<td style="text-align: center; padding: 10px 16px">62.3</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
### New Checkpoints
|
||||||
|
|
||||||
|
The SAM 3.1 checkpoints are available on the [Hugging Face repo](https://huggingface.co/facebook/sam3.1). See [Getting Started](README.md#getting-started) for download and authentication instructions.
|
||||||
|
|
||||||
|
### Notebooks
|
||||||
|
|
||||||
|
- [`sam3.1_video_predictor_example.ipynb`](examples/sam3.1_video_predictor_example.ipynb): Demonstrates how to use SAM 3.1 with Object Multiplex for video segmentation and dense tracking with text and point prompts.
|
||||||
|
|
||||||
|
### Contributors
|
||||||
|
|
||||||
|
[Arpit Kalla](https://github.com/arpitkalla), [Chaitanya Ryali](https://scholar.google.com/citations?user=4LWx24UAAAAJ&hl=en), [Christian Puhrsch](https://github.com/cpuhrsch), [Ho Kei Cheng](https://hkchengrex.com/), [Joseph Greer](https://scholar.google.com/citations?user=guL96CkAAAAJ&hl=en), [Meng Wang](https://github.com/mengwa41), [Miran Heo](https://sites.google.com/view/miranheo), [Pengchuan Zhang](https://pzzhang.github.io/pzzhang/), [Roman Rädle](https://scholar.google.com/citations?user=Tpt57v0AAAAJ&hl=en), [Yuan-Ting Hu](https://scholar.google.com/citations?user=E8DVVYQAAAAJ&hl=en)
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 100 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 375 KiB |
@@ -0,0 +1,643 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# Copyright (c) Meta Platforms, Inc. and affiliates."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Video segmentation and tracking with SAM 3.1 (Object Multiplex)\n",
|
||||||
|
"\n",
|
||||||
|
"This notebook demonstrates how to use SAM 3.1 with Object Multiplex for interactive video segmentation and dense tracking. Object Multiplex groups objects into fixed-capacity buckets and processes them jointly, drastically reducing redundant computation compared to SAM 3's per-object inference. It covers the following capabilities:\n",
|
||||||
|
"\n",
|
||||||
|
"- **Text prompts**: Using natural language descriptions to segment objects (e.g., \"person\", \"shoe\")\n",
|
||||||
|
"- **Point prompts**: Adding positive/negative clicks to segment and refine objects\n",
|
||||||
|
"\n",
|
||||||
|
"We use the terms _segment_ or _mask_ to refer to the model prediction for an object on a single frame, and _masklet_ to refer to the spatio-temporal masks across the entire video. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/sam3/blob/main/notebooks/sam3.1_video_predictor_example.ipynb\">\n",
|
||||||
|
" <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
|
||||||
|
"</a>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"using_colab = False"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"if using_colab:\n",
|
||||||
|
" import torch\n",
|
||||||
|
" import torchvision\n",
|
||||||
|
" print(\"PyTorch version:\", torch.__version__)\n",
|
||||||
|
" print(\"Torchvision version:\", torchvision.__version__)\n",
|
||||||
|
" print(\"CUDA is available:\", torch.cuda.is_available())\n",
|
||||||
|
" import sys\n",
|
||||||
|
" !{sys.executable} -m pip install opencv-python matplotlib scikit-learn\n",
|
||||||
|
" !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/sam3.git'"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"!nvidia-smi"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Set-up"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import os\n",
|
||||||
|
"import sam3\n",
|
||||||
|
"import torch\n",
|
||||||
|
"\n",
|
||||||
|
"sam3_root = os.path.join(os.path.dirname(sam3.__file__), \"..\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"#### Inference and visualization utils"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from sam3.model_builder import build_sam3_multiplex_video_predictor\n",
|
||||||
|
"\n",
|
||||||
|
"predictor = build_sam3_multiplex_video_predictor()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {
|
||||||
|
"jupyter": {
|
||||||
|
"source_hidden": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import glob\n",
|
||||||
|
"import os\n",
|
||||||
|
"\n",
|
||||||
|
"import cv2\n",
|
||||||
|
"import matplotlib.pyplot as plt\n",
|
||||||
|
"import numpy as np\n",
|
||||||
|
"from PIL import Image\n",
|
||||||
|
"from sam3.visualization_utils import (\n",
|
||||||
|
" load_frame,\n",
|
||||||
|
" prepare_masks_for_visualization,\n",
|
||||||
|
" visualize_formatted_frame_output,\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"plt.rcParams[\"axes.titlesize\"] = 12\n",
|
||||||
|
"plt.rcParams[\"figure.titlesize\"] = 12\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"def propagate_in_video(predictor, session_id):\n",
|
||||||
|
" outputs_per_frame = {}\n",
|
||||||
|
" for response in predictor.handle_stream_request(\n",
|
||||||
|
" request=dict(\n",
|
||||||
|
" type=\"propagate_in_video\",\n",
|
||||||
|
" session_id=session_id,\n",
|
||||||
|
" )\n",
|
||||||
|
" ):\n",
|
||||||
|
" outputs_per_frame[response[\"frame_index\"]] = response[\"outputs\"]\n",
|
||||||
|
"\n",
|
||||||
|
" return outputs_per_frame\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"def abs_to_rel_coords(coords, IMG_WIDTH, IMG_HEIGHT, coord_type=\"point\"):\n",
|
||||||
|
" \"\"\"Convert absolute coordinates to relative coordinates (0-1 range)\n",
|
||||||
|
"\n",
|
||||||
|
" Args:\n",
|
||||||
|
" coords: List of coordinates\n",
|
||||||
|
" coord_type: 'point' for [x, y] or 'box' for [x, y, w, h]\n",
|
||||||
|
" \"\"\"\n",
|
||||||
|
" if coord_type == \"point\":\n",
|
||||||
|
" return [[x / IMG_WIDTH, y / IMG_HEIGHT] for x, y in coords]\n",
|
||||||
|
" elif coord_type == \"box\":\n",
|
||||||
|
" return [\n",
|
||||||
|
" [x / IMG_WIDTH, y / IMG_HEIGHT, w / IMG_WIDTH, h / IMG_HEIGHT]\n",
|
||||||
|
" for x, y, w, h in coords\n",
|
||||||
|
" ]\n",
|
||||||
|
" else:\n",
|
||||||
|
" raise ValueError(f\"Unknown coord_type: {coord_type}\")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Loading an example video\n",
|
||||||
|
"\n",
|
||||||
|
"We assume that the video is stored as either **a list of JPEG frames with filenames like `<frame_index>.jpg`** or **an MP4 video**.\n",
|
||||||
|
"\n",
|
||||||
|
"Note that you can extract their JPEG frames using ffmpeg (https://ffmpeg.org/) as follows:\n",
|
||||||
|
"```\n",
|
||||||
|
"ffmpeg -i <your_video>.mp4 -q:v 2 -start_number 0 <output_dir>/'%05d.jpg'\n",
|
||||||
|
"```\n",
|
||||||
|
"where `-q:v` generates high-quality JPEG frames and `-start_number 0` asks ffmpeg to start the JPEG file from `00000.jpg`."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# \"video_path\" needs to be either a JPEG folder or a MP4 video file\n",
|
||||||
|
"video_path = f\"{sam3_root}/assets/videos/0001\""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# load \"video_frames_for_vis\" for visualization purposes (they are not used by the model)\n",
|
||||||
|
"if isinstance(video_path, str) and video_path.endswith(\".mp4\"):\n",
|
||||||
|
" cap = cv2.VideoCapture(video_path)\n",
|
||||||
|
" video_frames_for_vis = []\n",
|
||||||
|
" while True:\n",
|
||||||
|
" ret, frame = cap.read()\n",
|
||||||
|
" if not ret:\n",
|
||||||
|
" break\n",
|
||||||
|
" video_frames_for_vis.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n",
|
||||||
|
" cap.release()\n",
|
||||||
|
"else:\n",
|
||||||
|
" video_frames_for_vis = glob.glob(os.path.join(video_path, \"*.jpg\"))\n",
|
||||||
|
" try:\n",
|
||||||
|
" video_frames_for_vis.sort(\n",
|
||||||
|
" key=lambda p: int(os.path.splitext(os.path.basename(p))[0])\n",
|
||||||
|
" )\n",
|
||||||
|
" except ValueError:\n",
|
||||||
|
" print(\n",
|
||||||
|
" f'frame names are not in \"<frame_index>.jpg\" format: {video_frames_for_vis[:5]=}, '\n",
|
||||||
|
" f\"falling back to lexicographic sort.\"\n",
|
||||||
|
" )\n",
|
||||||
|
" video_frames_for_vis.sort()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Opening an inference session on this video\n",
|
||||||
|
"\n",
|
||||||
|
"SAM 3.1 requires stateful inference for interactive video segmentation, so we need to initialize an **inference session** on this video.\n",
|
||||||
|
"\n",
|
||||||
|
"During initialization, it loads all the video frames and stores their pixels in the session state."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"response = predictor.handle_request(\n",
|
||||||
|
" request=dict(\n",
|
||||||
|
" type=\"start_session\",\n",
|
||||||
|
" resource_path=video_path,\n",
|
||||||
|
" )\n",
|
||||||
|
")\n",
|
||||||
|
"session_id = response[\"session_id\"]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Video promptable concept segmentation with text\n",
|
||||||
|
"\n",
|
||||||
|
"Using SAM 3.1 you can describe objects using natural language, and the model will automatically detect and track all instances of that object throughout the video.\n",
|
||||||
|
"\n",
|
||||||
|
"In the example below, we add a text prompt on frame 0 and propagation throughout the video. Here we use the text prompt \"person\" to detect all people in the video. SAM 3.1 will automatically identify multiple person instances and assign each a unique object ID.\n",
|
||||||
|
"\n",
|
||||||
|
"Note that the first call might be slower due to setting up buffers. **You can rerun all the cells below when measuring speed.**"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# note: in case you already ran one text prompt and now want to switch to another text prompt\n",
|
||||||
|
"# it's required to reset the session first (otherwise the results would be wrong)\n",
|
||||||
|
"_ = predictor.handle_request(\n",
|
||||||
|
" request=dict(\n",
|
||||||
|
" type=\"reset_session\",\n",
|
||||||
|
" session_id=session_id,\n",
|
||||||
|
" )\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"prompt_text_str = \"person\"\n",
|
||||||
|
"frame_idx = 0 # add a text prompt on frame 0\n",
|
||||||
|
"response = predictor.handle_request(\n",
|
||||||
|
" request=dict(\n",
|
||||||
|
" type=\"add_prompt\",\n",
|
||||||
|
" session_id=session_id,\n",
|
||||||
|
" frame_index=frame_idx,\n",
|
||||||
|
" text=prompt_text_str,\n",
|
||||||
|
" )\n",
|
||||||
|
")\n",
|
||||||
|
"out = response[\"outputs\"]\n",
|
||||||
|
"\n",
|
||||||
|
"plt.close(\"all\")\n",
|
||||||
|
"visualize_formatted_frame_output(\n",
|
||||||
|
" frame_idx,\n",
|
||||||
|
" video_frames_for_vis,\n",
|
||||||
|
" outputs_list=[prepare_masks_for_visualization({frame_idx: out})],\n",
|
||||||
|
" titles=[\"SAM 3.1 Dense Tracking outputs\"],\n",
|
||||||
|
" figsize=(6, 4),\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# now we propagate the outputs from frame 0 to the end of the video and collect all outputs\n",
|
||||||
|
"outputs_per_frame = propagate_in_video(predictor, session_id)\n",
|
||||||
|
"\n",
|
||||||
|
"# finally, we reformat the outputs for visualization and plot the outputs every 60 frames\n",
|
||||||
|
"outputs_per_frame = prepare_masks_for_visualization(outputs_per_frame)\n",
|
||||||
|
"\n",
|
||||||
|
"vis_frame_stride = 60\n",
|
||||||
|
"plt.close(\"all\")\n",
|
||||||
|
"for frame_idx in range(0, len(outputs_per_frame), vis_frame_stride):\n",
|
||||||
|
" visualize_formatted_frame_output(\n",
|
||||||
|
" frame_idx,\n",
|
||||||
|
" video_frames_for_vis,\n",
|
||||||
|
" outputs_list=[outputs_per_frame],\n",
|
||||||
|
" titles=[\"SAM 3.1 Dense Tracking outputs\"],\n",
|
||||||
|
" figsize=(6, 4),\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Removing objects\n",
|
||||||
|
"\n",
|
||||||
|
"We can remove individual objects using their id.\n",
|
||||||
|
"\n",
|
||||||
|
"As an example, let's remove object 2 (which is the dancer in the front)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# we pick id 2, which is the dancer in the front\n",
|
||||||
|
"obj_id = 2\n",
|
||||||
|
"response = predictor.handle_request(\n",
|
||||||
|
" request=dict(\n",
|
||||||
|
" type=\"remove_object\",\n",
|
||||||
|
" session_id=session_id,\n",
|
||||||
|
" obj_id=obj_id,\n",
|
||||||
|
" )\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# now we propagate the outputs from frame 0 to the end of the video and collect all outputs\n",
|
||||||
|
"outputs_per_frame = propagate_in_video(predictor, session_id)\n",
|
||||||
|
"\n",
|
||||||
|
"# finally, we reformat the outputs for visualization and plot the outputs every 60 frames\n",
|
||||||
|
"outputs_per_frame = prepare_masks_for_visualization(outputs_per_frame)\n",
|
||||||
|
"\n",
|
||||||
|
"vis_frame_stride = 60\n",
|
||||||
|
"plt.close(\"all\")\n",
|
||||||
|
"for frame_idx in range(0, len(outputs_per_frame), vis_frame_stride):\n",
|
||||||
|
" visualize_formatted_frame_output(\n",
|
||||||
|
" frame_idx,\n",
|
||||||
|
" video_frames_for_vis,\n",
|
||||||
|
" outputs_list=[outputs_per_frame],\n",
|
||||||
|
" titles=[\"SAM 3.1 Dense Tracking outputs\"],\n",
|
||||||
|
" figsize=(6, 4),\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Adding new objects with point prompts\n",
|
||||||
|
"\n",
|
||||||
|
"We can add new objects through point prompts.\n",
|
||||||
|
"\n",
|
||||||
|
"Assuming that we've changed our mind, and now that we want to add back the dancer in the front (whom we just removed in the step above). We can use interactive clicks to add her back."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"sample_img = Image.fromarray(load_frame(video_frames_for_vis[0]))\n",
|
||||||
|
"\n",
|
||||||
|
"IMG_WIDTH, IMG_HEIGHT = sample_img.size"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# let's add back the dancer via point prompts.\n",
|
||||||
|
"# we will use a single positive click to add the dancer back.\n",
|
||||||
|
"\n",
|
||||||
|
"frame_idx = 0\n",
|
||||||
|
"obj_id = 2\n",
|
||||||
|
"points_abs = np.array(\n",
|
||||||
|
" [\n",
|
||||||
|
" [760, 550], # positive click\n",
|
||||||
|
" ]\n",
|
||||||
|
")\n",
|
||||||
|
"# positive clicks have label 1, while negative clicks have label 0\n",
|
||||||
|
"labels = np.array([1])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# convert points and labels to tensors; also convert to relative coordinates\n",
|
||||||
|
"points_tensor = torch.tensor(\n",
|
||||||
|
" abs_to_rel_coords(points_abs, IMG_WIDTH, IMG_HEIGHT, coord_type=\"point\"),\n",
|
||||||
|
" dtype=torch.float32,\n",
|
||||||
|
")\n",
|
||||||
|
"points_labels_tensor = torch.tensor(labels, dtype=torch.int32)\n",
|
||||||
|
"\n",
|
||||||
|
"response = predictor.handle_request(\n",
|
||||||
|
" request=dict(\n",
|
||||||
|
" type=\"add_prompt\",\n",
|
||||||
|
" session_id=session_id,\n",
|
||||||
|
" frame_index=frame_idx,\n",
|
||||||
|
" points=points_tensor,\n",
|
||||||
|
" point_labels=points_labels_tensor,\n",
|
||||||
|
" obj_id=obj_id,\n",
|
||||||
|
" )\n",
|
||||||
|
")\n",
|
||||||
|
"out = response[\"outputs\"]\n",
|
||||||
|
"\n",
|
||||||
|
"plt.close(\"all\")\n",
|
||||||
|
"visualize_formatted_frame_output(\n",
|
||||||
|
" frame_idx,\n",
|
||||||
|
" video_frames_for_vis,\n",
|
||||||
|
" outputs_list=[prepare_masks_for_visualization({frame_idx: out})],\n",
|
||||||
|
" titles=[\"SAM 3.1 Dense Tracking outputs\"],\n",
|
||||||
|
" figsize=(6, 4),\n",
|
||||||
|
" points_list=[points_abs],\n",
|
||||||
|
" points_labels_list=[labels],\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# now we propagate the outputs from frame 0 to the end of the video and collect all outputs\n",
|
||||||
|
"outputs_per_frame = propagate_in_video(predictor, session_id)\n",
|
||||||
|
"\n",
|
||||||
|
"# finally, we reformat the outputs for visualization and plot the outputs every 60 frames\n",
|
||||||
|
"outputs_per_frame = prepare_masks_for_visualization(outputs_per_frame)\n",
|
||||||
|
"\n",
|
||||||
|
"vis_frame_stride = 60\n",
|
||||||
|
"plt.close(\"all\")\n",
|
||||||
|
"for frame_idx in range(0, len(outputs_per_frame), vis_frame_stride):\n",
|
||||||
|
" visualize_formatted_frame_output(\n",
|
||||||
|
" frame_idx,\n",
|
||||||
|
" video_frames_for_vis,\n",
|
||||||
|
" outputs_list=[outputs_per_frame],\n",
|
||||||
|
" titles=[\"SAM 3.1 Dense Tracking outputs\"],\n",
|
||||||
|
" figsize=(6, 4),\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Refining an existing object with point prompts\n",
|
||||||
|
"\n",
|
||||||
|
"We can also refine the segmentation mask of an existing object through point prompts.\n",
|
||||||
|
"\n",
|
||||||
|
"Assuming that we've changed our mind (again) -- for Object ID 2 (the dancer in the front whom we just added back in the step above), now we only want to segment her T-shirt instead of her whole body. We can adjust the segmentation mask with a few more positive and negative clicks."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# For the dancer in the front, suppose now we only want to segment her T-shirt instead of her whole body\n",
|
||||||
|
"# we will use 2 positive clicks and 2 negative clicks to select her shirt.\n",
|
||||||
|
"\n",
|
||||||
|
"refine_object_3 = True\n",
|
||||||
|
"\n",
|
||||||
|
"if refine_object_3:\n",
|
||||||
|
" frame_idx = 0\n",
|
||||||
|
" obj_id = 3\n",
|
||||||
|
" points_abs = np.array(\n",
|
||||||
|
" [\n",
|
||||||
|
" [800, 135], # positive click\n",
|
||||||
|
" [800, 180], # negative click\n",
|
||||||
|
" ]\n",
|
||||||
|
" )\n",
|
||||||
|
" # positive clicks have label 1, while negative clicks have label 0\n",
|
||||||
|
" labels = np.array([1, 0])\n",
|
||||||
|
" \n",
|
||||||
|
"else:\n",
|
||||||
|
" frame_idx = 0\n",
|
||||||
|
" obj_id = 2\n",
|
||||||
|
" points_abs = np.array(\n",
|
||||||
|
" [\n",
|
||||||
|
" [740, 450], # positive click\n",
|
||||||
|
" [760, 630], # negative click\n",
|
||||||
|
" [840, 640], # negative click\n",
|
||||||
|
" [760, 550], # positive click\n",
|
||||||
|
" ]\n",
|
||||||
|
" )\n",
|
||||||
|
" # positive clicks have label 1, while negative clicks have label 0\n",
|
||||||
|
" labels = np.array([1, 0, 0, 1])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# convert points and labels to tensors; also convert to relative coordinates\n",
|
||||||
|
"points_tensor = torch.tensor(\n",
|
||||||
|
" abs_to_rel_coords(points_abs, IMG_WIDTH, IMG_HEIGHT, coord_type=\"point\"),\n",
|
||||||
|
" dtype=torch.float32,\n",
|
||||||
|
")\n",
|
||||||
|
"points_labels_tensor = torch.tensor(labels, dtype=torch.int32)\n",
|
||||||
|
"\n",
|
||||||
|
"response = predictor.handle_request(\n",
|
||||||
|
" request=dict(\n",
|
||||||
|
" type=\"add_prompt\",\n",
|
||||||
|
" session_id=session_id,\n",
|
||||||
|
" frame_index=frame_idx,\n",
|
||||||
|
" points=points_tensor,\n",
|
||||||
|
" point_labels=points_labels_tensor,\n",
|
||||||
|
" obj_id=obj_id,\n",
|
||||||
|
" )\n",
|
||||||
|
")\n",
|
||||||
|
"out = response[\"outputs\"]\n",
|
||||||
|
"\n",
|
||||||
|
"plt.close(\"all\")\n",
|
||||||
|
"visualize_formatted_frame_output(\n",
|
||||||
|
" frame_idx,\n",
|
||||||
|
" video_frames_for_vis,\n",
|
||||||
|
" outputs_list=[prepare_masks_for_visualization({frame_idx: out})],\n",
|
||||||
|
" titles=[\"SAM 3.1 Dense Tracking outputs\"],\n",
|
||||||
|
" figsize=(6, 4),\n",
|
||||||
|
" points_list=[points_abs],\n",
|
||||||
|
" points_labels_list=[labels],\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# now we propagate the outputs from frame 0 to the end of the video and collect all outputs\n",
|
||||||
|
"outputs_per_frame = propagate_in_video(predictor, session_id)\n",
|
||||||
|
"\n",
|
||||||
|
"# finally, we reformat the outputs for visualization and plot the outputs every 60 frames\n",
|
||||||
|
"outputs_per_frame = prepare_masks_for_visualization(outputs_per_frame)\n",
|
||||||
|
"\n",
|
||||||
|
"vis_frame_stride = 60\n",
|
||||||
|
"plt.close(\"all\")\n",
|
||||||
|
"for frame_idx in range(0, len(outputs_per_frame), vis_frame_stride):\n",
|
||||||
|
" visualize_formatted_frame_output(\n",
|
||||||
|
" frame_idx,\n",
|
||||||
|
" video_frames_for_vis,\n",
|
||||||
|
" outputs_list=[outputs_per_frame],\n",
|
||||||
|
" titles=[\"SAM 3.1 Dense Tracking outputs\"],\n",
|
||||||
|
" figsize=(6, 4),\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Close session\n",
|
||||||
|
"\n",
|
||||||
|
"Each session is tied to a single video. We can close the session after inference to free up its resources.\n",
|
||||||
|
"\n",
|
||||||
|
"(Then, you may start a new session on another video.)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"_ = predictor.handle_request(\n",
|
||||||
|
" request=dict(\n",
|
||||||
|
" type=\"close_session\",\n",
|
||||||
|
" session_id=session_id,\n",
|
||||||
|
" )\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"fileHeader": "",
|
||||||
|
"fileUid": "0c5b0843-1bcb-4dac-8c85-3f149debb325",
|
||||||
|
"isAdHoc": false,
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 3 (ipykernel)",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.10.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 4
|
||||||
|
}
|
||||||
+2
-2
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
# pyre-unsafe
|
# pyre-unsafe
|
||||||
|
|
||||||
from .model_builder import build_sam3_image_model
|
from .model_builder import build_sam3_image_model, build_sam3_predictor
|
||||||
|
|
||||||
__version__ = "0.1.0"
|
__version__ = "0.1.0"
|
||||||
|
|
||||||
__all__ = ["build_sam3_image_model"]
|
__all__ = ["build_sam3_image_model", "build_sam3_predictor"]
|
||||||
|
|||||||
@@ -296,9 +296,9 @@ def agent_inference(
|
|||||||
assert LATEST_SAM3_TEXT_PROMPT != ""
|
assert LATEST_SAM3_TEXT_PROMPT != ""
|
||||||
|
|
||||||
# Make sure that the last message is a image
|
# Make sure that the last message is a image
|
||||||
assert messages[-1]["content"][1]["type"] == "image", (
|
assert (
|
||||||
"Second content element should be an image"
|
messages[-1]["content"][1]["type"] == "image"
|
||||||
)
|
), "Second content element should be an image"
|
||||||
messages.pop() # Remove the last user message
|
messages.pop() # Remove the last user message
|
||||||
# Add simplified replacement message
|
# Add simplified replacement message
|
||||||
simplified_message = {
|
simplified_message = {
|
||||||
|
|||||||
@@ -84,9 +84,9 @@ class BoxMode(IntEnum):
|
|||||||
], "Relative mode not yet supported!"
|
], "Relative mode not yet supported!"
|
||||||
|
|
||||||
if from_mode == BoxMode.XYWHA_ABS and to_mode == BoxMode.XYXY_ABS:
|
if from_mode == BoxMode.XYWHA_ABS and to_mode == BoxMode.XYXY_ABS:
|
||||||
assert arr.shape[-1] == 5, (
|
assert (
|
||||||
"The last dimension of input shape must be 5 for XYWHA format"
|
arr.shape[-1] == 5
|
||||||
)
|
), "The last dimension of input shape must be 5 for XYWHA format"
|
||||||
original_dtype = arr.dtype
|
original_dtype = arr.dtype
|
||||||
arr = arr.double()
|
arr = arr.double()
|
||||||
|
|
||||||
@@ -244,9 +244,9 @@ class Boxes:
|
|||||||
if isinstance(item, int):
|
if isinstance(item, int):
|
||||||
return Boxes(self.tensor[item].view(1, -1))
|
return Boxes(self.tensor[item].view(1, -1))
|
||||||
b = self.tensor[item]
|
b = self.tensor[item]
|
||||||
assert b.dim() == 2, (
|
assert (
|
||||||
"Indexing on Boxes with {} failed to return a matrix!".format(item)
|
b.dim() == 2
|
||||||
)
|
), "Indexing on Boxes with {} failed to return a matrix!".format(item)
|
||||||
return Boxes(b)
|
return Boxes(b)
|
||||||
|
|
||||||
def __len__(self) -> int:
|
def __len__(self) -> int:
|
||||||
@@ -424,11 +424,11 @@ def matched_pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:
|
|||||||
Returns:
|
Returns:
|
||||||
Tensor: iou, sized [N].
|
Tensor: iou, sized [N].
|
||||||
"""
|
"""
|
||||||
assert len(boxes1) == len(boxes2), (
|
assert len(boxes1) == len(
|
||||||
"boxlists should have the samenumber of entries, got {}, {}".format(
|
boxes2
|
||||||
|
), "boxlists should have the samenumber of entries, got {}, {}".format(
|
||||||
len(boxes1), len(boxes2)
|
len(boxes1), len(boxes2)
|
||||||
)
|
)
|
||||||
)
|
|
||||||
area1 = boxes1.area() # [N]
|
area1 = boxes1.area() # [N]
|
||||||
area2 = boxes2.area() # [N]
|
area2 = boxes2.area() # [N]
|
||||||
box1, box2 = boxes1.tensor, boxes2.tensor
|
box1, box2 = boxes1.tensor, boxes2.tensor
|
||||||
|
|||||||
@@ -141,11 +141,11 @@ class BitMasks:
|
|||||||
if isinstance(item, int):
|
if isinstance(item, int):
|
||||||
return BitMasks(self.tensor[item].unsqueeze(0))
|
return BitMasks(self.tensor[item].unsqueeze(0))
|
||||||
m = self.tensor[item]
|
m = self.tensor[item]
|
||||||
assert m.dim() == 3, (
|
assert (
|
||||||
"Indexing on BitMasks with {} returns a tensor with shape {}!".format(
|
m.dim() == 3
|
||||||
|
), "Indexing on BitMasks with {} returns a tensor with shape {}!".format(
|
||||||
item, m.shape
|
item, m.shape
|
||||||
)
|
)
|
||||||
)
|
|
||||||
return BitMasks(m)
|
return BitMasks(m)
|
||||||
|
|
||||||
@torch.jit.unused
|
@torch.jit.unused
|
||||||
|
|||||||
@@ -363,9 +363,9 @@ class RotatedBoxes(Boxes):
|
|||||||
if isinstance(item, int):
|
if isinstance(item, int):
|
||||||
return RotatedBoxes(self.tensor[item].view(1, -1))
|
return RotatedBoxes(self.tensor[item].view(1, -1))
|
||||||
b = self.tensor[item]
|
b = self.tensor[item]
|
||||||
assert b.dim() == 2, (
|
assert (
|
||||||
"Indexing on RotatedBoxes with {} failed to return a matrix!".format(item)
|
b.dim() == 2
|
||||||
)
|
), "Indexing on RotatedBoxes with {} failed to return a matrix!".format(item)
|
||||||
return RotatedBoxes(b)
|
return RotatedBoxes(b)
|
||||||
|
|
||||||
def __len__(self) -> int:
|
def __len__(self) -> int:
|
||||||
|
|||||||
@@ -221,9 +221,9 @@ class _PanopticPrediction:
|
|||||||
empty_ids.append(id)
|
empty_ids.append(id)
|
||||||
if len(empty_ids) == 0:
|
if len(empty_ids) == 0:
|
||||||
return np.zeros(self._seg.shape, dtype=np.uint8)
|
return np.zeros(self._seg.shape, dtype=np.uint8)
|
||||||
assert len(empty_ids) == 1, (
|
assert (
|
||||||
">1 ids corresponds to no labels. This is currently not supported"
|
len(empty_ids) == 1
|
||||||
)
|
), ">1 ids corresponds to no labels. This is currently not supported"
|
||||||
return (self._seg != empty_ids[0]).numpy().astype(np.bool)
|
return (self._seg != empty_ids[0]).numpy().astype(np.bool)
|
||||||
|
|
||||||
def semantic_masks(self):
|
def semantic_masks(self):
|
||||||
|
|||||||
+18
-18
@@ -126,9 +126,9 @@ class COCOCustom(COCO):
|
|||||||
# MODIFICATION: faster and cached subset check
|
# MODIFICATION: faster and cached subset check
|
||||||
if not hasattr(self, "img_id_set"):
|
if not hasattr(self, "img_id_set"):
|
||||||
self.img_id_set = set(self.getImgIds())
|
self.img_id_set = set(self.getImgIds())
|
||||||
assert set(annsImgIds).issubset(self.img_id_set), (
|
assert set(annsImgIds).issubset(
|
||||||
"Results do not correspond to current coco set"
|
self.img_id_set
|
||||||
)
|
), "Results do not correspond to current coco set"
|
||||||
# END MODIFICATION
|
# END MODIFICATION
|
||||||
if "caption" in anns[0]:
|
if "caption" in anns[0]:
|
||||||
imgIds = set([img["id"] for img in res.dataset["images"]]) & set(
|
imgIds = set([img["id"] for img in res.dataset["images"]]) & set(
|
||||||
@@ -301,9 +301,9 @@ class CGF1Eval(COCOeval):
|
|||||||
TP = (match_scores >= thresh).sum()
|
TP = (match_scores >= thresh).sum()
|
||||||
FP = len(dt) - TP
|
FP = len(dt) - TP
|
||||||
FN = len(gt) - TP
|
FN = len(gt) - TP
|
||||||
assert FP >= 0 and FN >= 0, (
|
assert (
|
||||||
f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}"
|
FP >= 0 and FN >= 0
|
||||||
)
|
), f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}"
|
||||||
TPs.append(TP)
|
TPs.append(TP)
|
||||||
FPs.append(FP)
|
FPs.append(FP)
|
||||||
FNs.append(FN)
|
FNs.append(FN)
|
||||||
@@ -599,9 +599,9 @@ class CGF1Evaluator:
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
assert len(self.coco_gts) > 0, "No ground truth provided for evaluation."
|
assert len(self.coco_gts) > 0, "No ground truth provided for evaluation."
|
||||||
assert len(self.coco_gts) == len(self.coco_evals), (
|
assert len(self.coco_gts) == len(
|
||||||
"Mismatch in number of ground truths and evaluators."
|
self.coco_evals
|
||||||
)
|
), "Mismatch in number of ground truths and evaluators."
|
||||||
|
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print(f"Loading predictions from {pred_file}")
|
print(f"Loading predictions from {pred_file}")
|
||||||
@@ -668,17 +668,17 @@ class CGF1Evaluator:
|
|||||||
if len(scorings) == 1:
|
if len(scorings) == 1:
|
||||||
return scorings[0]
|
return scorings[0]
|
||||||
|
|
||||||
assert scorings[0].ndim == 3, (
|
assert (
|
||||||
f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
|
scorings[0].ndim == 3
|
||||||
)
|
), f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
|
||||||
assert scorings[0].shape[0] == 1, (
|
assert (
|
||||||
f"Expecting a single category, got {scorings[0].shape[0]}"
|
scorings[0].shape[0] == 1
|
||||||
)
|
), f"Expecting a single category, got {scorings[0].shape[0]}"
|
||||||
|
|
||||||
for scoring in scorings:
|
for scoring in scorings:
|
||||||
assert scoring.shape == scorings[0].shape, (
|
assert (
|
||||||
f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
|
scoring.shape == scorings[0].shape
|
||||||
)
|
), f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
|
||||||
|
|
||||||
selected_imgs = []
|
selected_imgs = []
|
||||||
for img_id in range(scorings[0].shape[-1]):
|
for img_id in range(scorings[0].shape[-1]):
|
||||||
|
|||||||
@@ -751,9 +751,9 @@ def loadRes(self, resFile):
|
|||||||
anns = resFile
|
anns = resFile
|
||||||
assert type(anns) == list, "results in not an array of objects"
|
assert type(anns) == list, "results in not an array of objects"
|
||||||
annsImgIds = [ann["image_id"] for ann in anns]
|
annsImgIds = [ann["image_id"] for ann in anns]
|
||||||
assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), (
|
assert set(annsImgIds) == (
|
||||||
"Results do not correspond to current coco set"
|
set(annsImgIds) & set(self.getImgIds())
|
||||||
)
|
), "Results do not correspond to current coco set"
|
||||||
if "caption" in anns[0]:
|
if "caption" in anns[0]:
|
||||||
imgIds = set([img["id"] for img in res.dataset["images"]]) & set(
|
imgIds = set([img["id"] for img in res.dataset["images"]]) & set(
|
||||||
[ann["image_id"] for ann in anns]
|
[ann["image_id"] for ann in anns]
|
||||||
|
|||||||
@@ -83,9 +83,9 @@ class PredictionDumper:
|
|||||||
self.merge_predictions = merge_predictions
|
self.merge_predictions = merge_predictions
|
||||||
self.pred_file_evaluators = pred_file_evaluators
|
self.pred_file_evaluators = pred_file_evaluators
|
||||||
if self.pred_file_evaluators is not None:
|
if self.pred_file_evaluators is not None:
|
||||||
assert merge_predictions, (
|
assert (
|
||||||
"merge_predictions must be True if pred_file_evaluators are provided"
|
merge_predictions
|
||||||
)
|
), "merge_predictions must be True if pred_file_evaluators are provided"
|
||||||
assert self.dump_dir is not None, "dump_dir must be provided"
|
assert self.dump_dir is not None, "dump_dir must be provided"
|
||||||
|
|
||||||
if is_main_process():
|
if is_main_process():
|
||||||
|
|||||||
+12
-12
@@ -154,9 +154,9 @@ class DemoEval(COCOeval):
|
|||||||
TP = (match_scores >= thresh).sum()
|
TP = (match_scores >= thresh).sum()
|
||||||
FP = len(dt) - TP
|
FP = len(dt) - TP
|
||||||
FN = len(gt) - TP
|
FN = len(gt) - TP
|
||||||
assert FP >= 0 and FN >= 0, (
|
assert (
|
||||||
f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}"
|
FP >= 0 and FN >= 0
|
||||||
)
|
), f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}"
|
||||||
TPs.append(TP)
|
TPs.append(TP)
|
||||||
FPs.append(FP)
|
FPs.append(FP)
|
||||||
FNs.append(FN)
|
FNs.append(FN)
|
||||||
@@ -526,17 +526,17 @@ class DemoEvaluator(CocoEvaluator):
|
|||||||
if len(scorings) == 1:
|
if len(scorings) == 1:
|
||||||
return scorings[0]
|
return scorings[0]
|
||||||
|
|
||||||
assert scorings[0].ndim == 3, (
|
assert (
|
||||||
f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
|
scorings[0].ndim == 3
|
||||||
)
|
), f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}"
|
||||||
assert scorings[0].shape[0] == 1, (
|
assert (
|
||||||
f"Expecting a single category, got {scorings[0].shape[0]}"
|
scorings[0].shape[0] == 1
|
||||||
)
|
), f"Expecting a single category, got {scorings[0].shape[0]}"
|
||||||
|
|
||||||
for scoring in scorings:
|
for scoring in scorings:
|
||||||
assert scoring.shape == scorings[0].shape, (
|
assert (
|
||||||
f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
|
scoring.shape == scorings[0].shape
|
||||||
)
|
), f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
|
||||||
|
|
||||||
selected_imgs = []
|
selected_imgs = []
|
||||||
for img_id in range(scorings[0].shape[-1]):
|
for img_id in range(scorings[0].shape[-1]):
|
||||||
|
|||||||
@@ -83,9 +83,9 @@ class PostProcessImage(nn.Module):
|
|||||||
ret_tensordict: Experimental argument. If true, return a tensordict.TensorDict instead of a list of dictionaries for easier manipulation.
|
ret_tensordict: Experimental argument. If true, return a tensordict.TensorDict instead of a list of dictionaries for easier manipulation.
|
||||||
"""
|
"""
|
||||||
if ret_tensordict:
|
if ret_tensordict:
|
||||||
assert consistent is True, (
|
assert (
|
||||||
"We don't support returning TensorDict if the outputs have different shapes"
|
consistent is True
|
||||||
) # NOTE: It's possible but we don't support it.
|
), "We don't support returning TensorDict if the outputs have different shapes" # NOTE: It's possible but we don't support it.
|
||||||
assert self.detection_threshold <= 0.0, "TODO: implement?"
|
assert self.detection_threshold <= 0.0, "TODO: implement?"
|
||||||
try:
|
try:
|
||||||
from tensordict import TensorDict
|
from tensordict import TensorDict
|
||||||
@@ -118,9 +118,7 @@ class PostProcessImage(nn.Module):
|
|||||||
|
|
||||||
if boxes is None:
|
if boxes is None:
|
||||||
assert out_masks is not None
|
assert out_masks is not None
|
||||||
assert not ret_tensordict, (
|
assert not ret_tensordict, "We don't support returning TensorDict if the output does not contain boxes"
|
||||||
"We don't support returning TensorDict if the output does not contain boxes"
|
|
||||||
)
|
|
||||||
B = len(out_masks)
|
B = len(out_masks)
|
||||||
boxes = [None] * B
|
boxes = [None] * B
|
||||||
scores = [None] * B
|
scores = [None] * B
|
||||||
@@ -420,9 +418,9 @@ class PostProcessAPIVideo(PostProcessImage):
|
|||||||
if video_id == -1:
|
if video_id == -1:
|
||||||
video_id = unique_vid_id.item()
|
video_id = unique_vid_id.item()
|
||||||
else:
|
else:
|
||||||
assert video_id == unique_vid_id.item(), (
|
assert (
|
||||||
"We can only postprocess one video per datapoint"
|
video_id == unique_vid_id.item()
|
||||||
)
|
), "We can only postprocess one video per datapoint"
|
||||||
# keeping track of which objects appear in the current frame
|
# keeping track of which objects appear in the current frame
|
||||||
obj_ids_per_frame = frame_outs["pred_object_ids"]
|
obj_ids_per_frame = frame_outs["pred_object_ids"]
|
||||||
assert obj_ids_per_frame.size(-1) == frame_outs["pred_logits"].size(-2)
|
assert obj_ids_per_frame.size(-1) == frame_outs["pred_logits"].size(-2)
|
||||||
|
|||||||
@@ -95,9 +95,9 @@ class YTVIS(COCO):
|
|||||||
anns = resFile
|
anns = resFile
|
||||||
assert type(anns) == list, "results is not an array of objects"
|
assert type(anns) == list, "results is not an array of objects"
|
||||||
annsImgIds = [ann["image_id"] for ann in anns]
|
annsImgIds = [ann["image_id"] for ann in anns]
|
||||||
assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), (
|
assert set(annsImgIds) == (
|
||||||
"Results do not correspond to current coco set"
|
set(annsImgIds) & set(self.getImgIds())
|
||||||
)
|
), "Results do not correspond to current coco set"
|
||||||
if "bboxes" in anns[0] and not anns[0]["bboxes"] == []:
|
if "bboxes" in anns[0] and not anns[0]["bboxes"] == []:
|
||||||
res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
|
res.dataset["categories"] = copy.deepcopy(self.dataset["categories"])
|
||||||
for id, ann in enumerate(anns):
|
for id, ann in enumerate(anns):
|
||||||
|
|||||||
+18
-16
@@ -109,7 +109,9 @@ class YTVISevalMixin:
|
|||||||
) # Num preds x Num GTS x Num frames
|
) # Num preds x Num GTS x Num frames
|
||||||
inter = inter.sum(-1)
|
inter = inter.sum(-1)
|
||||||
union = union.sum(-1)
|
union = union.sum(-1)
|
||||||
assert (union > 0).all(), (
|
assert (
|
||||||
|
union > 0
|
||||||
|
).all(), (
|
||||||
"There exists a tracklet with zero GTs across time. This is suspicious"
|
"There exists a tracklet with zero GTs across time. This is suspicious"
|
||||||
)
|
)
|
||||||
return inter / union
|
return inter / union
|
||||||
@@ -134,9 +136,9 @@ class YTVISevalMixin:
|
|||||||
iou = inter / union
|
iou = inter / union
|
||||||
assert iou >= 0 and iou <= 1, "Encountered an error in IoU computation"
|
assert iou >= 0 and iou <= 1, "Encountered an error in IoU computation"
|
||||||
else:
|
else:
|
||||||
assert np.isclose(inter, 0) and np.isclose(union, 0), (
|
assert np.isclose(inter, 0) and np.isclose(
|
||||||
"Encountered an error in IoU computation"
|
union, 0
|
||||||
)
|
), "Encountered an error in IoU computation"
|
||||||
iou = 1
|
iou = 1
|
||||||
return iou
|
return iou
|
||||||
|
|
||||||
@@ -204,16 +206,16 @@ class YTVISResultsWriter:
|
|||||||
if len(prediction) == 0:
|
if len(prediction) == 0:
|
||||||
continue
|
continue
|
||||||
for k in ["boxes", "scores", "labels"]:
|
for k in ["boxes", "scores", "labels"]:
|
||||||
assert k in prediction, (
|
assert (
|
||||||
f"Expected predictions to have `{k}` key, available keys are {prediction.keys()}"
|
k in prediction
|
||||||
)
|
), f"Expected predictions to have `{k}` key, available keys are {prediction.keys()}"
|
||||||
if self.save_per_frame_scores:
|
if self.save_per_frame_scores:
|
||||||
assert "per_frame_scores" in prediction, (
|
assert (
|
||||||
f"Expected predictions to have `per_frame_scores` key, available keys are {prediction.keys()}"
|
"per_frame_scores" in prediction
|
||||||
)
|
), f"Expected predictions to have `per_frame_scores` key, available keys are {prediction.keys()}"
|
||||||
assert xor("masks" in prediction, "masks_rle" in prediction), (
|
assert xor(
|
||||||
f"Expected predictions to have either `masks` key or `masks_rle` key, available keys are {prediction.keys()}"
|
"masks" in prediction, "masks_rle" in prediction
|
||||||
)
|
), f"Expected predictions to have either `masks` key or `masks_rle` key, available keys are {prediction.keys()}"
|
||||||
|
|
||||||
boxes = prediction["boxes"]
|
boxes = prediction["boxes"]
|
||||||
boxes = convert_to_xywh(boxes).tolist()
|
boxes = convert_to_xywh(boxes).tolist()
|
||||||
@@ -221,9 +223,9 @@ class YTVISResultsWriter:
|
|||||||
labels = prediction["labels"].tolist()
|
labels = prediction["labels"].tolist()
|
||||||
if "masks" in prediction:
|
if "masks" in prediction:
|
||||||
masks = prediction["masks"].squeeze(2)
|
masks = prediction["masks"].squeeze(2)
|
||||||
assert masks.ndim == 4, (
|
assert (
|
||||||
"Expected masks to be of shape(N_preds,T_frames,H,W)"
|
masks.ndim == 4
|
||||||
)
|
), "Expected masks to be of shape(N_preds,T_frames,H,W)"
|
||||||
|
|
||||||
areas = [mask.flatten(1).sum(1).tolist() for mask in masks]
|
areas = [mask.flatten(1).sum(1).tolist() for mask in masks]
|
||||||
rles = [rle_encode(masklet) for masklet in masks]
|
rles = [rle_encode(masklet) for masklet in masks]
|
||||||
|
|||||||
+3
-3
@@ -42,9 +42,9 @@ def get_logger(name, level=logging.INFO):
|
|||||||
"""A command line logger."""
|
"""A command line logger."""
|
||||||
if "LOG_LEVEL" in os.environ:
|
if "LOG_LEVEL" in os.environ:
|
||||||
level = os.environ["LOG_LEVEL"].upper()
|
level = os.environ["LOG_LEVEL"].upper()
|
||||||
assert level in LOG_LEVELS, (
|
assert (
|
||||||
f"Invalid LOG_LEVEL: {level}, must be one of {list(LOG_LEVELS.keys())}"
|
level in LOG_LEVELS
|
||||||
)
|
), f"Invalid LOG_LEVEL: {level}, must be one of {list(LOG_LEVELS.keys())}"
|
||||||
level = LOG_LEVELS[level]
|
level = LOG_LEVELS[level]
|
||||||
logger = logging.getLogger(name)
|
logger = logging.getLogger(name)
|
||||||
logger.setLevel(level)
|
logger.setLevel(level)
|
||||||
|
|||||||
+61
-3
@@ -16,6 +16,53 @@ import torch
|
|||||||
MyTensor = Union[torch.Tensor, List[Any]]
|
MyTensor = Union[torch.Tensor, List[Any]]
|
||||||
|
|
||||||
|
|
||||||
|
class NestedTensor:
|
||||||
|
def __init__(self, tensors, mask):
|
||||||
|
self.tensors = tensors
|
||||||
|
self.mask = mask
|
||||||
|
|
||||||
|
def to(self, *args, **kwargs):
|
||||||
|
cast_tensor = self.tensors.to(*args, **kwargs)
|
||||||
|
cast_mask = self.mask.to(*args, **kwargs) if self.mask is not None else None
|
||||||
|
return type(self)(cast_tensor, cast_mask)
|
||||||
|
|
||||||
|
def clone(self):
|
||||||
|
new_tensors = self.tensors.clone()
|
||||||
|
new_mask = None if self.mask is None else self.mask.clone()
|
||||||
|
return NestedTensor(new_tensors, new_mask)
|
||||||
|
|
||||||
|
def __getitem__(self, idx):
|
||||||
|
return self.tensors[idx]
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self.tensors)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def device(self):
|
||||||
|
return self.tensors.device
|
||||||
|
|
||||||
|
@property
|
||||||
|
def shape(self):
|
||||||
|
return self.tensors.shape
|
||||||
|
|
||||||
|
# custom memory pinning method on custom type
|
||||||
|
def pin_memory(self, device=None):
|
||||||
|
self.tensors = self.tensors.pin_memory(device)
|
||||||
|
if self.mask is not None:
|
||||||
|
self.mask = self.mask.pin_memory(device)
|
||||||
|
|
||||||
|
|
||||||
|
# Register NestedTensor as a pytree node so tree_map_only can traverse into it
|
||||||
|
# (matches onevision/utils/misc.py registration)
|
||||||
|
from torch.utils import _pytree as pytree
|
||||||
|
|
||||||
|
pytree.register_pytree_node(
|
||||||
|
NestedTensor,
|
||||||
|
lambda x: ([x.tensors, x.mask], None),
|
||||||
|
lambda values, _: NestedTensor(values[0], values[1]),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def interpolate(
|
def interpolate(
|
||||||
input, size=None, scale_factor=None, mode="nearest", align_corners=None
|
input, size=None, scale_factor=None, mode="nearest", align_corners=None
|
||||||
):
|
):
|
||||||
@@ -28,9 +75,9 @@ def interpolate(
|
|||||||
input, size, scale_factor, mode, align_corners
|
input, size, scale_factor, mode, align_corners
|
||||||
)
|
)
|
||||||
|
|
||||||
assert input.shape[0] != 0 or input.shape[1] != 0, (
|
assert (
|
||||||
"At least one of the two first dimensions must be non zero"
|
input.shape[0] != 0 or input.shape[1] != 0
|
||||||
)
|
), "At least one of the two first dimensions must be non zero"
|
||||||
|
|
||||||
if input.shape[1] == 0:
|
if input.shape[1] == 0:
|
||||||
# Pytorch doesn't support null dimension on the channel dimension, so we transpose to fake a null batch dim
|
# Pytorch doesn't support null dimension on the channel dimension, so we transpose to fake a null batch dim
|
||||||
@@ -81,6 +128,15 @@ class FindStage:
|
|||||||
# This is beneficial for tracking in videos without the need for pointers.
|
# This is beneficial for tracking in videos without the need for pointers.
|
||||||
object_ids: Optional[List[List]] = None # List of objects per query
|
object_ids: Optional[List[List]] = None # List of objects per query
|
||||||
|
|
||||||
|
# Multiplex-specific fields (used by sam3_demo_multiplex)
|
||||||
|
img_ids_np: Optional[Any] = None
|
||||||
|
input_boxes_before_embed: Optional[MyTensor] = None
|
||||||
|
input_boxes_before_embed__type = torch.float
|
||||||
|
input_points_before_embed: Optional[MyTensor] = None
|
||||||
|
input_points_before_embed__type = torch.float
|
||||||
|
ptrs: Optional[Any] = None
|
||||||
|
ptrs_seg: Optional[Any] = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class BatchedFindTarget:
|
class BatchedFindTarget:
|
||||||
@@ -165,6 +221,7 @@ class BatchedDatapoint:
|
|||||||
find_targets: List[BatchedFindTarget]
|
find_targets: List[BatchedFindTarget]
|
||||||
find_metadatas: List[BatchedInferenceMetadata]
|
find_metadatas: List[BatchedInferenceMetadata]
|
||||||
raw_images: Optional[List[Any]] = None
|
raw_images: Optional[List[Any]] = None
|
||||||
|
get_queries: Optional[Any] = None
|
||||||
|
|
||||||
|
|
||||||
def convert_my_tensors(obj):
|
def convert_my_tensors(obj):
|
||||||
@@ -188,6 +245,7 @@ def convert_my_tensors(obj):
|
|||||||
):
|
):
|
||||||
stack_dim = 0
|
stack_dim = 0
|
||||||
if field.name in [
|
if field.name in [
|
||||||
|
"input_boxes_before_embed",
|
||||||
"input_boxes",
|
"input_boxes",
|
||||||
"input_boxes_label",
|
"input_boxes_label",
|
||||||
]:
|
]:
|
||||||
|
|||||||
+434
-13
@@ -6,12 +6,17 @@ Transformer decoder.
|
|||||||
Inspired from Pytorch's version, adds the pre-norm variant
|
Inspired from Pytorch's version, adds the pre-norm variant
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import Any, Dict, List, Optional
|
import math
|
||||||
|
from functools import partial
|
||||||
|
from typing import Any, Dict, List, Optional, Union
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
|
import torch.nn.functional as torchF
|
||||||
|
from sam3.sam.rope import apply_rotary_enc, apply_rotary_enc_real, compute_axial_cis
|
||||||
from sam3.sam.transformer import RoPEAttention
|
from sam3.sam.transformer import RoPEAttention
|
||||||
from torch import nn, Tensor
|
from torch import nn, Tensor
|
||||||
|
from torch.nn.attention import sdpa_kernel, SDPBackend
|
||||||
from torchvision.ops.roi_align import RoIAlign
|
from torchvision.ops.roi_align import RoIAlign
|
||||||
|
|
||||||
from .act_ckpt_utils import activation_ckpt_wrapper
|
from .act_ckpt_utils import activation_ckpt_wrapper
|
||||||
@@ -439,9 +444,9 @@ class TransformerDecoder(nn.Module):
|
|||||||
- valid_ratios/spatial_shapes: bs, nlevel, 2
|
- valid_ratios/spatial_shapes: bs, nlevel, 2
|
||||||
"""
|
"""
|
||||||
if memory_mask is not None:
|
if memory_mask is not None:
|
||||||
assert self.boxRPB == "none", (
|
assert (
|
||||||
"inputting a memory_mask in the presence of boxRPB is unexpected/not implemented"
|
self.boxRPB == "none"
|
||||||
)
|
), "inputting a memory_mask in the presence of boxRPB is unexpected/not implemented"
|
||||||
|
|
||||||
apply_dac = apply_dac if apply_dac is not None else self.dac
|
apply_dac = apply_dac if apply_dac is not None else self.dac
|
||||||
if apply_dac:
|
if apply_dac:
|
||||||
@@ -511,18 +516,18 @@ class TransformerDecoder(nn.Module):
|
|||||||
query_pos = self.ref_point_head(query_sine_embed) # nq, bs, d_model
|
query_pos = self.ref_point_head(query_sine_embed) # nq, bs, d_model
|
||||||
|
|
||||||
if self.boxRPB != "none" and reference_boxes is not None:
|
if self.boxRPB != "none" and reference_boxes is not None:
|
||||||
assert spatial_shapes.shape[0] == 1, (
|
assert (
|
||||||
"only single scale support implemented"
|
spatial_shapes.shape[0] == 1
|
||||||
)
|
), "only single scale support implemented"
|
||||||
memory_mask = self._get_rpb_matrix(
|
memory_mask = self._get_rpb_matrix(
|
||||||
reference_boxes,
|
reference_boxes,
|
||||||
(spatial_shapes[0, 0], spatial_shapes[0, 1]),
|
(spatial_shapes[0, 0], spatial_shapes[0, 1]),
|
||||||
)
|
)
|
||||||
memory_mask = memory_mask.flatten(0, 1) # (bs*n_heads, nq, H*W)
|
memory_mask = memory_mask.flatten(0, 1) # (bs*n_heads, nq, H*W)
|
||||||
if self.training:
|
if self.training:
|
||||||
assert self.use_act_checkpoint, (
|
assert (
|
||||||
"Activation checkpointing not enabled in the decoder"
|
self.use_act_checkpoint
|
||||||
)
|
), "Activation checkpointing not enabled in the decoder"
|
||||||
output, presence_out = activation_ckpt_wrapper(layer)(
|
output, presence_out = activation_ckpt_wrapper(layer)(
|
||||||
tgt=output,
|
tgt=output,
|
||||||
tgt_query_pos=query_pos,
|
tgt_query_pos=query_pos,
|
||||||
@@ -671,9 +676,9 @@ class TransformerEncoderCrossAttention(nn.Module):
|
|||||||
src_pos[0],
|
src_pos[0],
|
||||||
)
|
)
|
||||||
|
|
||||||
assert src.shape[1] == prompt.shape[1], (
|
assert (
|
||||||
"Batch size must be the same for src and prompt"
|
src.shape[1] == prompt.shape[1]
|
||||||
)
|
), "Batch size must be the same for src and prompt"
|
||||||
|
|
||||||
output = src
|
output = src
|
||||||
|
|
||||||
@@ -951,3 +956,419 @@ class TransformerDecoderLayerv2(TransformerDecoderLayerv1):
|
|||||||
if self.pre_norm:
|
if self.pre_norm:
|
||||||
return self.forward_pre(*args, **kwds)
|
return self.forward_pre(*args, **kwds)
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
||||||
|
def functional_attention(
|
||||||
|
q: Tensor,
|
||||||
|
k: Tensor,
|
||||||
|
v: Tensor,
|
||||||
|
*,
|
||||||
|
dropout: float,
|
||||||
|
num_heads: int,
|
||||||
|
num_k_exclude_rope: int = 0,
|
||||||
|
freqs_cis: Optional[Tensor] = None,
|
||||||
|
freqs_cis_real: Optional[Tensor] = None,
|
||||||
|
freqs_cis_imag: Optional[Tensor] = None,
|
||||||
|
use_fa3: bool = False,
|
||||||
|
use_rope_real: bool = False,
|
||||||
|
rope_k_repeat: bool,
|
||||||
|
) -> Union[Tensor, tuple[Tensor, Tensor]]:
|
||||||
|
b, n, cq = q.shape
|
||||||
|
_, m, ck = k.shape
|
||||||
|
_, _, cv = v.shape
|
||||||
|
if b > 1:
|
||||||
|
assert k.shape[0] == v.shape[0] == b
|
||||||
|
else:
|
||||||
|
# broadcast-able
|
||||||
|
assert k.shape[0] == b == 1, f"{q.shape=} {k.shape=} {v.shape=}"
|
||||||
|
assert v.shape[1] == m
|
||||||
|
|
||||||
|
q = q.reshape(b, n, num_heads, cq // num_heads).transpose(1, 2)
|
||||||
|
k = k.reshape(b, m, num_heads, ck // num_heads).transpose(1, 2)
|
||||||
|
v = v.reshape(v.shape[0], m, num_heads, cv // num_heads).transpose(1, 2)
|
||||||
|
|
||||||
|
if freqs_cis is not None:
|
||||||
|
num_k_rope = k.size(-2) - num_k_exclude_rope
|
||||||
|
if use_rope_real:
|
||||||
|
q, k[:, :, :num_k_rope] = apply_rotary_enc_real(
|
||||||
|
q,
|
||||||
|
k[:, :, :num_k_rope],
|
||||||
|
freqs_cis_real=freqs_cis_real,
|
||||||
|
freqs_cis_imag=freqs_cis_imag,
|
||||||
|
repeat_freqs_k=rope_k_repeat,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
q, k[:, :, :num_k_rope] = apply_rotary_enc(
|
||||||
|
q,
|
||||||
|
k[:, :, :num_k_rope],
|
||||||
|
freqs_cis,
|
||||||
|
repeat_freqs_k=rope_k_repeat,
|
||||||
|
)
|
||||||
|
|
||||||
|
if use_fa3:
|
||||||
|
from sam3.perflib.fa3 import flash_attn_func
|
||||||
|
|
||||||
|
assert dropout == 0.0
|
||||||
|
out = flash_attn_func(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2))
|
||||||
|
else:
|
||||||
|
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
|
||||||
|
out = torchF.scaled_dot_product_attention(q, k, v, dropout_p=dropout)
|
||||||
|
out = out.transpose(1, 2) # B * n * n_heads * (cv // num_heads)
|
||||||
|
|
||||||
|
out = out.reshape(b, n, cv)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
class SimpleRoPEAttention(nn.Module):
|
||||||
|
"""
|
||||||
|
Attention with rotary position encoding.
|
||||||
|
This class is "simple" because it does not perform q/k/v/out projections.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
d_model: int,
|
||||||
|
num_heads: int,
|
||||||
|
dropout_p: float,
|
||||||
|
rope_theta=10000.0,
|
||||||
|
# whether to repeat q rope to match k length
|
||||||
|
# this is needed for cross-attention to memories
|
||||||
|
rope_k_repeat=False,
|
||||||
|
feat_sizes=(64, 64), # [w, h] for stride 16 feats at 1024 resolution
|
||||||
|
use_fa3: bool = False,
|
||||||
|
use_rope_real: bool = False,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
self.num_heads = num_heads
|
||||||
|
self.dropout_p = dropout_p
|
||||||
|
self.compute_cis = partial(
|
||||||
|
compute_axial_cis, dim=d_model // num_heads, theta=rope_theta
|
||||||
|
)
|
||||||
|
device = torch.device("cuda") if torch.cuda.is_available() else None
|
||||||
|
self.freqs_cis = self.compute_cis(
|
||||||
|
end_x=feat_sizes[0], end_y=feat_sizes[1], device=device
|
||||||
|
)
|
||||||
|
|
||||||
|
self.use_fa3 = use_fa3
|
||||||
|
self.use_rope_real = use_rope_real
|
||||||
|
if self.use_rope_real:
|
||||||
|
self.freqs_cis_real = self.freqs_cis.real
|
||||||
|
self.freqs_cis_imag = self.freqs_cis.imag
|
||||||
|
self.rope_k_repeat = rope_k_repeat
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
q: Tensor,
|
||||||
|
k: Tensor,
|
||||||
|
v: Tensor,
|
||||||
|
num_k_exclude_rope: int = 0,
|
||||||
|
) -> Union[Tensor, tuple[Tensor, Tensor]]:
|
||||||
|
# Apply rotary position encoding
|
||||||
|
w = h = math.sqrt(q.shape[-2])
|
||||||
|
self.freqs_cis = self.freqs_cis.to(q.device)
|
||||||
|
if self.freqs_cis.shape[0] != q.shape[-2]:
|
||||||
|
self.freqs_cis = self.compute_cis(end_x=w, end_y=h, device=q.device)
|
||||||
|
if self.use_rope_real:
|
||||||
|
self.freqs_cis_real = self.freqs_cis.real
|
||||||
|
self.freqs_cis_imag = self.freqs_cis.imag
|
||||||
|
if q.shape[-2] != k.shape[-2]:
|
||||||
|
assert self.rope_k_repeat
|
||||||
|
|
||||||
|
dropout_p = self.dropout_p if self.training else 0.0
|
||||||
|
out = functional_attention(
|
||||||
|
q,
|
||||||
|
k,
|
||||||
|
v,
|
||||||
|
dropout=dropout_p,
|
||||||
|
num_heads=self.num_heads,
|
||||||
|
num_k_exclude_rope=num_k_exclude_rope,
|
||||||
|
freqs_cis=self.freqs_cis,
|
||||||
|
freqs_cis_real=self.freqs_cis_real if self.use_rope_real else None,
|
||||||
|
freqs_cis_imag=self.freqs_cis_imag if self.use_rope_real else None,
|
||||||
|
use_fa3=self.use_fa3,
|
||||||
|
use_rope_real=self.use_rope_real,
|
||||||
|
rope_k_repeat=self.rope_k_repeat,
|
||||||
|
)
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
class DecoupledTransformerDecoderLayerv2(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
activation: str,
|
||||||
|
d_model: int,
|
||||||
|
num_heads: int,
|
||||||
|
dim_feedforward: int,
|
||||||
|
dropout: float,
|
||||||
|
pos_enc_at_attn: bool,
|
||||||
|
pos_enc_at_cross_attn_keys: bool,
|
||||||
|
pos_enc_at_cross_attn_queries: bool,
|
||||||
|
pre_norm: bool,
|
||||||
|
cross_attention_first: bool = False,
|
||||||
|
self_attention_rope: SimpleRoPEAttention,
|
||||||
|
cross_attention_rope: SimpleRoPEAttention,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.d_model = d_model
|
||||||
|
self.num_heads = num_heads
|
||||||
|
self.dim_feedforward = dim_feedforward
|
||||||
|
self.dropout_value = dropout
|
||||||
|
|
||||||
|
self.self_attn_q_proj = nn.Linear(d_model, d_model)
|
||||||
|
self.self_attn_k_proj = nn.Linear(d_model, d_model)
|
||||||
|
self.self_attn_v_proj = nn.Linear(d_model, d_model)
|
||||||
|
self.self_attn_out_proj = nn.Linear(d_model, d_model)
|
||||||
|
|
||||||
|
self.cross_attn_q_proj = nn.Linear(d_model, d_model)
|
||||||
|
self.cross_attn_k_proj = nn.Linear(d_model, d_model)
|
||||||
|
self.cross_attn_v_proj = nn.Linear(d_model, d_model)
|
||||||
|
self.cross_attn_out_proj = nn.Linear(d_model, d_model)
|
||||||
|
|
||||||
|
self.image_cross_attn_q_proj = nn.Linear(d_model, d_model)
|
||||||
|
self.image_cross_attn_k_proj = nn.Linear(d_model, d_model)
|
||||||
|
|
||||||
|
self.self_attention_rope = self_attention_rope
|
||||||
|
self.cross_attention_rope = cross_attention_rope
|
||||||
|
|
||||||
|
# Implementation of Feedforward model
|
||||||
|
self.linear1 = nn.Linear(d_model, dim_feedforward)
|
||||||
|
self.dropout = nn.Dropout(dropout)
|
||||||
|
self.linear2 = nn.Linear(dim_feedforward, d_model)
|
||||||
|
|
||||||
|
self.norm1 = nn.LayerNorm(d_model)
|
||||||
|
self.norm2 = nn.LayerNorm(d_model)
|
||||||
|
self.norm3 = nn.LayerNorm(d_model)
|
||||||
|
self.dropout1 = nn.Dropout(dropout)
|
||||||
|
self.dropout2 = nn.Dropout(dropout)
|
||||||
|
self.dropout3 = nn.Dropout(dropout)
|
||||||
|
|
||||||
|
self.activation_str = activation
|
||||||
|
self.activation = get_activation_fn(activation)
|
||||||
|
self.pre_norm = pre_norm
|
||||||
|
|
||||||
|
self.pos_enc_at_attn = pos_enc_at_attn
|
||||||
|
self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries
|
||||||
|
self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys
|
||||||
|
|
||||||
|
self.cross_attention_first = cross_attention_first
|
||||||
|
|
||||||
|
def _forward_sa(self, tgt, query_pos):
|
||||||
|
# Self-Attention
|
||||||
|
tgt2 = self.norm1(tgt)
|
||||||
|
|
||||||
|
q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2
|
||||||
|
|
||||||
|
q = self.self_attn_q_proj(q)
|
||||||
|
k = self.self_attn_k_proj(k)
|
||||||
|
v = self.self_attn_v_proj(tgt2)
|
||||||
|
out = self.self_attention_rope(q, k, v)
|
||||||
|
tgt2 = self.self_attn_out_proj(out)
|
||||||
|
|
||||||
|
tgt = tgt + self.dropout1(tgt2)
|
||||||
|
return tgt
|
||||||
|
|
||||||
|
def _forward_ca(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
image,
|
||||||
|
tgt,
|
||||||
|
memory_image,
|
||||||
|
memory,
|
||||||
|
query_pos,
|
||||||
|
memory_image_pos,
|
||||||
|
num_k_exclude_rope=0,
|
||||||
|
):
|
||||||
|
kwds = {}
|
||||||
|
if num_k_exclude_rope > 0:
|
||||||
|
assert isinstance(self.cross_attention_rope, SimpleRoPEAttention)
|
||||||
|
kwds = {"num_k_exclude_rope": num_k_exclude_rope}
|
||||||
|
|
||||||
|
# Cross-Attention
|
||||||
|
tgt2 = self.norm2(tgt)
|
||||||
|
|
||||||
|
q = self.image_cross_attn_q_proj(image) + self.cross_attn_q_proj(tgt2)
|
||||||
|
if self.pos_enc_at_cross_attn_queries:
|
||||||
|
q = q + query_pos
|
||||||
|
k = self.image_cross_attn_k_proj(memory_image) + self.cross_attn_k_proj(memory)
|
||||||
|
if self.pos_enc_at_cross_attn_keys:
|
||||||
|
k = k + memory_image_pos
|
||||||
|
v = self.cross_attn_v_proj(memory)
|
||||||
|
|
||||||
|
out = self.cross_attention_rope(q, k, v, **kwds)
|
||||||
|
tgt2 = self.cross_attn_out_proj(out)
|
||||||
|
|
||||||
|
tgt = tgt + self.dropout2(tgt2)
|
||||||
|
return tgt
|
||||||
|
|
||||||
|
def forward_pre(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
image,
|
||||||
|
tgt,
|
||||||
|
memory_image,
|
||||||
|
memory,
|
||||||
|
image_pos: Optional[Tensor] = None,
|
||||||
|
query_pos: Optional[Tensor] = None,
|
||||||
|
memory_image_pos: Optional[Tensor] = None,
|
||||||
|
memory_pos: Optional[Tensor] = None,
|
||||||
|
num_k_exclude_rope: int = 0,
|
||||||
|
):
|
||||||
|
if self.cross_attention_first:
|
||||||
|
tgt = self._forward_ca(
|
||||||
|
image=image,
|
||||||
|
tgt=tgt,
|
||||||
|
memory_image=memory_image,
|
||||||
|
memory=memory,
|
||||||
|
query_pos=query_pos,
|
||||||
|
memory_image_pos=memory_image_pos,
|
||||||
|
num_k_exclude_rope=num_k_exclude_rope,
|
||||||
|
)
|
||||||
|
tgt = self._forward_sa(tgt, query_pos)
|
||||||
|
else:
|
||||||
|
tgt = self._forward_sa(tgt, query_pos)
|
||||||
|
tgt = self._forward_ca(
|
||||||
|
image=image,
|
||||||
|
tgt=tgt,
|
||||||
|
memory_image=memory_image,
|
||||||
|
memory=memory,
|
||||||
|
query_pos=query_pos,
|
||||||
|
memory_image_pos=memory_image_pos,
|
||||||
|
num_k_exclude_rope=num_k_exclude_rope,
|
||||||
|
)
|
||||||
|
|
||||||
|
# MLP
|
||||||
|
tgt2 = self.norm3(tgt)
|
||||||
|
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
|
||||||
|
tgt = tgt + self.dropout3(tgt2)
|
||||||
|
|
||||||
|
return image, tgt
|
||||||
|
|
||||||
|
def forward(self, *args: Any, **kwds: Any) -> torch.Tensor:
|
||||||
|
if self.pre_norm:
|
||||||
|
return self.forward_pre(*args, **kwds)
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
||||||
|
class TransformerEncoderDecoupledCrossAttention(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
d_model: int,
|
||||||
|
frozen: bool,
|
||||||
|
pos_enc_at_input: bool,
|
||||||
|
layer,
|
||||||
|
num_layers: int,
|
||||||
|
use_act_checkpoint: bool = False,
|
||||||
|
batch_first: bool = False, # Do layers expect batch first input?
|
||||||
|
use_image_in_output: bool = True,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.d_model = d_model
|
||||||
|
self.layers = get_clones(layer, num_layers)
|
||||||
|
self.num_layers = num_layers
|
||||||
|
self.norm = nn.LayerNorm(d_model)
|
||||||
|
self.pos_enc_at_input = pos_enc_at_input
|
||||||
|
self.use_act_checkpoint = use_act_checkpoint
|
||||||
|
self.use_image_in_output = use_image_in_output
|
||||||
|
|
||||||
|
if frozen:
|
||||||
|
for p in self.parameters():
|
||||||
|
p.requires_grad_(False)
|
||||||
|
|
||||||
|
self.batch_first = batch_first
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
image: Tensor, # image features
|
||||||
|
src: Tensor, # self-attention inputs; object features
|
||||||
|
memory_image: Tensor, # cross-attention inputs; image features
|
||||||
|
memory: Tensor, # cross-attention inputs; object features
|
||||||
|
image_pos: Optional[Tensor] = None, # pos_enc for self-attention inputs
|
||||||
|
src_pos: Optional[Tensor] = None, # pos_enc for self-attention inputs
|
||||||
|
memory_image_pos: Optional[Tensor] = None, # pos_enc for cross-attention inputs
|
||||||
|
memory_pos: Optional[Tensor] = None, # pos_enc for cross-attention inputs
|
||||||
|
num_obj_ptr_tokens: int = 0, # number of object pointer *tokens*
|
||||||
|
):
|
||||||
|
assert (
|
||||||
|
src.shape[1] == memory.shape[1]
|
||||||
|
), "Batch size must be the same for src and memory"
|
||||||
|
assert (
|
||||||
|
image.shape[1] == memory_image.shape[1]
|
||||||
|
), "Batch size must be the same for image and memory_image"
|
||||||
|
|
||||||
|
output = src
|
||||||
|
|
||||||
|
if self.pos_enc_at_input and src_pos is not None:
|
||||||
|
output = output + 0.1 * src_pos
|
||||||
|
|
||||||
|
if self.batch_first:
|
||||||
|
# Convert to batch first
|
||||||
|
output = output.transpose(0, 1)
|
||||||
|
src_pos = src_pos.transpose(0, 1)
|
||||||
|
image = image.transpose(0, 1)
|
||||||
|
memory = memory.transpose(0, 1)
|
||||||
|
memory_pos = memory_pos.transpose(0, 1)
|
||||||
|
memory_image = memory_image.transpose(0, 1)
|
||||||
|
memory_image_pos = memory_image_pos.transpose(0, 1)
|
||||||
|
|
||||||
|
if memory_image.shape[1] != memory.shape[1]:
|
||||||
|
# Pad memory_image with zeros, to accodmate object pointers
|
||||||
|
assert (
|
||||||
|
(memory.shape[1] - memory_image.shape[1]) == num_obj_ptr_tokens
|
||||||
|
), f"{memory.shape[1]} - {memory_image.shape[1]} != {num_obj_ptr_tokens}"
|
||||||
|
memory_image = torch.cat(
|
||||||
|
[
|
||||||
|
memory_image,
|
||||||
|
torch.zeros(
|
||||||
|
(memory_image.shape[0], num_obj_ptr_tokens)
|
||||||
|
+ memory_image.shape[2:],
|
||||||
|
dtype=memory_image.dtype,
|
||||||
|
device=memory_image.device,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
dim=1,
|
||||||
|
)
|
||||||
|
if memory_image_pos is not None:
|
||||||
|
assert (
|
||||||
|
(memory_pos.shape[1] - memory_image_pos.shape[1])
|
||||||
|
== num_obj_ptr_tokens
|
||||||
|
), f"{memory_pos.shape[1]} - {memory_image_pos.shape[1]} != {num_obj_ptr_tokens}"
|
||||||
|
# tpos is the same in the batch anyway; note that memory_image always has a batch size of 1
|
||||||
|
memory_image_pos = torch.cat(
|
||||||
|
[
|
||||||
|
memory_image_pos,
|
||||||
|
memory_pos[0:1, -num_obj_ptr_tokens:],
|
||||||
|
],
|
||||||
|
dim=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
for layer in self.layers:
|
||||||
|
image, output = activation_ckpt_wrapper(layer)(
|
||||||
|
image=image,
|
||||||
|
tgt=output,
|
||||||
|
memory_image=memory_image,
|
||||||
|
memory=memory,
|
||||||
|
image_pos=image_pos,
|
||||||
|
query_pos=src_pos,
|
||||||
|
memory_image_pos=memory_image_pos,
|
||||||
|
memory_pos=memory_pos,
|
||||||
|
num_k_exclude_rope=num_obj_ptr_tokens,
|
||||||
|
act_ckpt_enable=self.training and self.use_act_checkpoint,
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.use_image_in_output:
|
||||||
|
normed_output = self.norm(output + image)
|
||||||
|
else:
|
||||||
|
normed_output = self.norm(output)
|
||||||
|
|
||||||
|
if self.batch_first:
|
||||||
|
# Convert back to seq first
|
||||||
|
normed_output = normed_output.transpose(0, 1)
|
||||||
|
src_pos = src_pos.transpose(0, 1)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"memory": normed_output,
|
||||||
|
"pos_embed": src_pos,
|
||||||
|
}
|
||||||
|
|||||||
@@ -322,9 +322,9 @@ class TransformerEncoder(nn.Module):
|
|||||||
return reference_points
|
return reference_points
|
||||||
|
|
||||||
def _prepare_multilevel_features(self, srcs, masks, pos_embeds):
|
def _prepare_multilevel_features(self, srcs, masks, pos_embeds):
|
||||||
assert len(srcs) == self.num_feature_levels, (
|
assert (
|
||||||
"mismatch between expected and received # of feature levels"
|
len(srcs) == self.num_feature_levels
|
||||||
)
|
), "mismatch between expected and received # of feature levels"
|
||||||
|
|
||||||
src_flatten = []
|
src_flatten = []
|
||||||
mask_flatten = []
|
mask_flatten = []
|
||||||
@@ -406,9 +406,9 @@ class TransformerEncoder(nn.Module):
|
|||||||
- spatial_shapes: Spatial dimensions of each feature level
|
- spatial_shapes: Spatial dimensions of each feature level
|
||||||
- valid_ratios: Valid ratios for each feature level
|
- valid_ratios: Valid ratios for each feature level
|
||||||
"""
|
"""
|
||||||
assert len(src) == self.num_feature_levels, (
|
assert (
|
||||||
"must be equal to num_feature_levels"
|
len(src) == self.num_feature_levels
|
||||||
)
|
), "must be equal to num_feature_levels"
|
||||||
if src_key_padding_masks is not None:
|
if src_key_padding_masks is not None:
|
||||||
assert len(src_key_padding_masks) == self.num_feature_levels
|
assert len(src_key_padding_masks) == self.num_feature_levels
|
||||||
if pos is not None:
|
if pos is not None:
|
||||||
@@ -538,9 +538,9 @@ class TransformerEncoderFusion(TransformerEncoder):
|
|||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
assert all(x.dim == 4 for x in src), (
|
assert all(
|
||||||
"expected list of (bs, c, h, w) tensors"
|
x.dim == 4 for x in src
|
||||||
)
|
), "expected list of (bs, c, h, w) tensors"
|
||||||
|
|
||||||
if self.add_pooled_text_to_img_feat:
|
if self.add_pooled_text_to_img_feat:
|
||||||
# Fusion: Add mean pooled text to image features
|
# Fusion: Add mean pooled text to image features
|
||||||
|
|||||||
@@ -147,42 +147,54 @@ class Prompt:
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Dimension checks
|
# Dimension checks
|
||||||
assert box_embeddings is not None and list(box_embeddings.shape[:2]) == [
|
assert (
|
||||||
|
box_embeddings is not None
|
||||||
|
and list(box_embeddings.shape[:2])
|
||||||
|
== [
|
||||||
box_seq_len,
|
box_seq_len,
|
||||||
bs,
|
bs,
|
||||||
], (
|
]
|
||||||
f"Wrong dimension for box embeddings. Expected [{box_seq_len}, {bs}, *] got {box_embeddings.shape}"
|
), f"Wrong dimension for box embeddings. Expected [{box_seq_len}, {bs}, *] got {box_embeddings.shape}"
|
||||||
)
|
assert (
|
||||||
assert box_mask is not None and list(box_mask.shape) == [
|
box_mask is not None
|
||||||
|
and list(box_mask.shape)
|
||||||
|
== [
|
||||||
bs,
|
bs,
|
||||||
box_seq_len,
|
box_seq_len,
|
||||||
], (
|
]
|
||||||
f"Wrong dimension for box mask. Expected [{bs}, {box_seq_len}] got {box_mask.shape}"
|
), f"Wrong dimension for box mask. Expected [{bs}, {box_seq_len}] got {box_mask.shape}"
|
||||||
)
|
assert (
|
||||||
assert point_embeddings is not None and list(point_embeddings.shape[:2]) == [
|
point_embeddings is not None
|
||||||
|
and list(point_embeddings.shape[:2])
|
||||||
|
== [
|
||||||
point_seq_len,
|
point_seq_len,
|
||||||
bs,
|
bs,
|
||||||
], (
|
]
|
||||||
f"Wrong dimension for point embeddings. Expected [{point_seq_len}, {bs}, *] got {point_embeddings.shape}"
|
), f"Wrong dimension for point embeddings. Expected [{point_seq_len}, {bs}, *] got {point_embeddings.shape}"
|
||||||
)
|
assert (
|
||||||
assert point_mask is not None and list(point_mask.shape) == [
|
point_mask is not None
|
||||||
|
and list(point_mask.shape)
|
||||||
|
== [
|
||||||
bs,
|
bs,
|
||||||
point_seq_len,
|
point_seq_len,
|
||||||
], (
|
]
|
||||||
f"Wrong dimension for point mask. Expected [{bs}, {point_seq_len}] got {point_mask.shape}"
|
), f"Wrong dimension for point mask. Expected [{bs}, {point_seq_len}] got {point_mask.shape}"
|
||||||
)
|
assert (
|
||||||
assert box_labels is not None and list(box_labels.shape) == [
|
box_labels is not None
|
||||||
|
and list(box_labels.shape)
|
||||||
|
== [
|
||||||
box_seq_len,
|
box_seq_len,
|
||||||
bs,
|
bs,
|
||||||
], (
|
]
|
||||||
f"Wrong dimension for box labels. Expected [{box_seq_len}, {bs}] got {box_labels.shape}"
|
), f"Wrong dimension for box labels. Expected [{box_seq_len}, {bs}] got {box_labels.shape}"
|
||||||
)
|
assert (
|
||||||
assert point_labels is not None and list(point_labels.shape) == [
|
point_labels is not None
|
||||||
|
and list(point_labels.shape)
|
||||||
|
== [
|
||||||
point_seq_len,
|
point_seq_len,
|
||||||
bs,
|
bs,
|
||||||
], (
|
]
|
||||||
f"Wrong dimension for point labels. Expected [{point_seq_len}, {bs}] got {point_labels.shape}"
|
), f"Wrong dimension for point labels. Expected [{point_seq_len}, {bs}] got {point_labels.shape}"
|
||||||
)
|
|
||||||
assert (
|
assert (
|
||||||
# Allowed to be None, we leave it to the encoder to check for validity before encoding.
|
# Allowed to be None, we leave it to the encoder to check for validity before encoding.
|
||||||
mask_embeddings is None
|
mask_embeddings is None
|
||||||
@@ -191,41 +203,41 @@ class Prompt:
|
|||||||
mask_seq_len,
|
mask_seq_len,
|
||||||
bs,
|
bs,
|
||||||
]
|
]
|
||||||
), (
|
), f"Wrong dimension for mask embeddings. Expected [{mask_seq_len}, {bs}, *] got {mask_embeddings.shape}"
|
||||||
f"Wrong dimension for mask embeddings. Expected [{mask_seq_len}, {bs}, *] got {mask_embeddings.shape}"
|
assert (
|
||||||
)
|
mask_mask is None
|
||||||
assert mask_mask is None or list(mask_mask.shape) == [
|
or list(mask_mask.shape)
|
||||||
|
== [
|
||||||
bs,
|
bs,
|
||||||
mask_seq_len,
|
mask_seq_len,
|
||||||
], (
|
]
|
||||||
f"Wrong dimension for mask attn. mask. Expected [{bs}, {mask_seq_len}] got {mask_mask.shape}"
|
), f"Wrong dimension for mask attn. mask. Expected [{bs}, {mask_seq_len}] got {mask_mask.shape}"
|
||||||
)
|
|
||||||
|
|
||||||
# Device checks
|
# Device checks
|
||||||
assert box_embeddings is not None and box_embeddings.device == device, (
|
assert (
|
||||||
f"Expected box embeddings to be on device {device}, got {box_embeddings.device}"
|
box_embeddings is not None and box_embeddings.device == device
|
||||||
)
|
), f"Expected box embeddings to be on device {device}, got {box_embeddings.device}"
|
||||||
assert box_mask is not None and box_mask.device == device, (
|
assert (
|
||||||
f"Expected box mask to be on device {device}, got {box_mask.device}"
|
box_mask is not None and box_mask.device == device
|
||||||
)
|
), f"Expected box mask to be on device {device}, got {box_mask.device}"
|
||||||
assert box_labels is not None and box_labels.device == device, (
|
assert (
|
||||||
f"Expected box labels to be on device {device}, got {box_labels.device}"
|
box_labels is not None and box_labels.device == device
|
||||||
)
|
), f"Expected box labels to be on device {device}, got {box_labels.device}"
|
||||||
assert point_embeddings is not None and point_embeddings.device == device, (
|
assert (
|
||||||
f"Expected point embeddings to be on device {device}, got {point_embeddings.device}"
|
point_embeddings is not None and point_embeddings.device == device
|
||||||
)
|
), f"Expected point embeddings to be on device {device}, got {point_embeddings.device}"
|
||||||
assert point_mask is not None and point_mask.device == device, (
|
assert (
|
||||||
f"Expected point mask to be on device {device}, got {point_mask.device}"
|
point_mask is not None and point_mask.device == device
|
||||||
)
|
), f"Expected point mask to be on device {device}, got {point_mask.device}"
|
||||||
assert point_labels is not None and point_labels.device == device, (
|
assert (
|
||||||
f"Expected point labels to be on device {device}, got {point_labels.device}"
|
point_labels is not None and point_labels.device == device
|
||||||
)
|
), f"Expected point labels to be on device {device}, got {point_labels.device}"
|
||||||
assert mask_embeddings is None or mask_embeddings.device == device, (
|
assert (
|
||||||
f"Expected mask embeddings to be on device {device}, got {mask_embeddings.device}"
|
mask_embeddings is None or mask_embeddings.device == device
|
||||||
)
|
), f"Expected mask embeddings to be on device {device}, got {mask_embeddings.device}"
|
||||||
assert mask_mask is None or mask_mask.device == device, (
|
assert (
|
||||||
f"Expected mask attn. mask to be on device {device}, got {mask_mask.device}"
|
mask_mask is None or mask_mask.device == device
|
||||||
)
|
), f"Expected mask attn. mask to be on device {device}, got {mask_mask.device}"
|
||||||
|
|
||||||
self.box_embeddings = box_embeddings
|
self.box_embeddings = box_embeddings
|
||||||
self.point_embeddings = point_embeddings
|
self.point_embeddings = point_embeddings
|
||||||
@@ -251,30 +263,30 @@ class Prompt:
|
|||||||
if point_embeddings is not None:
|
if point_embeddings is not None:
|
||||||
point_seq_len = point_embeddings.shape[0]
|
point_seq_len = point_embeddings.shape[0]
|
||||||
if bs is not None:
|
if bs is not None:
|
||||||
assert bs == point_embeddings.shape[1], (
|
assert (
|
||||||
f"Batch size mismatch between box and point embeddings. Got {bs} and {point_embeddings.shape[1]}."
|
bs == point_embeddings.shape[1]
|
||||||
)
|
), f"Batch size mismatch between box and point embeddings. Got {bs} and {point_embeddings.shape[1]}."
|
||||||
else:
|
else:
|
||||||
bs = point_embeddings.shape[1]
|
bs = point_embeddings.shape[1]
|
||||||
if device is not None:
|
if device is not None:
|
||||||
assert device == point_embeddings.device, (
|
assert (
|
||||||
"Device mismatch between box and point embeddings"
|
device == point_embeddings.device
|
||||||
)
|
), "Device mismatch between box and point embeddings"
|
||||||
else:
|
else:
|
||||||
device = point_embeddings.device
|
device = point_embeddings.device
|
||||||
|
|
||||||
if mask_embeddings is not None:
|
if mask_embeddings is not None:
|
||||||
mask_seq_len = mask_embeddings.shape[0]
|
mask_seq_len = mask_embeddings.shape[0]
|
||||||
if bs is not None:
|
if bs is not None:
|
||||||
assert bs == mask_embeddings.shape[1], (
|
assert (
|
||||||
f"Batch size mismatch between box/point and mask embedding. Got {bs} and {mask_embeddings.shape[1]}"
|
bs == mask_embeddings.shape[1]
|
||||||
)
|
), f"Batch size mismatch between box/point and mask embedding. Got {bs} and {mask_embeddings.shape[1]}"
|
||||||
else:
|
else:
|
||||||
bs = mask_embeddings.shape[1]
|
bs = mask_embeddings.shape[1]
|
||||||
if device is not None:
|
if device is not None:
|
||||||
assert device == mask_embeddings.device, (
|
assert (
|
||||||
"Device mismatch between box/point and mask embeddings."
|
device == mask_embeddings.device
|
||||||
)
|
), "Device mismatch between box/point and mask embeddings."
|
||||||
else:
|
else:
|
||||||
device = mask_embeddings.device
|
device = mask_embeddings.device
|
||||||
|
|
||||||
@@ -526,9 +538,9 @@ class SequenceGeometryEncoder(nn.Module):
|
|||||||
if add_cls:
|
if add_cls:
|
||||||
self.cls_embed = torch.nn.Embedding(1, self.d_model)
|
self.cls_embed = torch.nn.Embedding(1, self.d_model)
|
||||||
|
|
||||||
assert points_direct_project or points_pos_enc or points_pool, (
|
assert (
|
||||||
"Error: need at least one way to encode points"
|
points_direct_project or points_pos_enc or points_pool
|
||||||
)
|
), "Error: need at least one way to encode points"
|
||||||
assert (
|
assert (
|
||||||
encode_boxes_as_points
|
encode_boxes_as_points
|
||||||
or boxes_direct_project
|
or boxes_direct_project
|
||||||
@@ -570,16 +582,16 @@ class SequenceGeometryEncoder(nn.Module):
|
|||||||
|
|
||||||
self.encode = None
|
self.encode = None
|
||||||
if num_layers > 0:
|
if num_layers > 0:
|
||||||
assert add_cls, (
|
assert (
|
||||||
"It's currently highly recommended to add a CLS when using a transformer"
|
add_cls
|
||||||
)
|
), "It's currently highly recommended to add a CLS when using a transformer"
|
||||||
self.encode = get_clones(layer, num_layers)
|
self.encode = get_clones(layer, num_layers)
|
||||||
self.encode_norm = nn.LayerNorm(self.d_model)
|
self.encode_norm = nn.LayerNorm(self.d_model)
|
||||||
|
|
||||||
if mask_encoder is not None:
|
if mask_encoder is not None:
|
||||||
assert isinstance(mask_encoder, MaskEncoder), (
|
assert isinstance(
|
||||||
f"Expected mask_encoder of type MaskEncoder. Got {type(mask_encoder)}."
|
mask_encoder, MaskEncoder
|
||||||
)
|
), f"Expected mask_encoder of type MaskEncoder. Got {type(mask_encoder)}."
|
||||||
if add_mask_label:
|
if add_mask_label:
|
||||||
self.mask_label_embed = torch.nn.Embedding(2, self.d_model)
|
self.mask_label_embed = torch.nn.Embedding(2, self.d_model)
|
||||||
self.add_mask_label = add_mask_label
|
self.add_mask_label = add_mask_label
|
||||||
@@ -688,15 +700,16 @@ class SequenceGeometryEncoder(nn.Module):
|
|||||||
img_feats: torch.Tensor = None,
|
img_feats: torch.Tensor = None,
|
||||||
):
|
):
|
||||||
n_masks, bs = masks.shape[:2]
|
n_masks, bs = masks.shape[:2]
|
||||||
assert n_masks == 1, (
|
assert (
|
||||||
"We assume one mask per prompt for now. Code should still be functional if this assertion is removed."
|
n_masks == 1
|
||||||
)
|
), "We assume one mask per prompt for now. Code should still be functional if this assertion is removed."
|
||||||
assert list(attn_mask.shape) == [
|
assert (
|
||||||
|
list(attn_mask.shape)
|
||||||
|
== [
|
||||||
bs,
|
bs,
|
||||||
n_masks,
|
n_masks,
|
||||||
], (
|
]
|
||||||
f"Expected attn_mask to be of shape {bs}x{n_masks}. Got {list(attn_mask.shape)}."
|
), f"Expected attn_mask to be of shape {bs}x{n_masks}. Got {list(attn_mask.shape)}."
|
||||||
)
|
|
||||||
masks, pos = self.mask_encoder(
|
masks, pos = self.mask_encoder(
|
||||||
masks=masks.flatten(0, 1).float(),
|
masks=masks.flatten(0, 1).float(),
|
||||||
pix_feat=img_feats,
|
pix_feat=img_feats,
|
||||||
|
|||||||
+11
-1
@@ -132,6 +132,13 @@ def load_video_frames(
|
|||||||
match = re.match(r"<load-dummy-video-(\d+)>", video_path)
|
match = re.match(r"<load-dummy-video-(\d+)>", video_path)
|
||||||
num_frames = int(match.group(1)) if match else 60
|
num_frames = int(match.group(1)) if match else 60
|
||||||
return load_dummy_video(image_size, offload_video_to_cpu, num_frames=num_frames)
|
return load_dummy_video(image_size, offload_video_to_cpu, num_frames=num_frames)
|
||||||
|
elif video_path.startswith("<load-zero-video"):
|
||||||
|
# Check for pattern <load-zero-video-N> where N is an integer
|
||||||
|
match = re.match(r"<load-zero-video-(\d+)>", video_path)
|
||||||
|
num_frames = int(match.group(1)) if match else 60
|
||||||
|
return load_dummy_video(
|
||||||
|
image_size, offload_video_to_cpu, num_frames=num_frames, do_zeros=True
|
||||||
|
)
|
||||||
elif os.path.isdir(video_path):
|
elif os.path.isdir(video_path):
|
||||||
return load_video_frames_from_image_folder(
|
return load_video_frames_from_image_folder(
|
||||||
image_folder=video_path,
|
image_folder=video_path,
|
||||||
@@ -322,12 +329,15 @@ def load_video_frames_from_video_file_using_cv2(
|
|||||||
return video_tensor, original_height, original_width
|
return video_tensor, original_height, original_width
|
||||||
|
|
||||||
|
|
||||||
def load_dummy_video(image_size, offload_video_to_cpu, num_frames=60):
|
def load_dummy_video(image_size, offload_video_to_cpu, num_frames=60, do_zeros=False):
|
||||||
"""
|
"""
|
||||||
Load a dummy video with random frames for testing and compilation warmup purposes.
|
Load a dummy video with random frames for testing and compilation warmup purposes.
|
||||||
"""
|
"""
|
||||||
video_height, video_width = 480, 640 # dummy original video sizes
|
video_height, video_width = 480, 640 # dummy original video sizes
|
||||||
|
if not do_zeros:
|
||||||
images = torch.randn(num_frames, 3, image_size, image_size, dtype=torch.float16)
|
images = torch.randn(num_frames, 3, image_size, image_size, dtype=torch.float16)
|
||||||
|
else:
|
||||||
|
images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float16)
|
||||||
if not offload_video_to_cpu:
|
if not offload_video_to_cpu:
|
||||||
images = images.cuda()
|
images = images.cuda()
|
||||||
return images, video_height, video_width
|
return images, video_height, video_width
|
||||||
|
|||||||
@@ -107,6 +107,12 @@ class SegmentationHead(nn.Module):
|
|||||||
image_ids,
|
image_ids,
|
||||||
encoder_hidden_states,
|
encoder_hidden_states,
|
||||||
) -> torch.Tensor:
|
) -> torch.Tensor:
|
||||||
|
# Unwrap NestedTensors to plain tensors if needed (multiplex path)
|
||||||
|
from sam3.model.data_misc import NestedTensor
|
||||||
|
|
||||||
|
def _unwrap(x):
|
||||||
|
return x.tensors if isinstance(x, NestedTensor) else x
|
||||||
|
|
||||||
feature_device = backbone_feats[0].device # features could be on CPU
|
feature_device = backbone_feats[0].device # features could be on CPU
|
||||||
model_device = self.device
|
model_device = self.device
|
||||||
image_ids_ = image_ids.to(feature_device)
|
image_ids_ = image_ids.to(feature_device)
|
||||||
@@ -116,10 +122,14 @@ class SegmentationHead(nn.Module):
|
|||||||
backbone_visual_feats = []
|
backbone_visual_feats = []
|
||||||
for feat in backbone_feats:
|
for feat in backbone_feats:
|
||||||
# Copy the img features per query (pixel decoder won't share img feats)
|
# Copy the img features per query (pixel decoder won't share img feats)
|
||||||
backbone_visual_feats.append(feat[image_ids_, ...].to(model_device))
|
backbone_visual_feats.append(
|
||||||
|
_unwrap(feat)[image_ids_, ...].to(model_device)
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
# Bs=1, we rely on broadcasting for query-based processing
|
# Bs=1, we rely on broadcasting for query-based processing
|
||||||
backbone_visual_feats = [bb_feat.clone() for bb_feat in backbone_feats]
|
backbone_visual_feats = [
|
||||||
|
_unwrap(bb_feat).clone() for bb_feat in backbone_feats
|
||||||
|
]
|
||||||
# Extract visual embeddings
|
# Extract visual embeddings
|
||||||
encoder_hidden_states = encoder_hidden_states.permute(1, 2, 0)
|
encoder_hidden_states = encoder_hidden_states.permute(1, 2, 0)
|
||||||
spatial_dim = math.prod(backbone_feats[-1].shape[-2:])
|
spatial_dim = math.prod(backbone_feats[-1].shape[-2:])
|
||||||
@@ -135,7 +145,7 @@ class SegmentationHead(nn.Module):
|
|||||||
else:
|
else:
|
||||||
pixel_embed = self.pixel_decoder(backbone_visual_feats)
|
pixel_embed = self.pixel_decoder(backbone_visual_feats)
|
||||||
else:
|
else:
|
||||||
backbone_feats = [x.to(model_device) for x in backbone_feats]
|
backbone_feats = [_unwrap(x).to(model_device) for x in backbone_feats]
|
||||||
pixel_embed = self.pixel_decoder(backbone_feats)
|
pixel_embed = self.pixel_decoder(backbone_feats)
|
||||||
if pixel_embed.shape[0] == 1:
|
if pixel_embed.shape[0] == 1:
|
||||||
# For batch_size=1 training, we can avoid the indexing to save memory
|
# For batch_size=1 training, we can avoid the indexing to save memory
|
||||||
@@ -248,9 +258,7 @@ class UniversalSegmentationHead(SegmentationHead):
|
|||||||
self.d_model = hidden_dim
|
self.d_model = hidden_dim
|
||||||
|
|
||||||
if dot_product_scorer is not None:
|
if dot_product_scorer is not None:
|
||||||
assert presence_head, (
|
assert presence_head, "Specifying a dot product scorer without a presence head is likely a mistake"
|
||||||
"Specifying a dot product scorer without a presence head is likely a mistake"
|
|
||||||
)
|
|
||||||
|
|
||||||
self.presence_head = None
|
self.presence_head = None
|
||||||
if presence_head:
|
if presence_head:
|
||||||
|
|||||||
+11
-5
@@ -38,14 +38,19 @@ class SimpleMaskDownSampler(nn.Module):
|
|||||||
# Option to interpolate the input mask first before downsampling using convs. In that case, the total_stride is assumed to be after interpolation.
|
# Option to interpolate the input mask first before downsampling using convs. In that case, the total_stride is assumed to be after interpolation.
|
||||||
# If set to input resolution or None, we don't interpolate. We default to None to be safe (for older configs or if not explicitly set)
|
# If set to input resolution or None, we don't interpolate. We default to None to be safe (for older configs or if not explicitly set)
|
||||||
interpol_size=None,
|
interpol_size=None,
|
||||||
|
# options for incorporating multiplex memory encoding
|
||||||
|
multiplex_count: int = 1,
|
||||||
|
starting_out_chan: int = 1,
|
||||||
|
input_channel_multiplier: int = 1,
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
num_layers = int(math.log2(total_stride) // math.log2(stride))
|
num_layers = int(math.log2(total_stride) // math.log2(stride))
|
||||||
|
multiplex_count = multiplex_count * input_channel_multiplier
|
||||||
assert stride**num_layers == total_stride
|
assert stride**num_layers == total_stride
|
||||||
self.encoder = nn.Sequential()
|
self.encoder = nn.Sequential()
|
||||||
mask_in_chans, mask_out_chans = 1, 1
|
mask_in_chans, mask_out_chans = multiplex_count, starting_out_chan
|
||||||
for _ in range(num_layers):
|
for _ in range(num_layers):
|
||||||
mask_out_chans = mask_in_chans * (stride**2)
|
mask_out_chans = mask_out_chans * (stride**2)
|
||||||
self.encoder.append(
|
self.encoder.append(
|
||||||
nn.Conv2d(
|
nn.Conv2d(
|
||||||
mask_in_chans,
|
mask_in_chans,
|
||||||
@@ -60,11 +65,12 @@ class SimpleMaskDownSampler(nn.Module):
|
|||||||
mask_in_chans = mask_out_chans
|
mask_in_chans = mask_out_chans
|
||||||
|
|
||||||
self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1))
|
self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1))
|
||||||
|
self.multiplex_count = multiplex_count
|
||||||
self.interpol_size = interpol_size
|
self.interpol_size = interpol_size
|
||||||
if self.interpol_size is not None:
|
if self.interpol_size is not None:
|
||||||
assert isinstance(self.interpol_size, (list, tuple)), (
|
assert isinstance(
|
||||||
f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple."
|
self.interpol_size, (list, tuple)
|
||||||
)
|
), f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple."
|
||||||
self.interpol_size = list(interpol_size)
|
self.interpol_size = list(interpol_size)
|
||||||
assert len(self.interpol_size) == 2
|
assert len(self.interpol_size) == 2
|
||||||
|
|
||||||
|
|||||||
+688
-11
@@ -6,18 +6,25 @@
|
|||||||
|
|
||||||
import copy
|
import copy
|
||||||
import math
|
import math
|
||||||
|
import warnings
|
||||||
import weakref
|
import weakref
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from contextlib import AbstractContextManager
|
from contextlib import AbstractContextManager
|
||||||
from enum import auto, Enum
|
from enum import auto, Enum
|
||||||
from typing import Dict, List, Optional, Union
|
from typing import Dict, List, Optional, Tuple, Union
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
from torch import nn, Tensor
|
from torch import nn, Tensor
|
||||||
|
from torch.overrides import handle_torch_function, has_torch_function
|
||||||
from typing_extensions import override
|
from typing_extensions import override
|
||||||
|
|
||||||
|
try:
|
||||||
|
import xformers
|
||||||
|
except ImportError:
|
||||||
|
xformers = None
|
||||||
|
|
||||||
|
|
||||||
def inverse_sigmoid(x, eps=1e-3):
|
def inverse_sigmoid(x, eps=1e-3):
|
||||||
"""
|
"""
|
||||||
@@ -30,10 +37,680 @@ def inverse_sigmoid(x, eps=1e-3):
|
|||||||
return torch.log(x1 / x2)
|
return torch.log(x1 / x2)
|
||||||
|
|
||||||
|
|
||||||
class MultiheadAttentionWrapper(nn.MultiheadAttention):
|
def get_sdpa_settings():
|
||||||
def forward(self, *args, **kwargs):
|
if torch.cuda.is_available():
|
||||||
kwargs["need_weights"] = False
|
old_gpu = torch.cuda.get_device_properties(0).major < 7
|
||||||
return super().forward(*args, **kwargs)
|
# only use Flash Attention on Ampere (8.0) or newer GPUs
|
||||||
|
use_flash_attn = torch.cuda.get_device_properties(0).major >= 8
|
||||||
|
if not use_flash_attn:
|
||||||
|
warnings.warn(
|
||||||
|
"Flash Attention is disabled as it requires a GPU with Ampere (8.0) CUDA capability.",
|
||||||
|
category=UserWarning,
|
||||||
|
stacklevel=2,
|
||||||
|
)
|
||||||
|
# keep math kernel for PyTorch versions before 2.2 (Flash Attention v2 is only
|
||||||
|
# available on PyTorch 2.2+, while Flash Attention v1 cannot handle all cases)
|
||||||
|
pytorch_version = tuple(int(v) for v in torch.__version__.split(".")[:2])
|
||||||
|
if pytorch_version < (2, 2):
|
||||||
|
warnings.warn(
|
||||||
|
f"You are using PyTorch {torch.__version__} without Flash Attention v2 support. "
|
||||||
|
"Consider upgrading to PyTorch 2.2+ for Flash Attention v2 (which could be faster).",
|
||||||
|
category=UserWarning,
|
||||||
|
stacklevel=2,
|
||||||
|
)
|
||||||
|
math_kernel_on = pytorch_version < (2, 2) or not use_flash_attn
|
||||||
|
else:
|
||||||
|
old_gpu = True
|
||||||
|
use_flash_attn = False
|
||||||
|
math_kernel_on = True
|
||||||
|
|
||||||
|
return old_gpu, use_flash_attn, math_kernel_on
|
||||||
|
|
||||||
|
|
||||||
|
OLD_GPU, USE_FLASH_ATTN, MATH_KERNEL_ON = get_sdpa_settings()
|
||||||
|
|
||||||
|
|
||||||
|
class AttentionType:
|
||||||
|
"""Type of attention"""
|
||||||
|
|
||||||
|
# Simple dot product attention
|
||||||
|
Vanilla = "Vanilla"
|
||||||
|
|
||||||
|
# Efficient attention from xformers
|
||||||
|
Xformer = "Xformer"
|
||||||
|
|
||||||
|
# Sparse attention
|
||||||
|
Sparse = "Sparse"
|
||||||
|
|
||||||
|
# Deformable attention (not compatible with text)
|
||||||
|
Deformable = "Deformable"
|
||||||
|
|
||||||
|
|
||||||
|
def multi_head_attention_forward(
|
||||||
|
query: Tensor,
|
||||||
|
key: Tensor,
|
||||||
|
value: Tensor,
|
||||||
|
embed_dim_to_check: int,
|
||||||
|
num_heads: int,
|
||||||
|
in_proj_weight: Optional[Tensor],
|
||||||
|
in_proj_bias: Optional[Tensor],
|
||||||
|
bias_k: Optional[Tensor],
|
||||||
|
bias_v: Optional[Tensor],
|
||||||
|
add_zero_attn: bool,
|
||||||
|
dropout_p: float,
|
||||||
|
out_proj_weight: Tensor,
|
||||||
|
out_proj_bias: Optional[Tensor],
|
||||||
|
training: bool = True,
|
||||||
|
key_padding_mask: Optional[Tensor] = None,
|
||||||
|
need_weights: bool = True,
|
||||||
|
attn_mask: Optional[Tensor] = None,
|
||||||
|
use_separate_proj_weight: bool = False,
|
||||||
|
q_proj_weight: Optional[Tensor] = None,
|
||||||
|
k_proj_weight: Optional[Tensor] = None,
|
||||||
|
v_proj_weight: Optional[Tensor] = None,
|
||||||
|
static_k: Optional[Tensor] = None,
|
||||||
|
static_v: Optional[Tensor] = None,
|
||||||
|
average_attn_weights: bool = True,
|
||||||
|
is_causal: bool = False,
|
||||||
|
attn_type: AttentionType = AttentionType.Vanilla,
|
||||||
|
attn_sparsity: float = 0.0,
|
||||||
|
attn_bias: Optional[Tensor] = None,
|
||||||
|
use_fa3: bool = False,
|
||||||
|
) -> Tuple[Tensor, Optional[Tensor]]:
|
||||||
|
tens_ops = (
|
||||||
|
query,
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
in_proj_weight,
|
||||||
|
in_proj_bias,
|
||||||
|
bias_k,
|
||||||
|
bias_v,
|
||||||
|
out_proj_weight,
|
||||||
|
out_proj_bias,
|
||||||
|
)
|
||||||
|
if has_torch_function(tens_ops):
|
||||||
|
return handle_torch_function(
|
||||||
|
multi_head_attention_forward,
|
||||||
|
tens_ops,
|
||||||
|
query,
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
embed_dim_to_check,
|
||||||
|
num_heads,
|
||||||
|
in_proj_weight,
|
||||||
|
in_proj_bias,
|
||||||
|
bias_k,
|
||||||
|
bias_v,
|
||||||
|
add_zero_attn,
|
||||||
|
dropout_p,
|
||||||
|
out_proj_weight,
|
||||||
|
out_proj_bias,
|
||||||
|
training=training,
|
||||||
|
key_padding_mask=key_padding_mask,
|
||||||
|
need_weights=need_weights,
|
||||||
|
attn_mask=attn_mask,
|
||||||
|
is_causal=is_causal,
|
||||||
|
use_separate_proj_weight=use_separate_proj_weight,
|
||||||
|
q_proj_weight=q_proj_weight,
|
||||||
|
k_proj_weight=k_proj_weight,
|
||||||
|
v_proj_weight=v_proj_weight,
|
||||||
|
static_k=static_k,
|
||||||
|
static_v=static_v,
|
||||||
|
average_attn_weights=average_attn_weights,
|
||||||
|
use_fa3=use_fa3,
|
||||||
|
)
|
||||||
|
|
||||||
|
is_batched = True
|
||||||
|
|
||||||
|
if is_causal:
|
||||||
|
raise NotImplementedError("is_causal is not supported in this implem")
|
||||||
|
attn_mask = None
|
||||||
|
|
||||||
|
if not is_batched:
|
||||||
|
query = query.unsqueeze(1)
|
||||||
|
key = key.unsqueeze(1)
|
||||||
|
value = value.unsqueeze(1)
|
||||||
|
if key_padding_mask is not None:
|
||||||
|
key_padding_mask = key_padding_mask.unsqueeze(0)
|
||||||
|
|
||||||
|
# set up shape vars
|
||||||
|
tgt_len, bsz, embed_dim = query.shape
|
||||||
|
src_len, _, _ = key.shape
|
||||||
|
if key_padding_mask is not None:
|
||||||
|
_kpm_dtype = key_padding_mask.dtype
|
||||||
|
if _kpm_dtype != torch.bool and not torch.is_floating_point(key_padding_mask):
|
||||||
|
raise AssertionError(
|
||||||
|
"only bool and floating types of key_padding_mask are supported"
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
embed_dim == embed_dim_to_check
|
||||||
|
), f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
|
||||||
|
if isinstance(embed_dim, torch.Tensor):
|
||||||
|
head_dim = embed_dim.div(num_heads, rounding_mode="trunc")
|
||||||
|
else:
|
||||||
|
head_dim = embed_dim // num_heads
|
||||||
|
assert (
|
||||||
|
head_dim * num_heads == embed_dim
|
||||||
|
), f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
|
||||||
|
if use_separate_proj_weight:
|
||||||
|
assert (
|
||||||
|
key.shape[:2] == value.shape[:2]
|
||||||
|
), f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
|
||||||
|
else:
|
||||||
|
assert (
|
||||||
|
key.shape == value.shape
|
||||||
|
), f"key shape {key.shape} does not match value shape {value.shape}"
|
||||||
|
|
||||||
|
#
|
||||||
|
# compute in-projection
|
||||||
|
#
|
||||||
|
if not use_separate_proj_weight:
|
||||||
|
assert (
|
||||||
|
in_proj_weight is not None
|
||||||
|
), "use_separate_proj_weight is False but in_proj_weight is None"
|
||||||
|
q, k, v = F._in_projection_packed(
|
||||||
|
query, key, value, in_proj_weight, in_proj_bias
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
assert (
|
||||||
|
q_proj_weight is not None
|
||||||
|
), "use_separate_proj_weight is True but q_proj_weight is None"
|
||||||
|
assert (
|
||||||
|
k_proj_weight is not None
|
||||||
|
), "use_separate_proj_weight is True but k_proj_weight is None"
|
||||||
|
assert (
|
||||||
|
v_proj_weight is not None
|
||||||
|
), "use_separate_proj_weight is True but v_proj_weight is None"
|
||||||
|
if in_proj_bias is None:
|
||||||
|
b_q = b_k = b_v = None
|
||||||
|
else:
|
||||||
|
b_q, b_k, b_v = in_proj_bias.chunk(3)
|
||||||
|
q, k, v = F._in_projection(
|
||||||
|
query,
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
q_proj_weight,
|
||||||
|
k_proj_weight,
|
||||||
|
v_proj_weight,
|
||||||
|
b_q,
|
||||||
|
b_k,
|
||||||
|
b_v,
|
||||||
|
)
|
||||||
|
|
||||||
|
# prep attention mask
|
||||||
|
if attn_mask is not None:
|
||||||
|
if attn_mask.dtype == torch.uint8:
|
||||||
|
warnings.warn(
|
||||||
|
"Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead."
|
||||||
|
)
|
||||||
|
attn_mask = attn_mask.to(torch.bool)
|
||||||
|
else:
|
||||||
|
assert (
|
||||||
|
attn_mask.is_floating_point() or attn_mask.dtype == torch.bool
|
||||||
|
), f"Only float, byte, and bool types are supported for attn_mask, not {attn_mask.dtype}"
|
||||||
|
# ensure attn_mask's dim is 3
|
||||||
|
if attn_mask.dim() == 2:
|
||||||
|
correct_2d_size = (tgt_len, src_len)
|
||||||
|
if attn_mask.shape != correct_2d_size:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}."
|
||||||
|
)
|
||||||
|
attn_mask = attn_mask.unsqueeze(0)
|
||||||
|
elif attn_mask.dim() == 3:
|
||||||
|
correct_3d_size = (bsz * num_heads, tgt_len, src_len)
|
||||||
|
if attn_mask.shape != correct_3d_size:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"attn_mask's dimension {attn_mask.dim()} is not supported"
|
||||||
|
)
|
||||||
|
|
||||||
|
# add bias along batch dimension (currently second)
|
||||||
|
if bias_k is not None and bias_v is not None:
|
||||||
|
assert static_k is None, "bias cannot be added to static key."
|
||||||
|
assert static_v is None, "bias cannot be added to static value."
|
||||||
|
k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
|
||||||
|
v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
|
||||||
|
if attn_mask is not None:
|
||||||
|
attn_mask = F.pad(attn_mask, (0, 1))
|
||||||
|
if key_padding_mask is not None:
|
||||||
|
key_padding_mask = F.pad(key_padding_mask, (0, 1))
|
||||||
|
else:
|
||||||
|
assert bias_k is None
|
||||||
|
assert bias_v is None
|
||||||
|
|
||||||
|
#
|
||||||
|
# reshape q, k, v for multihead attention and make em batch first
|
||||||
|
#
|
||||||
|
q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
|
||||||
|
if static_k is None:
|
||||||
|
k = k.contiguous().view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
|
||||||
|
else:
|
||||||
|
assert (
|
||||||
|
static_k.size(0) == bsz * num_heads
|
||||||
|
), f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
|
||||||
|
assert (
|
||||||
|
static_k.size(2) == head_dim
|
||||||
|
), f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
|
||||||
|
k = static_k
|
||||||
|
if static_v is None:
|
||||||
|
v = v.contiguous().view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
|
||||||
|
else:
|
||||||
|
assert (
|
||||||
|
static_v.size(0) == bsz * num_heads
|
||||||
|
), f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
|
||||||
|
assert (
|
||||||
|
static_v.size(2) == head_dim
|
||||||
|
), f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
|
||||||
|
v = static_v
|
||||||
|
|
||||||
|
# add zero attention along batch dimension (now first)
|
||||||
|
if add_zero_attn:
|
||||||
|
zero_attn_shape = (bsz * num_heads, 1, head_dim)
|
||||||
|
k = torch.cat(
|
||||||
|
[k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1
|
||||||
|
)
|
||||||
|
v = torch.cat(
|
||||||
|
[v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1
|
||||||
|
)
|
||||||
|
if attn_mask is not None:
|
||||||
|
attn_mask = F.pad(attn_mask, (0, 1))
|
||||||
|
if key_padding_mask is not None:
|
||||||
|
key_padding_mask = F.pad(key_padding_mask, (0, 1))
|
||||||
|
|
||||||
|
# update source sequence length after adjustments
|
||||||
|
src_len = k.size(1)
|
||||||
|
|
||||||
|
# merge key padding and attention masks
|
||||||
|
if key_padding_mask is not None:
|
||||||
|
assert (
|
||||||
|
key_padding_mask.shape
|
||||||
|
== (
|
||||||
|
bsz,
|
||||||
|
src_len,
|
||||||
|
)
|
||||||
|
), f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
|
||||||
|
key_padding_mask = (
|
||||||
|
key_padding_mask.view(bsz, 1, 1, src_len)
|
||||||
|
.expand(-1, num_heads, -1, -1)
|
||||||
|
.reshape(bsz * num_heads, 1, src_len)
|
||||||
|
)
|
||||||
|
if attn_mask is None:
|
||||||
|
attn_mask = key_padding_mask
|
||||||
|
elif attn_mask.dtype == torch.bool:
|
||||||
|
attn_mask = attn_mask.logical_or(key_padding_mask)
|
||||||
|
else:
|
||||||
|
attn_mask = attn_mask.masked_fill(key_padding_mask, float("-inf"))
|
||||||
|
|
||||||
|
# convert mask to float
|
||||||
|
if attn_mask is not None and attn_mask.dtype == torch.bool:
|
||||||
|
new_attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype)
|
||||||
|
new_attn_mask.masked_fill_(attn_mask, float("-inf"))
|
||||||
|
attn_mask = new_attn_mask
|
||||||
|
|
||||||
|
# adjust dropout probability
|
||||||
|
if not training:
|
||||||
|
dropout_p = 0.0
|
||||||
|
|
||||||
|
#
|
||||||
|
# (deep breath) calculate attention and out projection
|
||||||
|
#
|
||||||
|
|
||||||
|
if attn_mask is not None:
|
||||||
|
if attn_mask.size(0) == 1:
|
||||||
|
attn_mask = attn_mask.unsqueeze(0)
|
||||||
|
else:
|
||||||
|
attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
|
||||||
|
|
||||||
|
if attn_bias is not None:
|
||||||
|
assert (
|
||||||
|
attn_bias.shape
|
||||||
|
== (
|
||||||
|
bsz,
|
||||||
|
num_heads,
|
||||||
|
tgt_len,
|
||||||
|
src_len,
|
||||||
|
)
|
||||||
|
), f"expecting attn_bias shape of {(bsz, num_heads, tgt_len, src_len)}, but got {attn_bias.shape}"
|
||||||
|
if attn_mask is None:
|
||||||
|
attn_mask = attn_bias
|
||||||
|
else:
|
||||||
|
attn_mask = attn_mask + attn_bias
|
||||||
|
|
||||||
|
q = q.view(bsz, num_heads, tgt_len, head_dim)
|
||||||
|
k = k.view(bsz, num_heads, src_len, head_dim)
|
||||||
|
v = v.view(bsz, num_heads, src_len, head_dim)
|
||||||
|
|
||||||
|
if attn_type == AttentionType.Vanilla:
|
||||||
|
if attn_mask is None and not is_causal and use_fa3:
|
||||||
|
from sam3.perflib.fa3 import flash_attn_func
|
||||||
|
|
||||||
|
assert dropout_p == 0.0
|
||||||
|
attn_output = flash_attn_func(
|
||||||
|
q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
|
||||||
|
).transpose(1, 2)
|
||||||
|
else:
|
||||||
|
torch.backends.cuda.enable_flash_sdp(True)
|
||||||
|
torch.backends.cuda.enable_math_sdp(True)
|
||||||
|
torch.backends.cuda.enable_mem_efficient_sdp(True)
|
||||||
|
|
||||||
|
attn_output = F.scaled_dot_product_attention(
|
||||||
|
q, k, v, attn_mask, dropout_p, is_causal
|
||||||
|
)
|
||||||
|
|
||||||
|
attn_output = (
|
||||||
|
attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
|
||||||
|
)
|
||||||
|
elif attn_type == AttentionType.Xformer:
|
||||||
|
attn_output_weights = None
|
||||||
|
assert not need_weights, "need_weights is not supported in efficient mode"
|
||||||
|
attn_output = xformers.ops.memory_efficient_attention(
|
||||||
|
q.transpose(1, 2),
|
||||||
|
k.transpose(1, 2),
|
||||||
|
v.transpose(1, 2),
|
||||||
|
attn_bias=attn_mask,
|
||||||
|
p=dropout_p,
|
||||||
|
)
|
||||||
|
attn_output = attn_output.permute(1, 0, 2, 3).reshape(bsz * tgt_len, embed_dim)
|
||||||
|
elif attn_type == AttentionType.Sparse:
|
||||||
|
attn_output_weights = None
|
||||||
|
assert not need_weights, "need_weights is not supported in efficient mode"
|
||||||
|
# Need to collapse heads and batch dimensions
|
||||||
|
q = q.reshape(bsz * num_heads, tgt_len, head_dim).contiguous()
|
||||||
|
k = k.reshape(bsz * num_heads, src_len, head_dim).contiguous()
|
||||||
|
v = v.reshape(bsz * num_heads, src_len, head_dim).contiguous()
|
||||||
|
row_offsets, column_indices = xformers.ops.find_locations_new(
|
||||||
|
q, k, attn_sparsity, True
|
||||||
|
)
|
||||||
|
attn_output = xformers.ops.sparse_memory_efficient_attention(
|
||||||
|
q, k, v, row_offsets, column_indices, attn_bias=attn_mask
|
||||||
|
).reshape(bsz, num_heads, tgt_len, head_dim)
|
||||||
|
attn_output = attn_output.permute(2, 0, 1, 3).reshape(bsz * tgt_len, embed_dim)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unsupported attention type {attn_type}")
|
||||||
|
|
||||||
|
attn_output = F.linear(attn_output, out_proj_weight, out_proj_bias)
|
||||||
|
attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
|
||||||
|
|
||||||
|
if need_weights:
|
||||||
|
attn_output_weights = (q * head_dim**-0.5) @ k.transpose(-2, -1)
|
||||||
|
attn_output_weights = attn_output_weights.softmax(dim=-1)
|
||||||
|
attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
|
||||||
|
if average_attn_weights:
|
||||||
|
attn_output_weights = attn_output_weights.sum(dim=1) / num_heads
|
||||||
|
|
||||||
|
if not is_batched:
|
||||||
|
attn_output = attn_output.squeeze(1)
|
||||||
|
attn_output_weights = attn_output_weights.squeeze(0)
|
||||||
|
return attn_output, attn_output_weights
|
||||||
|
else:
|
||||||
|
attn_output_weights = None
|
||||||
|
if not is_batched:
|
||||||
|
attn_output = attn_output.squeeze(1)
|
||||||
|
return attn_output, None
|
||||||
|
|
||||||
|
|
||||||
|
class MultiheadAttention(nn.Module):
|
||||||
|
__constants__ = ["batch_first"]
|
||||||
|
bias_k: Optional[torch.Tensor]
|
||||||
|
bias_v: Optional[torch.Tensor]
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
embed_dim,
|
||||||
|
num_heads,
|
||||||
|
dropout=0.0,
|
||||||
|
bias=True,
|
||||||
|
add_bias_kv=False,
|
||||||
|
add_zero_attn=False,
|
||||||
|
kdim=None,
|
||||||
|
vdim=None,
|
||||||
|
batch_first=False,
|
||||||
|
device=None,
|
||||||
|
dtype=None,
|
||||||
|
attn_type: AttentionType = AttentionType.Vanilla,
|
||||||
|
sparsity: float = 0.0,
|
||||||
|
use_act_checkpoint: bool = False,
|
||||||
|
use_fa3: bool = False,
|
||||||
|
) -> None:
|
||||||
|
factory_kwargs = {"device": device, "dtype": dtype}
|
||||||
|
super(MultiheadAttention, self).__init__()
|
||||||
|
self.embed_dim = embed_dim
|
||||||
|
self.kdim = kdim if kdim is not None else embed_dim
|
||||||
|
self.vdim = vdim if vdim is not None else embed_dim
|
||||||
|
self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
|
||||||
|
|
||||||
|
self.num_heads = num_heads
|
||||||
|
self.dropout = dropout
|
||||||
|
self.batch_first = batch_first
|
||||||
|
self.head_dim = embed_dim // num_heads
|
||||||
|
self.use_act_checkpoint = use_act_checkpoint
|
||||||
|
assert (
|
||||||
|
self.head_dim * num_heads == self.embed_dim
|
||||||
|
), "embed_dim must be divisible by num_heads"
|
||||||
|
|
||||||
|
assert (
|
||||||
|
attn_type == AttentionType.Sparse or sparsity == 0.0
|
||||||
|
), "sparsity is only supported for sparse attention"
|
||||||
|
|
||||||
|
if not self._qkv_same_embed_dim:
|
||||||
|
self.q_proj_weight = nn.Parameter(
|
||||||
|
torch.empty((embed_dim, embed_dim), **factory_kwargs)
|
||||||
|
)
|
||||||
|
self.k_proj_weight = nn.Parameter(
|
||||||
|
torch.empty((embed_dim, self.kdim), **factory_kwargs)
|
||||||
|
)
|
||||||
|
self.v_proj_weight = nn.Parameter(
|
||||||
|
torch.empty((embed_dim, self.vdim), **factory_kwargs)
|
||||||
|
)
|
||||||
|
self.register_parameter("in_proj_weight", None)
|
||||||
|
else:
|
||||||
|
self.in_proj_weight = nn.Parameter(
|
||||||
|
torch.empty((3 * embed_dim, embed_dim), **factory_kwargs)
|
||||||
|
)
|
||||||
|
self.register_parameter("q_proj_weight", None)
|
||||||
|
self.register_parameter("k_proj_weight", None)
|
||||||
|
self.register_parameter("v_proj_weight", None)
|
||||||
|
|
||||||
|
if bias:
|
||||||
|
self.in_proj_bias = nn.Parameter(
|
||||||
|
torch.empty(3 * embed_dim, **factory_kwargs)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.register_parameter("in_proj_bias", None)
|
||||||
|
self.out_proj = nn.modules.linear.NonDynamicallyQuantizableLinear(
|
||||||
|
embed_dim, embed_dim, bias=bias, **factory_kwargs
|
||||||
|
)
|
||||||
|
|
||||||
|
if add_bias_kv:
|
||||||
|
self.bias_k = nn.Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
||||||
|
self.bias_v = nn.Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
||||||
|
else:
|
||||||
|
self.bias_k = self.bias_v = None
|
||||||
|
|
||||||
|
self.add_zero_attn = add_zero_attn
|
||||||
|
|
||||||
|
self.attn_type = attn_type
|
||||||
|
self.sparsity = sparsity
|
||||||
|
self.use_fa3 = use_fa3
|
||||||
|
|
||||||
|
self._reset_parameters()
|
||||||
|
|
||||||
|
def _reset_parameters(self):
|
||||||
|
if self._qkv_same_embed_dim:
|
||||||
|
nn.init.xavier_uniform_(self.in_proj_weight)
|
||||||
|
else:
|
||||||
|
nn.init.xavier_uniform_(self.q_proj_weight)
|
||||||
|
nn.init.xavier_uniform_(self.k_proj_weight)
|
||||||
|
nn.init.xavier_uniform_(self.v_proj_weight)
|
||||||
|
|
||||||
|
if self.in_proj_bias is not None:
|
||||||
|
nn.init.constant_(self.in_proj_bias, 0.0)
|
||||||
|
nn.init.constant_(self.out_proj.bias, 0.0)
|
||||||
|
if self.bias_k is not None:
|
||||||
|
nn.init.xavier_normal_(self.bias_k)
|
||||||
|
if self.bias_v is not None:
|
||||||
|
nn.init.xavier_normal_(self.bias_v)
|
||||||
|
|
||||||
|
def __setstate__(self, state):
|
||||||
|
if "_qkv_same_embed_dim" not in state:
|
||||||
|
state["_qkv_same_embed_dim"] = True
|
||||||
|
|
||||||
|
super(MultiheadAttention, self).__setstate__(state)
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
query: Tensor,
|
||||||
|
key: Tensor,
|
||||||
|
value: Tensor,
|
||||||
|
key_padding_mask: Optional[Tensor] = None,
|
||||||
|
need_weights: bool = False,
|
||||||
|
attn_mask: Optional[Tensor] = None,
|
||||||
|
average_attn_weights: bool = True,
|
||||||
|
attn_bias: Optional[Tensor] = None,
|
||||||
|
) -> Tuple[Tensor, Optional[Tensor]]:
|
||||||
|
is_batched = query.dim() == 3
|
||||||
|
if key_padding_mask is not None:
|
||||||
|
_kpm_dtype = key_padding_mask.dtype
|
||||||
|
if _kpm_dtype != torch.bool and not torch.is_floating_point(
|
||||||
|
key_padding_mask
|
||||||
|
):
|
||||||
|
raise AssertionError(
|
||||||
|
"only bool and floating types of key_padding_mask are supported"
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.batch_first and is_batched:
|
||||||
|
if key is value:
|
||||||
|
if query is key:
|
||||||
|
query = key = value = query.transpose(1, 0)
|
||||||
|
else:
|
||||||
|
query, key = [x.transpose(1, 0) for x in (query, key)]
|
||||||
|
value = key
|
||||||
|
else:
|
||||||
|
query, key, value = [x.transpose(1, 0) for x in (query, key, value)]
|
||||||
|
|
||||||
|
if not self._qkv_same_embed_dim:
|
||||||
|
if self.use_act_checkpoint:
|
||||||
|
attn_output, attn_output_weights = torch.utils.checkpoint.checkpoint(
|
||||||
|
multi_head_attention_forward,
|
||||||
|
query,
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
self.embed_dim,
|
||||||
|
self.num_heads,
|
||||||
|
self.in_proj_weight,
|
||||||
|
self.in_proj_bias,
|
||||||
|
self.bias_k,
|
||||||
|
self.bias_v,
|
||||||
|
self.add_zero_attn,
|
||||||
|
self.dropout,
|
||||||
|
self.out_proj.weight,
|
||||||
|
self.out_proj.bias,
|
||||||
|
use_reentrant=False,
|
||||||
|
training=self.training,
|
||||||
|
key_padding_mask=key_padding_mask,
|
||||||
|
need_weights=need_weights,
|
||||||
|
attn_mask=attn_mask,
|
||||||
|
use_separate_proj_weight=True,
|
||||||
|
q_proj_weight=self.q_proj_weight,
|
||||||
|
k_proj_weight=self.k_proj_weight,
|
||||||
|
v_proj_weight=self.v_proj_weight,
|
||||||
|
average_attn_weights=average_attn_weights,
|
||||||
|
attn_type=self.attn_type,
|
||||||
|
attn_sparsity=self.sparsity,
|
||||||
|
attn_bias=attn_bias,
|
||||||
|
use_fa3=self.use_fa3,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
attn_output, attn_output_weights = multi_head_attention_forward(
|
||||||
|
query,
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
self.embed_dim,
|
||||||
|
self.num_heads,
|
||||||
|
self.in_proj_weight,
|
||||||
|
self.in_proj_bias,
|
||||||
|
self.bias_k,
|
||||||
|
self.bias_v,
|
||||||
|
self.add_zero_attn,
|
||||||
|
self.dropout,
|
||||||
|
self.out_proj.weight,
|
||||||
|
self.out_proj.bias,
|
||||||
|
training=self.training,
|
||||||
|
key_padding_mask=key_padding_mask,
|
||||||
|
need_weights=need_weights,
|
||||||
|
attn_mask=attn_mask,
|
||||||
|
use_separate_proj_weight=True,
|
||||||
|
q_proj_weight=self.q_proj_weight,
|
||||||
|
k_proj_weight=self.k_proj_weight,
|
||||||
|
v_proj_weight=self.v_proj_weight,
|
||||||
|
average_attn_weights=average_attn_weights,
|
||||||
|
attn_type=self.attn_type,
|
||||||
|
attn_sparsity=self.sparsity,
|
||||||
|
attn_bias=attn_bias,
|
||||||
|
use_fa3=self.use_fa3,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
if self.use_act_checkpoint:
|
||||||
|
attn_output, attn_output_weights = torch.utils.checkpoint.checkpoint(
|
||||||
|
multi_head_attention_forward,
|
||||||
|
query,
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
self.embed_dim,
|
||||||
|
self.num_heads,
|
||||||
|
self.in_proj_weight,
|
||||||
|
self.in_proj_bias,
|
||||||
|
self.bias_k,
|
||||||
|
self.bias_v,
|
||||||
|
self.add_zero_attn,
|
||||||
|
self.dropout,
|
||||||
|
self.out_proj.weight,
|
||||||
|
self.out_proj.bias,
|
||||||
|
use_reentrant=False,
|
||||||
|
training=self.training,
|
||||||
|
key_padding_mask=key_padding_mask,
|
||||||
|
need_weights=need_weights,
|
||||||
|
attn_mask=attn_mask,
|
||||||
|
average_attn_weights=average_attn_weights,
|
||||||
|
attn_type=self.attn_type,
|
||||||
|
attn_sparsity=self.sparsity,
|
||||||
|
attn_bias=attn_bias,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
attn_output, attn_output_weights = multi_head_attention_forward(
|
||||||
|
query,
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
self.embed_dim,
|
||||||
|
self.num_heads,
|
||||||
|
self.in_proj_weight,
|
||||||
|
self.in_proj_bias,
|
||||||
|
self.bias_k,
|
||||||
|
self.bias_v,
|
||||||
|
self.add_zero_attn,
|
||||||
|
self.dropout,
|
||||||
|
self.out_proj.weight,
|
||||||
|
self.out_proj.bias,
|
||||||
|
training=self.training,
|
||||||
|
key_padding_mask=key_padding_mask,
|
||||||
|
need_weights=need_weights,
|
||||||
|
attn_mask=attn_mask,
|
||||||
|
average_attn_weights=average_attn_weights,
|
||||||
|
attn_type=self.attn_type,
|
||||||
|
attn_sparsity=self.sparsity,
|
||||||
|
attn_bias=attn_bias,
|
||||||
|
)
|
||||||
|
if self.batch_first and is_batched:
|
||||||
|
return attn_output.transpose(1, 0), attn_output_weights
|
||||||
|
else:
|
||||||
|
return attn_output, attn_output_weights
|
||||||
|
|
||||||
|
|
||||||
|
# Keep backward compatibility alias
|
||||||
|
MultiheadAttentionWrapper = MultiheadAttention
|
||||||
|
|
||||||
|
|
||||||
class DotProductScoring(torch.nn.Module):
|
class DotProductScoring(torch.nn.Module):
|
||||||
@@ -330,9 +1007,9 @@ class SAM3Output(list):
|
|||||||
self.output = output
|
self.output = output
|
||||||
else:
|
else:
|
||||||
self.output = []
|
self.output = []
|
||||||
assert isinstance(iter_mode, SAM3Output.IterMode), (
|
assert isinstance(
|
||||||
f"iter_mode shoulf be of enum type 'SAM3Output.IterMode'. Got {type(iter_mode)}"
|
iter_mode, SAM3Output.IterMode
|
||||||
)
|
), f"iter_mode shoulf be of enum type 'SAM3Output.IterMode'. Got {type(iter_mode)}"
|
||||||
|
|
||||||
self.iter_mode = iter_mode
|
self.iter_mode = iter_mode
|
||||||
# We create a weak reference to self to be used in the lambda functions.
|
# We create a weak reference to self to be used in the lambda functions.
|
||||||
@@ -411,9 +1088,9 @@ class SAM3Output(list):
|
|||||||
return SAM3Output._IterationMode(model_output=model_output, iter_mode=iter_mode)
|
return SAM3Output._IterationMode(model_output=model_output, iter_mode=iter_mode)
|
||||||
|
|
||||||
def append(self, item: list):
|
def append(self, item: list):
|
||||||
assert isinstance(item, list), (
|
assert isinstance(
|
||||||
f"Only list items are supported. Got {type(item)}"
|
item, list
|
||||||
)
|
), f"Only list items are supported. Got {type(item)}"
|
||||||
self.output.append(item)
|
self.output.append(item)
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
|
|||||||
@@ -0,0 +1,470 @@
|
|||||||
|
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||||
|
# All rights reserved.
|
||||||
|
|
||||||
|
# This source code is licensed under the license found in the
|
||||||
|
# LICENSE file in the root directory of this source tree.
|
||||||
|
|
||||||
|
|
||||||
|
from typing import List, Optional, Type
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from sam3.sam.common import LayerNorm2d
|
||||||
|
from torch import nn
|
||||||
|
from torch.nn import functional as F
|
||||||
|
|
||||||
|
|
||||||
|
class MultiplexMaskDecoder(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
transformer_dim: int,
|
||||||
|
transformer: nn.Module,
|
||||||
|
multiplex_count: int,
|
||||||
|
num_multimask_outputs: int = 3,
|
||||||
|
activation: Type[nn.Module] = nn.GELU,
|
||||||
|
iou_head_depth: int = 3,
|
||||||
|
iou_head_hidden_dim: int = 256,
|
||||||
|
use_high_res_features: bool = False,
|
||||||
|
iou_prediction_use_sigmoid: bool = False,
|
||||||
|
dynamic_multimask_via_stability=False,
|
||||||
|
dynamic_multimask_stability_delta=0.05,
|
||||||
|
dynamic_multimask_stability_thresh=0.98,
|
||||||
|
pred_obj_scores: bool = False,
|
||||||
|
pred_obj_scores_mlp: bool = False,
|
||||||
|
use_multimask_token_for_obj_ptr: bool = False,
|
||||||
|
decode_mask_with_shared_tokens: bool = False,
|
||||||
|
decode_mask_attribute_with_shared_tokens: bool = False,
|
||||||
|
multimask_outputs_only: bool = False,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Predicts masks given an image and prompt embeddings, using a
|
||||||
|
transformer architecture with multiplex capabilities.
|
||||||
|
|
||||||
|
Arguments:
|
||||||
|
multiplex_count: the number of masks multiplexed into a single feature map
|
||||||
|
num_multimask_outputs: the number of masks to predict per multiplex output
|
||||||
|
(the total number of masks is (num_multimask_outputs+1) * multiplex_count)
|
||||||
|
use_multimask_token_for_obj_ptr: whether to use multimask tokens for object pointers
|
||||||
|
decode_mask_with_shared_tokens: use the same mask token for multimasks with different projection layers
|
||||||
|
decode_mask_attribute_with_shared_tokens: use the mask tokens (instead of separate tokens)
|
||||||
|
to predict iou and object scores
|
||||||
|
multimask_outputs_only: predict num_multimask_outputs masks without the single
|
||||||
|
mask output token (i.e., without the +1)
|
||||||
|
"""
|
||||||
|
super().__init__()
|
||||||
|
self.transformer_dim = transformer_dim
|
||||||
|
self.transformer = transformer
|
||||||
|
|
||||||
|
self.multiplex_count = multiplex_count
|
||||||
|
self.num_multimask_outputs = num_multimask_outputs
|
||||||
|
self.multimask_outputs_only = multimask_outputs_only
|
||||||
|
self.decode_mask_with_shared_tokens = decode_mask_with_shared_tokens
|
||||||
|
self.decode_mask_attribute_with_shared_tokens = (
|
||||||
|
decode_mask_attribute_with_shared_tokens
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.decode_mask_with_shared_tokens:
|
||||||
|
assert (
|
||||||
|
multimask_outputs_only
|
||||||
|
), "multimask_outputs_only must be True if decode_mask_with_shared_tokens"
|
||||||
|
|
||||||
|
if self.multimask_outputs_only:
|
||||||
|
self.num_mask_output_per_object = num_multimask_outputs
|
||||||
|
else:
|
||||||
|
self.num_mask_output_per_object = num_multimask_outputs + 1
|
||||||
|
|
||||||
|
if self.decode_mask_with_shared_tokens:
|
||||||
|
self.num_mask_tokens = multiplex_count
|
||||||
|
else:
|
||||||
|
self.num_mask_tokens = multiplex_count * self.num_mask_output_per_object
|
||||||
|
|
||||||
|
self.pred_obj_scores = pred_obj_scores
|
||||||
|
self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
|
||||||
|
|
||||||
|
if not self.decode_mask_attribute_with_shared_tokens:
|
||||||
|
self.iou_token = nn.Embedding(multiplex_count, transformer_dim)
|
||||||
|
if self.pred_obj_scores:
|
||||||
|
self.obj_score_token = nn.Embedding(multiplex_count, transformer_dim)
|
||||||
|
|
||||||
|
self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
|
||||||
|
|
||||||
|
self.output_upscaling = nn.Sequential(
|
||||||
|
nn.ConvTranspose2d(
|
||||||
|
transformer_dim, transformer_dim // 4, kernel_size=2, stride=2
|
||||||
|
),
|
||||||
|
LayerNorm2d(transformer_dim // 4),
|
||||||
|
activation(),
|
||||||
|
nn.ConvTranspose2d(
|
||||||
|
transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2
|
||||||
|
),
|
||||||
|
activation(),
|
||||||
|
)
|
||||||
|
self.use_high_res_features = use_high_res_features
|
||||||
|
if use_high_res_features:
|
||||||
|
self.conv_s0 = nn.Conv2d(
|
||||||
|
transformer_dim, transformer_dim // 8, kernel_size=1, stride=1
|
||||||
|
)
|
||||||
|
self.conv_s1 = nn.Conv2d(
|
||||||
|
transformer_dim, transformer_dim // 4, kernel_size=1, stride=1
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.num_multimask_outputs == 0:
|
||||||
|
self.output_hypernetworks_mlp = MLP(
|
||||||
|
transformer_dim, transformer_dim, transformer_dim // 8, 3
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.output_hypernetworks_mlps = nn.ModuleList(
|
||||||
|
[
|
||||||
|
MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
|
||||||
|
for _ in range(self.num_mask_output_per_object)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
self.iou_prediction_head = MLP(
|
||||||
|
transformer_dim,
|
||||||
|
iou_head_hidden_dim,
|
||||||
|
(
|
||||||
|
1
|
||||||
|
if (
|
||||||
|
self.decode_mask_attribute_with_shared_tokens
|
||||||
|
and not self.decode_mask_with_shared_tokens
|
||||||
|
)
|
||||||
|
else self.num_mask_output_per_object
|
||||||
|
),
|
||||||
|
iou_head_depth,
|
||||||
|
sigmoid_output=iou_prediction_use_sigmoid,
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.pred_obj_scores:
|
||||||
|
self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
|
||||||
|
if pred_obj_scores_mlp:
|
||||||
|
self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
|
||||||
|
|
||||||
|
# When outputting a single mask, optionally we can dynamically fall back to the best
|
||||||
|
# multimask output token if the single mask output token gives low stability scores.
|
||||||
|
self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
|
||||||
|
self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
|
||||||
|
self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
image_embeddings: torch.Tensor,
|
||||||
|
image_pe: torch.Tensor,
|
||||||
|
multimask_output: bool,
|
||||||
|
high_res_features: Optional[List[torch.Tensor]] = None,
|
||||||
|
extra_per_object_embeddings: Optional[torch.Tensor] = None,
|
||||||
|
) -> dict[str, torch.Tensor]:
|
||||||
|
"""
|
||||||
|
Predict masks given image and prompt embeddings.
|
||||||
|
|
||||||
|
Arguments:
|
||||||
|
image_embeddings (torch.Tensor): the embeddings from the image encoder
|
||||||
|
image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
|
||||||
|
extra_per_object_embeddings (torch.Tensor): a tensor with shape b * multiplex_count * C to be added to the mask tokens
|
||||||
|
|
||||||
|
Returns: a dict of Tensors indexed by strings
|
||||||
|
masks: batched predicted masks
|
||||||
|
iou_pred: batched predictions of mask quality
|
||||||
|
object_score_logits: batched predictions of object existence
|
||||||
|
"""
|
||||||
|
|
||||||
|
if self.num_multimask_outputs <= 0:
|
||||||
|
assert (
|
||||||
|
not multimask_output
|
||||||
|
), f"multimask_output must be False with {self.num_multimask_outputs=}"
|
||||||
|
|
||||||
|
if self.multimask_outputs_only:
|
||||||
|
assert (
|
||||||
|
multimask_output
|
||||||
|
), f"multimask_output must be True with {self.multimask_outputs_only=}"
|
||||||
|
|
||||||
|
out = self.predict_masks(
|
||||||
|
image_embeddings=image_embeddings,
|
||||||
|
image_pe=image_pe,
|
||||||
|
high_res_features=high_res_features,
|
||||||
|
extra_per_object_embeddings=extra_per_object_embeddings,
|
||||||
|
)
|
||||||
|
|
||||||
|
masks = out["masks"] # [B, M, (self.num_mask_token_per_object), H, W]
|
||||||
|
iou_pred = out["iou_pred"] # [B, M, (self.num_mask_token_per_object)]
|
||||||
|
mask_tokens_out = out[
|
||||||
|
"mask_tokens_out"
|
||||||
|
] # [B, M, (self.num_mask_token_per_object), C]
|
||||||
|
|
||||||
|
# Select the correct mask or masks for output
|
||||||
|
if multimask_output:
|
||||||
|
if not self.multimask_outputs_only:
|
||||||
|
masks = masks[:, :, 1:, :, :]
|
||||||
|
iou_pred = iou_pred[:, :, 1:]
|
||||||
|
elif self.dynamic_multimask_via_stability and not self.training:
|
||||||
|
masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred)
|
||||||
|
else:
|
||||||
|
masks = masks[:, :, 0:1, :, :]
|
||||||
|
iou_pred = iou_pred[:, :, 0:1]
|
||||||
|
|
||||||
|
if multimask_output and self.use_multimask_token_for_obj_ptr:
|
||||||
|
if self.multimask_outputs_only:
|
||||||
|
sam_tokens_out = mask_tokens_out
|
||||||
|
else:
|
||||||
|
sam_tokens_out = mask_tokens_out[
|
||||||
|
:, :, 1:
|
||||||
|
] # [B, M, num_multimask_outputs, C] shape
|
||||||
|
else:
|
||||||
|
# Take the mask output token. Here we *always* use the token for single mask output.
|
||||||
|
# At test time, even if we track after 1-click (and using multimask_output=True),
|
||||||
|
# we still take the single mask token here. The rationale is that we always track
|
||||||
|
# after multiple clicks during training, so the past tokens seen during training
|
||||||
|
# are always the single mask token (and we'll let it be the object-memory token).
|
||||||
|
sam_tokens_out = mask_tokens_out[:, :, 0:1] # [B, M, 1, C] shape
|
||||||
|
|
||||||
|
del out["mask_tokens_out"]
|
||||||
|
out["masks"] = masks
|
||||||
|
out["iou_pred"] = iou_pred
|
||||||
|
out["sam_tokens_out"] = sam_tokens_out
|
||||||
|
|
||||||
|
if multimask_output:
|
||||||
|
assert (
|
||||||
|
masks.shape[2] == self.num_mask_output_per_object
|
||||||
|
), f"{masks.shape=}, {self.num_mask_output_per_object=}"
|
||||||
|
assert (
|
||||||
|
iou_pred.shape[2] == self.num_mask_output_per_object
|
||||||
|
), f"{iou_pred.shape=}, {self.num_mask_output_per_object=}"
|
||||||
|
if self.use_multimask_token_for_obj_ptr:
|
||||||
|
if self.decode_mask_with_shared_tokens:
|
||||||
|
assert sam_tokens_out.shape[2] == 1, f"{sam_tokens_out.shape=}"
|
||||||
|
else:
|
||||||
|
assert (
|
||||||
|
sam_tokens_out.shape[2] == self.num_mask_output_per_object
|
||||||
|
), f"{sam_tokens_out.shape=}, {self.num_mask_output_per_object=}"
|
||||||
|
else:
|
||||||
|
assert masks.shape[2] == 1, f"{masks.shape=}"
|
||||||
|
assert iou_pred.shape[2] == 1, f"{iou_pred.shape=}"
|
||||||
|
assert sam_tokens_out.shape[2] == 1, f"{sam_tokens_out.shape=}"
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
def predict_masks(
|
||||||
|
self,
|
||||||
|
image_embeddings: torch.Tensor,
|
||||||
|
image_pe: torch.Tensor,
|
||||||
|
high_res_features: Optional[List[torch.Tensor]] = None,
|
||||||
|
extra_per_object_embeddings: Optional[
|
||||||
|
torch.Tensor
|
||||||
|
] = None, # num_buckets, multiplex_count, C
|
||||||
|
) -> dict[str, torch.Tensor]:
|
||||||
|
"""Predicts masks. See 'forward' for more details."""
|
||||||
|
# Concatenate output tokens
|
||||||
|
B = image_embeddings.shape[0]
|
||||||
|
token_list = []
|
||||||
|
if self.pred_obj_scores and not self.decode_mask_attribute_with_shared_tokens:
|
||||||
|
token_list.append(self.obj_score_token.weight)
|
||||||
|
if not self.decode_mask_attribute_with_shared_tokens:
|
||||||
|
token_list.append(self.iou_token.weight)
|
||||||
|
|
||||||
|
tokens = torch.cat(token_list, dim=0)
|
||||||
|
tokens = tokens.unsqueeze(0).expand(B, -1, -1)
|
||||||
|
|
||||||
|
if extra_per_object_embeddings is not None:
|
||||||
|
mask_tokens = self.mask_tokens.weight.view(
|
||||||
|
1, self.multiplex_count, self.num_mask_output_per_object, -1
|
||||||
|
).expand(B, -1, -1, -1)
|
||||||
|
|
||||||
|
mask_tokens = mask_tokens + extra_per_object_embeddings.unsqueeze(2)
|
||||||
|
mask_tokens = mask_tokens.flatten(1, 2)
|
||||||
|
else:
|
||||||
|
mask_tokens = self.mask_tokens.weight.unsqueeze(0).expand(B, -1, -1)
|
||||||
|
|
||||||
|
tokens = torch.cat([tokens, mask_tokens], dim=1)
|
||||||
|
|
||||||
|
src = image_embeddings
|
||||||
|
|
||||||
|
assert (
|
||||||
|
image_pe.size(0) == 1
|
||||||
|
), "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
|
||||||
|
pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
|
||||||
|
b, c, h, w = src.shape
|
||||||
|
|
||||||
|
# Run the transformer
|
||||||
|
hs, src = self.transformer(src, pos_src, tokens)
|
||||||
|
|
||||||
|
# Parse transformer outputs based on token sharing configuration
|
||||||
|
if self.decode_mask_attribute_with_shared_tokens:
|
||||||
|
assert (
|
||||||
|
hs.shape[1] == self.num_mask_tokens
|
||||||
|
), f"{hs.shape=}, {self.num_mask_tokens=}"
|
||||||
|
iou_token_out = mask_tokens_out = hs[:, 0 : self.num_mask_tokens]
|
||||||
|
if self.pred_obj_scores:
|
||||||
|
obj_score_token_out = mask_tokens_out
|
||||||
|
else:
|
||||||
|
# Separate tokens for each prediction type
|
||||||
|
s = 0
|
||||||
|
if self.pred_obj_scores:
|
||||||
|
obj_score_token_out = hs[:, s : s + self.multiplex_count, :]
|
||||||
|
s += self.multiplex_count
|
||||||
|
|
||||||
|
iou_token_out = hs[:, s : s + self.multiplex_count, :]
|
||||||
|
s += self.multiplex_count
|
||||||
|
mask_tokens_out = hs[:, s : s + self.num_mask_tokens, :]
|
||||||
|
assert (
|
||||||
|
hs.shape[1] == s + self.num_mask_tokens
|
||||||
|
), f"{hs.shape=}, {s=}, {self.num_mask_tokens=}"
|
||||||
|
|
||||||
|
# Upscale mask embeddings and predict masks using the mask tokens
|
||||||
|
src = src.transpose(1, 2).view(b, c, h, w)
|
||||||
|
if not self.use_high_res_features:
|
||||||
|
upscaled_embedding = self.output_upscaling(src)
|
||||||
|
else:
|
||||||
|
dc1, ln1, act1, dc2, act2 = self.output_upscaling
|
||||||
|
feat_s0, feat_s1 = high_res_features
|
||||||
|
upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
|
||||||
|
upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
|
||||||
|
|
||||||
|
if self.decode_mask_with_shared_tokens:
|
||||||
|
mask_tokens_out = mask_tokens_out.view(B, self.multiplex_count, 1, -1)
|
||||||
|
else:
|
||||||
|
mask_tokens_out = mask_tokens_out.view(
|
||||||
|
B, self.multiplex_count, self.num_mask_output_per_object, -1
|
||||||
|
)
|
||||||
|
if self.num_multimask_outputs == 0:
|
||||||
|
hyper_in = self.output_hypernetworks_mlp(
|
||||||
|
mask_tokens_out[:, :, 0, :]
|
||||||
|
).unsqueeze(2) # [B, M, 1, C]
|
||||||
|
else:
|
||||||
|
hyper_in_list: List[torch.Tensor] = []
|
||||||
|
for i in range(self.num_mask_output_per_object):
|
||||||
|
if self.decode_mask_with_shared_tokens:
|
||||||
|
hyper_in_list.append(
|
||||||
|
self.output_hypernetworks_mlps[i](mask_tokens_out[:, :, 0, :])
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
hyper_in_list.append(
|
||||||
|
self.output_hypernetworks_mlps[i](mask_tokens_out[:, :, i, :])
|
||||||
|
)
|
||||||
|
# hyper_in: [B, M, num_multimask_outputs+1, C]
|
||||||
|
hyper_in = torch.stack(hyper_in_list, dim=2)
|
||||||
|
|
||||||
|
# generate the masks
|
||||||
|
b, c, h, w = upscaled_embedding.shape
|
||||||
|
masks = torch.bmm(
|
||||||
|
hyper_in.flatten(1, 2), upscaled_embedding.view(b, c, h * w)
|
||||||
|
).view(b, self.multiplex_count, self.num_mask_output_per_object, h, w)
|
||||||
|
|
||||||
|
# Generate mask quality predictions, with shape b * multiplex_count * (num_multimask_outputs+1)
|
||||||
|
iou_pred = self.iou_prediction_head(iou_token_out).view(
|
||||||
|
b, self.multiplex_count, self.num_mask_output_per_object
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.pred_obj_scores:
|
||||||
|
# Generate mask quality predictions, with shape b * (num_multimask_outputs+1)
|
||||||
|
if (
|
||||||
|
self.decode_mask_attribute_with_shared_tokens
|
||||||
|
and not self.decode_mask_with_shared_tokens
|
||||||
|
):
|
||||||
|
object_score_logits = (
|
||||||
|
self.pred_obj_score_head(obj_score_token_out)
|
||||||
|
.view(b, self.multiplex_count, self.num_mask_output_per_object)
|
||||||
|
.sum(-1, keepdim=True)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
object_score_logits = self.pred_obj_score_head(obj_score_token_out)
|
||||||
|
else:
|
||||||
|
# Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
|
||||||
|
object_score_logits = 10.0 * iou_pred.new_ones(
|
||||||
|
iou_pred.shape[0], iou_pred.shape[1]
|
||||||
|
)
|
||||||
|
|
||||||
|
outputs = {
|
||||||
|
"masks": masks,
|
||||||
|
"iou_pred": iou_pred,
|
||||||
|
"mask_tokens_out": mask_tokens_out,
|
||||||
|
"object_score_logits": object_score_logits,
|
||||||
|
}
|
||||||
|
|
||||||
|
return outputs
|
||||||
|
|
||||||
|
def _get_stability_scores(self, mask_logits):
|
||||||
|
"""
|
||||||
|
Compute stability scores of the mask logits based on the IoU between upper and
|
||||||
|
lower thresholds.
|
||||||
|
"""
|
||||||
|
mask_logits = mask_logits.flatten(-2)
|
||||||
|
stability_delta = self.dynamic_multimask_stability_delta
|
||||||
|
area_i = torch.sum(mask_logits > stability_delta, dim=-1).float()
|
||||||
|
area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float()
|
||||||
|
stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0)
|
||||||
|
return stability_scores
|
||||||
|
|
||||||
|
def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
|
||||||
|
"""
|
||||||
|
When outputting a single mask, if the stability score from the current single-mask
|
||||||
|
output (based on output token 0) falls below a threshold, we instead select from
|
||||||
|
multi-mask outputs (based on output token 1~3) the mask with the highest predicted
|
||||||
|
IoU score. This is intended to ensure a valid mask for both clicking and tracking.
|
||||||
|
"""
|
||||||
|
# first, flatten the batch and the multiplex dimensions
|
||||||
|
B, M = all_mask_logits.shape[:2]
|
||||||
|
all_mask_logits = all_mask_logits.flatten(0, 1)
|
||||||
|
all_iou_scores = all_iou_scores.flatten(0, 1)
|
||||||
|
|
||||||
|
# The best mask from multimask output tokens (1~3)
|
||||||
|
multimask_logits = all_mask_logits[:, 1:, :, :]
|
||||||
|
multimask_iou_scores = all_iou_scores[:, 1:]
|
||||||
|
best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1)
|
||||||
|
batch_inds = torch.arange(
|
||||||
|
multimask_iou_scores.size(0), device=all_iou_scores.device
|
||||||
|
)
|
||||||
|
best_multimask_logits = multimask_logits[batch_inds, best_scores_inds]
|
||||||
|
best_multimask_logits = best_multimask_logits.unsqueeze(1)
|
||||||
|
best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds]
|
||||||
|
best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1)
|
||||||
|
|
||||||
|
# The mask from singlemask output token 0 and its stability score
|
||||||
|
singlemask_logits = all_mask_logits[:, 0:1, :, :]
|
||||||
|
singlemask_iou_scores = all_iou_scores[:, 0:1]
|
||||||
|
stability_scores = self._get_stability_scores(singlemask_logits)
|
||||||
|
is_stable = stability_scores >= self.dynamic_multimask_stability_thresh
|
||||||
|
|
||||||
|
# Dynamically fall back to best multimask output upon low stability scores.
|
||||||
|
mask_logits_out = torch.where(
|
||||||
|
is_stable[..., None, None].expand_as(singlemask_logits),
|
||||||
|
singlemask_logits,
|
||||||
|
best_multimask_logits,
|
||||||
|
)
|
||||||
|
iou_scores_out = torch.where(
|
||||||
|
is_stable.expand_as(singlemask_iou_scores),
|
||||||
|
singlemask_iou_scores,
|
||||||
|
best_multimask_iou_scores,
|
||||||
|
)
|
||||||
|
|
||||||
|
# restore the batch and multiplex dimensions
|
||||||
|
mask_logits_out = mask_logits_out.unflatten(0, (B, M))
|
||||||
|
iou_scores_out = iou_scores_out.unflatten(0, (B, M))
|
||||||
|
|
||||||
|
return mask_logits_out, iou_scores_out
|
||||||
|
|
||||||
|
|
||||||
|
# Lightly adapted from
|
||||||
|
# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
|
||||||
|
class MLP(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
input_dim: int,
|
||||||
|
hidden_dim: int,
|
||||||
|
output_dim: int,
|
||||||
|
num_layers: int,
|
||||||
|
sigmoid_output: bool = False,
|
||||||
|
) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.num_layers = num_layers
|
||||||
|
h = [hidden_dim] * (num_layers - 1)
|
||||||
|
self.layers = nn.ModuleList(
|
||||||
|
nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
|
||||||
|
)
|
||||||
|
self.sigmoid_output = sigmoid_output
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
for i, layer in enumerate(self.layers):
|
||||||
|
x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
|
||||||
|
if self.sigmoid_output:
|
||||||
|
x = F.sigmoid(x)
|
||||||
|
return x
|
||||||
@@ -0,0 +1,538 @@
|
|||||||
|
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
||||||
|
|
||||||
|
# pyre-unsafe
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import math
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from torch import nn
|
||||||
|
|
||||||
|
# Special values for object tracking
|
||||||
|
_PADDING_NUM = -1 # Marks empty slots in buckets
|
||||||
|
_REMOVED_NUM = -1116 # Marks objects that have been removed
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class MultiplexState:
|
||||||
|
"""
|
||||||
|
MultiplexState records the state of multiplexing, for one or more buckets.
|
||||||
|
|
||||||
|
At a high level, we deal with the conversion of tensors between the data space (batch_size, num_channels, ...)
|
||||||
|
and the multiplex space (num_buckets, multiplex_count, num_channels, ...).
|
||||||
|
|
||||||
|
The multiplex state stores the assignments of each batch element to a slot in a bucket.
|
||||||
|
Each bucket has a fixed number of slots (multiplex_count), and not all slots need to be filled.
|
||||||
|
The batch size should equate to total_valid_entries, which is the sum of the number of valid entries in each bucket.
|
||||||
|
|
||||||
|
There are two main operations that this class supports:
|
||||||
|
mux: convert tensors in the data space to the multiplex space.
|
||||||
|
The mental model is that we start from a tensor of zeros that has the shape of the output,
|
||||||
|
then we go through the valid entries and place them into the corresponding slots, indicated by the assignments.
|
||||||
|
|
||||||
|
demux: convert tensors in the multiplex space to the data space.
|
||||||
|
This is the reverse operation of mux. Note that zeros were used in mux for the padding slots,
|
||||||
|
and that those slots are ignored in demux.
|
||||||
|
|
||||||
|
There are also two utility functions for object mangement:
|
||||||
|
add_objects: add new objects to the state by filling in empty slots
|
||||||
|
remove_objects: remove objects from the state by marking them as removed (not the same as empty!)
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
assignments: list[list[int]],
|
||||||
|
device: torch.device,
|
||||||
|
dtype: torch.dtype,
|
||||||
|
allowed_bucket_capacity: int,
|
||||||
|
*,
|
||||||
|
object_ids: Optional[list[int]] = None,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
assignments: a list of lists of object indices
|
||||||
|
Each top-level list represents a bucket
|
||||||
|
Each inner list represents the object indices that are in the bucket
|
||||||
|
The object indices must ranges from 0 to num_valid_entries - 1, except for the following special values (all negatives):
|
||||||
|
_PADDING_NUM, which denotes padding entries
|
||||||
|
_REMOVED_NUM, which denotes an pre-existing object that got removed (currently not used during init)
|
||||||
|
If you wish to save the "true" object IDs, i.e., during inference, you can bookkeep them here
|
||||||
|
"""
|
||||||
|
self.device = device
|
||||||
|
self.dtype = dtype
|
||||||
|
|
||||||
|
# Initialize bucket assignments and precompute matrices
|
||||||
|
self.allowed_bucket_capacity = allowed_bucket_capacity
|
||||||
|
self._initialize_assignments(assignments, object_ids=object_ids)
|
||||||
|
|
||||||
|
def _initialize_assignments(
|
||||||
|
self, assignments: list[list[int]], *, object_ids: Optional[list[int]] = None
|
||||||
|
):
|
||||||
|
self.assignments = assignments
|
||||||
|
self.num_buckets = len(self.assignments)
|
||||||
|
if self.num_buckets == 0:
|
||||||
|
logger.error("No buckets found in the state")
|
||||||
|
raise ValueError("No buckets found in the state")
|
||||||
|
|
||||||
|
self.multiplex_count = len(self.assignments[0])
|
||||||
|
assert all(
|
||||||
|
len(self.assignments[i]) == self.multiplex_count
|
||||||
|
for i in range(self.num_buckets)
|
||||||
|
)
|
||||||
|
|
||||||
|
# number of non-negative elements in the state
|
||||||
|
self.total_valid_entries = sum(
|
||||||
|
sum(1 for x in bucket if x >= 0) for bucket in self.assignments
|
||||||
|
)
|
||||||
|
self.total_non_padding_entries = sum(
|
||||||
|
sum(1 for x in bucket if x != _PADDING_NUM) for bucket in self.assignments
|
||||||
|
)
|
||||||
|
|
||||||
|
# check the validity of the object IDs
|
||||||
|
self.object_ids = object_ids
|
||||||
|
if self.object_ids is not None:
|
||||||
|
assert (
|
||||||
|
len(self.object_ids) == self.total_valid_entries
|
||||||
|
), "object_ids should map 1:1 to the valid entries"
|
||||||
|
|
||||||
|
# check the validity of the assignments
|
||||||
|
all_object_idxs = set()
|
||||||
|
for bucket in self.assignments:
|
||||||
|
valid_entries_in_bucket = sum(1 for x in bucket if x != _PADDING_NUM)
|
||||||
|
assert (
|
||||||
|
valid_entries_in_bucket <= self.allowed_bucket_capacity
|
||||||
|
), f"{valid_entries_in_bucket=} > {self.allowed_bucket_capacity=}"
|
||||||
|
for obj_idx in bucket:
|
||||||
|
if obj_idx >= 0:
|
||||||
|
assert (
|
||||||
|
obj_idx < self.total_non_padding_entries
|
||||||
|
), f"object ID {obj_idx} >= {self.total_non_padding_entries}"
|
||||||
|
assert obj_idx not in all_object_idxs, "object IDs must be unique"
|
||||||
|
all_object_idxs.add(obj_idx)
|
||||||
|
|
||||||
|
# Precompute and cache the actual selection matrices
|
||||||
|
self._precompute_transition_matrices(self.device, self.dtype)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def available_slots(self) -> int:
|
||||||
|
# returns the number of available slots in the state
|
||||||
|
return (
|
||||||
|
self.num_buckets * self.allowed_bucket_capacity
|
||||||
|
- self.total_non_padding_entries
|
||||||
|
)
|
||||||
|
|
||||||
|
def find_next_batch_of_available_indices(
|
||||||
|
self,
|
||||||
|
num_objects: int,
|
||||||
|
*,
|
||||||
|
allow_new_buckets: bool = False,
|
||||||
|
prefer_new_buckets: bool = False,
|
||||||
|
) -> list[int]:
|
||||||
|
# produce a list of consecutive indices that are available in the state
|
||||||
|
# Note: prefer_new_buckets parameter is accepted for API compatibility but not used here
|
||||||
|
# as the actual bucket allocation logic is in add_objects()
|
||||||
|
assert num_objects > 0, f"{num_objects=} must be positive"
|
||||||
|
if not allow_new_buckets:
|
||||||
|
assert (
|
||||||
|
self.available_slots >= num_objects
|
||||||
|
), f"not enough available slots {self.available_slots} < {num_objects}"
|
||||||
|
|
||||||
|
return list(
|
||||||
|
range(
|
||||||
|
self.total_valid_entries,
|
||||||
|
self.total_valid_entries + num_objects,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def add_objects(
|
||||||
|
self,
|
||||||
|
object_indices: list[int],
|
||||||
|
*,
|
||||||
|
object_ids: Optional[list[int]] = None,
|
||||||
|
allow_new_buckets: bool = False,
|
||||||
|
prefer_new_buckets: bool = False,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Add new objects to the state by filling in empty slots and
|
||||||
|
creating new buckets if necessary.
|
||||||
|
|
||||||
|
object_indices must be sorted and follow existing object indices.
|
||||||
|
If prefer_new_buckets is True, we skip filling existing slots and place
|
||||||
|
the objects into freshly created buckets (requires allow_new_buckets=True).
|
||||||
|
"""
|
||||||
|
if len(object_indices) == 0:
|
||||||
|
return
|
||||||
|
|
||||||
|
# we will modify this in-place
|
||||||
|
object_indices = object_indices.copy()
|
||||||
|
assert (object_ids is None) == (
|
||||||
|
self.object_ids is None
|
||||||
|
), "object_ids must either be always given or always omitted"
|
||||||
|
|
||||||
|
if object_ids is not None:
|
||||||
|
assert len(object_ids) == len(
|
||||||
|
object_indices
|
||||||
|
), "object_ids must have the same length as object_indices"
|
||||||
|
object_ids = object_ids.copy()
|
||||||
|
|
||||||
|
num_new_objects = len(object_indices)
|
||||||
|
assert object_indices == sorted(object_indices), "object_indices must be sorted"
|
||||||
|
object_indices.reverse() # reverse so we can pop from the end
|
||||||
|
if object_ids is not None:
|
||||||
|
object_ids.reverse()
|
||||||
|
|
||||||
|
if prefer_new_buckets:
|
||||||
|
assert allow_new_buckets, "prefer_new_buckets requires allow_new_buckets"
|
||||||
|
|
||||||
|
slots_filled = 0
|
||||||
|
buckets_created = 0
|
||||||
|
|
||||||
|
def _pop_next():
|
||||||
|
idx = object_indices.pop()
|
||||||
|
if object_ids is not None and self.object_ids is not None:
|
||||||
|
self.object_ids.append(object_ids.pop())
|
||||||
|
return idx
|
||||||
|
|
||||||
|
if not prefer_new_buckets:
|
||||||
|
# Fill empty slots in existing buckets first
|
||||||
|
for bucket in self.assignments:
|
||||||
|
for i in range(self.allowed_bucket_capacity):
|
||||||
|
if bucket[i] == _PADDING_NUM:
|
||||||
|
bucket[i] = _pop_next()
|
||||||
|
slots_filled += 1
|
||||||
|
if len(object_indices) == 0:
|
||||||
|
break
|
||||||
|
if len(object_indices) == 0:
|
||||||
|
break
|
||||||
|
|
||||||
|
if len(object_indices) > 0 and not allow_new_buckets:
|
||||||
|
raise ValueError(
|
||||||
|
f"Cannot place objects {list(reversed(object_indices))} without creating new buckets"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create new buckets for remaining objects (or all objects if prefer_new_buckets)
|
||||||
|
while len(object_indices) > 0:
|
||||||
|
new_bucket = [_PADDING_NUM] * self.multiplex_count
|
||||||
|
for i in range(self.allowed_bucket_capacity):
|
||||||
|
if len(object_indices) == 0:
|
||||||
|
break
|
||||||
|
new_bucket[i] = _pop_next()
|
||||||
|
self.assignments.append(new_bucket)
|
||||||
|
buckets_created += 1
|
||||||
|
|
||||||
|
# reinitialize all the settings
|
||||||
|
original_num_entries = self.total_valid_entries
|
||||||
|
self._initialize_assignments(self.assignments, object_ids=self.object_ids)
|
||||||
|
assert (
|
||||||
|
self.total_valid_entries == original_num_entries + num_new_objects
|
||||||
|
), f"{self.total_valid_entries=} != {original_num_entries=} + {num_new_objects=}"
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"Filled {slots_filled} slots and created {buckets_created} new buckets"
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
f"{self.num_buckets=}, {self.total_valid_entries=}, {self.total_non_padding_entries=}"
|
||||||
|
)
|
||||||
|
|
||||||
|
def remove_objects(self, object_indices: list[int], strict: bool = True):
|
||||||
|
"""
|
||||||
|
Remove objects from the state by marking them as removed.
|
||||||
|
Remove a bucket if all objects in the bucket are removed.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
object_indices: List of object indices to remove
|
||||||
|
strict: If True, will raise an error if any object indices are not found in the state
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List of bucket indices that we are going to keep
|
||||||
|
"""
|
||||||
|
object_indices = object_indices.copy()
|
||||||
|
|
||||||
|
# Mark objects as removed in assignments
|
||||||
|
for bucket_idx, bucket in enumerate(self.assignments):
|
||||||
|
for slot_idx, obj_id in enumerate(bucket):
|
||||||
|
if obj_id in object_indices:
|
||||||
|
self.assignments[bucket_idx][slot_idx] = _REMOVED_NUM
|
||||||
|
object_indices.remove(obj_id)
|
||||||
|
|
||||||
|
if strict:
|
||||||
|
assert (
|
||||||
|
len(object_indices) == 0
|
||||||
|
), f"Failed to remove objects: {object_indices}"
|
||||||
|
|
||||||
|
# Check which buckets should be completely removed (all objects removed/paddings)
|
||||||
|
# and which buckets we will keep
|
||||||
|
buckets_to_remove = []
|
||||||
|
buckets_to_keep = []
|
||||||
|
for bucket_idx, bucket in enumerate(self.assignments):
|
||||||
|
# Check if all objects in this bucket are removed or are paddings
|
||||||
|
all_removed = all(
|
||||||
|
obj_id in [_PADDING_NUM, _REMOVED_NUM] for obj_id in bucket
|
||||||
|
)
|
||||||
|
if all_removed:
|
||||||
|
buckets_to_remove.append(bucket_idx)
|
||||||
|
logger.info(
|
||||||
|
f"Bucket {bucket_idx} marked for removal - all objects removed/paddings"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
buckets_to_keep.append(bucket_idx)
|
||||||
|
|
||||||
|
# Remove buckets in reverse order to maintain correct indices
|
||||||
|
for bucket_idx in reversed(buckets_to_remove):
|
||||||
|
del self.assignments[bucket_idx]
|
||||||
|
|
||||||
|
if len(buckets_to_keep) == 0:
|
||||||
|
logger.info(f"Removing all buckets: {buckets_to_remove}; state invalidated")
|
||||||
|
self.assignments = None
|
||||||
|
if self.object_ids is not None:
|
||||||
|
self.object_ids = []
|
||||||
|
return buckets_to_keep
|
||||||
|
|
||||||
|
# After removal, remap object IDs to be sequential
|
||||||
|
# Collect all unique positive object IDs and create a mapping to sequential IDs
|
||||||
|
all_positive_ids = set()
|
||||||
|
for bucket in self.assignments:
|
||||||
|
for obj_id in bucket:
|
||||||
|
if obj_id >= 0:
|
||||||
|
all_positive_ids.add(obj_id)
|
||||||
|
|
||||||
|
# Create mapping from old IDs to new sequential IDs
|
||||||
|
sorted_ids = sorted(all_positive_ids)
|
||||||
|
id_mapping = {old_id: new_id for new_id, old_id in enumerate(sorted_ids)}
|
||||||
|
|
||||||
|
# Apply the mapping to assignments to make IDs sequential
|
||||||
|
for bucket in self.assignments:
|
||||||
|
for i, obj_id in enumerate(bucket):
|
||||||
|
if obj_id >= 0:
|
||||||
|
bucket[i] = id_mapping[obj_id]
|
||||||
|
|
||||||
|
# Update object_ids if they exist
|
||||||
|
if self.object_ids is not None:
|
||||||
|
# Create new object_ids array based on the remapped indices
|
||||||
|
# We need to preserve the original object_ids for the objects that weren't removed
|
||||||
|
new_object_ids = [None] * len(sorted_ids)
|
||||||
|
|
||||||
|
# Map the original object_ids to their new positions
|
||||||
|
for old_idx, new_idx in id_mapping.items():
|
||||||
|
new_object_ids[new_idx] = self.object_ids[old_idx]
|
||||||
|
|
||||||
|
assert not any(obj_id is None for obj_id in new_object_ids)
|
||||||
|
self.object_ids = new_object_ids
|
||||||
|
|
||||||
|
# Reinitialize the state to update all internal structures
|
||||||
|
self._initialize_assignments(self.assignments, object_ids=self.object_ids)
|
||||||
|
|
||||||
|
logger.info(f"Removed these buckets: {buckets_to_remove}")
|
||||||
|
logger.info(f"Kept these buckets: {buckets_to_keep}")
|
||||||
|
logger.info(
|
||||||
|
f"Remaining buckets: {self.num_buckets}, total valid entries: {self.total_valid_entries}"
|
||||||
|
)
|
||||||
|
|
||||||
|
return buckets_to_keep
|
||||||
|
|
||||||
|
def _precompute_transition_matrices(self, device: torch.device, dtype: torch.dtype):
|
||||||
|
"""
|
||||||
|
Precompute the transition matrices for maximum efficiency.
|
||||||
|
Note that these should be partial permutation matrices.
|
||||||
|
"""
|
||||||
|
# Create a transition matrix for muxing
|
||||||
|
self.mux_matrix = torch.zeros(
|
||||||
|
self.num_buckets * self.multiplex_count,
|
||||||
|
self.total_valid_entries,
|
||||||
|
device=device,
|
||||||
|
dtype=dtype,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create a transition matrix for demuxing
|
||||||
|
self.demux_matrix = torch.zeros(
|
||||||
|
self.total_valid_entries,
|
||||||
|
self.num_buckets * self.multiplex_count,
|
||||||
|
device=device,
|
||||||
|
dtype=dtype,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Fill both matrices based on assignments
|
||||||
|
for i in range(self.num_buckets):
|
||||||
|
for j in range(self.multiplex_count):
|
||||||
|
bucket_idx = i * self.multiplex_count + j
|
||||||
|
object_idx = self.assignments[i][j]
|
||||||
|
if object_idx >= 0:
|
||||||
|
self.mux_matrix[bucket_idx, object_idx] = 1.0
|
||||||
|
self.demux_matrix[object_idx, bucket_idx] = 1.0
|
||||||
|
|
||||||
|
def mux(self, x: torch.Tensor) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
Multiplexing operation
|
||||||
|
x: self.total_valid_entries * ...
|
||||||
|
|
||||||
|
return num_buckets * multiplex_count * ...
|
||||||
|
with padding entries filled with 0
|
||||||
|
"""
|
||||||
|
num_valid_entries = x.shape[0]
|
||||||
|
assert (
|
||||||
|
num_valid_entries == self.total_valid_entries
|
||||||
|
), f"{num_valid_entries=} != {self.total_valid_entries=}"
|
||||||
|
output_shape = (
|
||||||
|
self.num_buckets,
|
||||||
|
self.multiplex_count,
|
||||||
|
) + x.shape[1:]
|
||||||
|
|
||||||
|
x_flat = x.reshape(num_valid_entries, -1)
|
||||||
|
|
||||||
|
# Apply mux matrix: (num_buckets * multiplex_count, batch_size) @ (batch_size, features)
|
||||||
|
# Result: (num_buckets * multiplex_count, features)
|
||||||
|
result_flat = self.mux_matrix @ x_flat
|
||||||
|
|
||||||
|
result = result_flat.view(output_shape)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def demux(self, x: torch.Tensor) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
Inverse operation of mux
|
||||||
|
x: num_buckets, multiplex_count * ...
|
||||||
|
Returns: total_valid_entries * ...
|
||||||
|
"""
|
||||||
|
num_buckets, multiplex_count = x.shape[:2]
|
||||||
|
assert num_buckets == self.num_buckets, f"{num_buckets=} != {self.num_buckets=}"
|
||||||
|
assert (
|
||||||
|
multiplex_count == self.multiplex_count
|
||||||
|
), f"{multiplex_count=} != {self.multiplex_count=}"
|
||||||
|
output_shape = (self.total_valid_entries,) + x.shape[2:]
|
||||||
|
|
||||||
|
x_flat = x.reshape(num_buckets * multiplex_count, -1)
|
||||||
|
|
||||||
|
# Apply demux matrix: (total_valid_entries, num_buckets*multiplex_count) @ (num_buckets*multiplex_count, features)
|
||||||
|
# Result: (total_valid_entries, features)
|
||||||
|
result_flat = self.demux_matrix @ x_flat
|
||||||
|
|
||||||
|
result = result_flat.view(output_shape)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def get_valid_object_mask(self) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
Returns a (num_buckets, multiplex_count) tensor with 1 for valid entries and 0 for padding entries
|
||||||
|
"""
|
||||||
|
valid_mask = self.mux_matrix.sum(dim=1) > 0
|
||||||
|
valid_mask = valid_mask.reshape(self.num_buckets, self.multiplex_count)
|
||||||
|
|
||||||
|
return valid_mask
|
||||||
|
|
||||||
|
def get_all_valid_object_idx(self) -> set[int]:
|
||||||
|
"""
|
||||||
|
Returns a set of all valid object idx in the state
|
||||||
|
Note that this returns the internal object idx representations,
|
||||||
|
not the arbitrary object IDs that are passed in during initialization
|
||||||
|
"""
|
||||||
|
all_valid_objects = {
|
||||||
|
obj_idx for bucket in self.assignments for obj_idx in bucket if obj_idx >= 0
|
||||||
|
}
|
||||||
|
return all_valid_objects
|
||||||
|
|
||||||
|
|
||||||
|
class MultiplexController(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
multiplex_count: int,
|
||||||
|
full_shuffle: bool = False,
|
||||||
|
eval_multiplex_count: int = -1,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
self.multiplex_count = multiplex_count
|
||||||
|
self.full_shuffle = full_shuffle
|
||||||
|
if eval_multiplex_count < 0:
|
||||||
|
self.eval_multiplex_count = multiplex_count
|
||||||
|
else:
|
||||||
|
self.eval_multiplex_count = eval_multiplex_count
|
||||||
|
assert self.multiplex_count >= 1
|
||||||
|
|
||||||
|
@property
|
||||||
|
def allowed_bucket_capacity(self) -> int:
|
||||||
|
if self.training:
|
||||||
|
return self.multiplex_count
|
||||||
|
else:
|
||||||
|
return self.eval_multiplex_count
|
||||||
|
|
||||||
|
def get_state(
|
||||||
|
self,
|
||||||
|
num_valid_entries: int,
|
||||||
|
device: torch.device,
|
||||||
|
dtype: torch.dtype,
|
||||||
|
random: bool = True,
|
||||||
|
*,
|
||||||
|
object_ids: Optional[
|
||||||
|
list[int]
|
||||||
|
] = None, # object_ids is an auxiliary field that we pass to the state unmodified
|
||||||
|
) -> MultiplexState:
|
||||||
|
# returns a state that maps elements in the batch to buckets of size self.multiplex_count
|
||||||
|
|
||||||
|
allowed_bucket_capacity = self.allowed_bucket_capacity
|
||||||
|
|
||||||
|
# the size of the bucket during training
|
||||||
|
true_bucket_capacity = self.multiplex_count
|
||||||
|
|
||||||
|
num_buckets = math.ceil(num_valid_entries / allowed_bucket_capacity)
|
||||||
|
# each bucket contains at most self.multiplex_count elements
|
||||||
|
# padding elements are marked with _PADDING_NUM (only the last bucket should contain _PADDING_NUM)
|
||||||
|
|
||||||
|
if self.full_shuffle:
|
||||||
|
# Shuffle all IDs, including the paddings
|
||||||
|
ids = torch.cat(
|
||||||
|
[
|
||||||
|
torch.arange(num_valid_entries, dtype=torch.long),
|
||||||
|
torch.tensor(
|
||||||
|
[_PADDING_NUM]
|
||||||
|
* (num_buckets * true_bucket_capacity - num_valid_entries),
|
||||||
|
dtype=torch.long,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
dim=0,
|
||||||
|
)
|
||||||
|
if random:
|
||||||
|
indices = torch.randperm(ids.shape[0], dtype=torch.long)
|
||||||
|
ids = ids[indices]
|
||||||
|
|
||||||
|
# convert to a list of list
|
||||||
|
assignments = []
|
||||||
|
for i in range(num_buckets):
|
||||||
|
assignments.append(
|
||||||
|
ids[
|
||||||
|
i * true_bucket_capacity : (i + 1) * true_bucket_capacity
|
||||||
|
].tolist()
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Only shuffle the the IDs within the first #batch_size slots, leave all paddings at the end
|
||||||
|
if random:
|
||||||
|
# randomly assign ids to buckets
|
||||||
|
ids = torch.randperm(num_valid_entries, dtype=torch.int64)
|
||||||
|
else:
|
||||||
|
ids = torch.arange(num_valid_entries)
|
||||||
|
# append with _PADDING_NUM to make a multiple of bucket_capacity
|
||||||
|
total_elements = num_buckets * allowed_bucket_capacity
|
||||||
|
if ids.shape[0] < total_elements:
|
||||||
|
ids = torch.cat(
|
||||||
|
[
|
||||||
|
ids,
|
||||||
|
torch.tensor([_PADDING_NUM] * (total_elements - ids.shape[0])),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
# convert to a list of list
|
||||||
|
assignments = []
|
||||||
|
for i in range(num_buckets):
|
||||||
|
assignments.append(
|
||||||
|
ids[
|
||||||
|
i * allowed_bucket_capacity : (i + 1) * allowed_bucket_capacity
|
||||||
|
].tolist()
|
||||||
|
+ [_PADDING_NUM] * (true_bucket_capacity - allowed_bucket_capacity)
|
||||||
|
)
|
||||||
|
|
||||||
|
return MultiplexState(
|
||||||
|
assignments,
|
||||||
|
device,
|
||||||
|
dtype,
|
||||||
|
allowed_bucket_capacity=allowed_bucket_capacity,
|
||||||
|
object_ids=object_ids,
|
||||||
|
)
|
||||||
@@ -9,6 +9,7 @@ from typing import List, Optional, Tuple
|
|||||||
|
|
||||||
import torch
|
import torch
|
||||||
import torch.nn as nn
|
import torch.nn as nn
|
||||||
|
from sam3.model.data_misc import NestedTensor
|
||||||
|
|
||||||
|
|
||||||
class Sam3DualViTDetNeck(nn.Module):
|
class Sam3DualViTDetNeck(nn.Module):
|
||||||
@@ -124,3 +125,145 @@ class Sam3DualViTDetNeck(nn.Module):
|
|||||||
sam2_out.append(sam2_x_out)
|
sam2_out.append(sam2_x_out)
|
||||||
sam2_pos.append(sam2_pos_out)
|
sam2_pos.append(sam2_pos_out)
|
||||||
return sam3_out, sam3_pos, sam2_out, sam2_pos
|
return sam3_out, sam3_pos, sam2_out, sam2_pos
|
||||||
|
|
||||||
|
|
||||||
|
class Sam3TriViTDetNeck(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
trunk: nn.Module,
|
||||||
|
position_encoding: nn.Module,
|
||||||
|
d_model: int,
|
||||||
|
neck_norm=None,
|
||||||
|
scale_factors=(4.0, 2.0, 1.0),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
SimpleFPN neck with three heads (sam3, interactive, propagation).
|
||||||
|
"""
|
||||||
|
super().__init__()
|
||||||
|
self.trunk = trunk
|
||||||
|
self.position_encoding = position_encoding
|
||||||
|
self.convs = nn.ModuleList()
|
||||||
|
|
||||||
|
self.scale_factors = scale_factors
|
||||||
|
use_bias = neck_norm is None
|
||||||
|
dim = self.trunk.channel_list[-1]
|
||||||
|
|
||||||
|
for _, scale in enumerate(scale_factors):
|
||||||
|
current = nn.Sequential()
|
||||||
|
|
||||||
|
if scale == 4.0:
|
||||||
|
current.add_module(
|
||||||
|
"dconv_2x2_0",
|
||||||
|
nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
|
||||||
|
)
|
||||||
|
current.add_module(
|
||||||
|
"gelu",
|
||||||
|
nn.GELU(),
|
||||||
|
)
|
||||||
|
current.add_module(
|
||||||
|
"dconv_2x2_1",
|
||||||
|
nn.ConvTranspose2d(dim // 2, dim // 4, kernel_size=2, stride=2),
|
||||||
|
)
|
||||||
|
out_dim = dim // 4
|
||||||
|
elif scale == 2.0:
|
||||||
|
current.add_module(
|
||||||
|
"dconv_2x2",
|
||||||
|
nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
|
||||||
|
)
|
||||||
|
out_dim = dim // 2
|
||||||
|
elif scale == 1.0:
|
||||||
|
out_dim = dim
|
||||||
|
elif scale == 0.5:
|
||||||
|
current.add_module(
|
||||||
|
"maxpool_2x2",
|
||||||
|
nn.MaxPool2d(kernel_size=2, stride=2),
|
||||||
|
)
|
||||||
|
out_dim = dim
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(f"scale_factor={scale} is not supported yet.")
|
||||||
|
|
||||||
|
current.add_module(
|
||||||
|
"conv_1x1",
|
||||||
|
nn.Conv2d(
|
||||||
|
in_channels=out_dim,
|
||||||
|
out_channels=d_model,
|
||||||
|
kernel_size=1,
|
||||||
|
bias=use_bias,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
current.add_module(
|
||||||
|
"conv_3x3",
|
||||||
|
nn.Conv2d(
|
||||||
|
in_channels=d_model,
|
||||||
|
out_channels=d_model,
|
||||||
|
kernel_size=3,
|
||||||
|
padding=1,
|
||||||
|
bias=use_bias,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
self.convs.append(current)
|
||||||
|
|
||||||
|
# Assumes the new necks are just clones of the original neck
|
||||||
|
self.interactive_convs = deepcopy(self.convs)
|
||||||
|
self.propagation_convs = deepcopy(self.convs)
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
tensor_list,
|
||||||
|
*,
|
||||||
|
need_sam3_out: bool = True,
|
||||||
|
need_interactive_out: bool = True,
|
||||||
|
need_propagation_out: bool = True,
|
||||||
|
):
|
||||||
|
xs = self.trunk(tensor_list)
|
||||||
|
sam3_out = []
|
||||||
|
interactive_out = []
|
||||||
|
propagation_out = []
|
||||||
|
|
||||||
|
sam3_pos = []
|
||||||
|
interactive_pos = []
|
||||||
|
propagation_pos = []
|
||||||
|
x = xs[-1] # simpleFPN
|
||||||
|
# OSS trunk returns plain tensors; onevision trunk returns NestedTensors.
|
||||||
|
# Use getattr to handle both in a torch.compile-friendly way.
|
||||||
|
x_data = getattr(x, "tensors", x)
|
||||||
|
x_mask = getattr(x, "mask", None)
|
||||||
|
for _, (conv, interactive_conv, propagation_conv) in enumerate(
|
||||||
|
zip(self.convs, self.interactive_convs, self.propagation_convs)
|
||||||
|
):
|
||||||
|
if need_sam3_out:
|
||||||
|
sam3_conv_out = conv(x_data)
|
||||||
|
sam3_x_out = NestedTensor(sam3_conv_out, x_mask)
|
||||||
|
sam3_out.append(sam3_x_out)
|
||||||
|
sam3_pos.append(
|
||||||
|
self.position_encoding(sam3_conv_out).to(sam3_conv_out.dtype)
|
||||||
|
)
|
||||||
|
|
||||||
|
if need_interactive_out:
|
||||||
|
interactive_conv_out_t = interactive_conv(x_data)
|
||||||
|
interactive_conv_out = NestedTensor(interactive_conv_out_t, x_mask)
|
||||||
|
interactive_out.append(interactive_conv_out)
|
||||||
|
interactive_pos.append(
|
||||||
|
self.position_encoding(interactive_conv_out_t).to(
|
||||||
|
interactive_conv_out_t.dtype
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
if need_propagation_out:
|
||||||
|
propagation_conv_out = propagation_conv(x_data)
|
||||||
|
propagation_x_out = NestedTensor(propagation_conv_out, x_mask)
|
||||||
|
propagation_out.append(propagation_x_out)
|
||||||
|
propagation_pos.append(
|
||||||
|
self.position_encoding(propagation_conv_out).to(
|
||||||
|
propagation_conv_out.dtype
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
sam3_out,
|
||||||
|
sam3_pos,
|
||||||
|
interactive_out,
|
||||||
|
interactive_pos,
|
||||||
|
propagation_out,
|
||||||
|
propagation_pos,
|
||||||
|
)
|
||||||
|
|||||||
@@ -38,11 +38,17 @@ class PositionEmbeddingSine(nn.Module):
|
|||||||
# Precompute positional encodings under `precompute_resolution` to fill the cache
|
# Precompute positional encodings under `precompute_resolution` to fill the cache
|
||||||
# and avoid symbolic shape tracing errors in torch.compile in PyTorch 2.4 nightly.
|
# and avoid symbolic shape tracing errors in torch.compile in PyTorch 2.4 nightly.
|
||||||
if precompute_resolution is not None:
|
if precompute_resolution is not None:
|
||||||
# We precompute pos enc for stride 4, 8, 16 and 32 to fill `self.cache`.
|
# We precompute pos enc for all strides used by both DualViTDetNeck and
|
||||||
|
# TriViTDetNeck (scale_factors 4.0, 2.0, 1.0, 0.5 applied to backbone
|
||||||
|
# output at stride 14 from 1008px input → 72x72).
|
||||||
precompute_sizes = [
|
precompute_sizes = [
|
||||||
|
(int(precompute_resolution // 3.5), int(precompute_resolution // 3.5)),
|
||||||
(precompute_resolution // 4, precompute_resolution // 4),
|
(precompute_resolution // 4, precompute_resolution // 4),
|
||||||
|
(int(precompute_resolution // 7), int(precompute_resolution // 7)),
|
||||||
(precompute_resolution // 8, precompute_resolution // 8),
|
(precompute_resolution // 8, precompute_resolution // 8),
|
||||||
|
(int(precompute_resolution // 14), int(precompute_resolution // 14)),
|
||||||
(precompute_resolution // 16, precompute_resolution // 16),
|
(precompute_resolution // 16, precompute_resolution // 16),
|
||||||
|
(int(precompute_resolution // 28), int(precompute_resolution // 28)),
|
||||||
(precompute_resolution // 32, precompute_resolution // 32),
|
(precompute_resolution // 32, precompute_resolution // 32),
|
||||||
]
|
]
|
||||||
for size in precompute_sizes:
|
for size in precompute_sizes:
|
||||||
|
|||||||
@@ -94,9 +94,9 @@ class SAM3InteractiveImagePredictor(nn.Module):
|
|||||||
input_image = self._transforms(image)
|
input_image = self._transforms(image)
|
||||||
input_image = input_image[None, ...].to(self.device)
|
input_image = input_image[None, ...].to(self.device)
|
||||||
|
|
||||||
assert len(input_image.shape) == 4 and input_image.shape[1] == 3, (
|
assert (
|
||||||
f"input_image must be of size 1x3xHxW, got {input_image.shape}"
|
len(input_image.shape) == 4 and input_image.shape[1] == 3
|
||||||
)
|
), f"input_image must be of size 1x3xHxW, got {input_image.shape}"
|
||||||
logging.info("Computing image embeddings for the provided image...")
|
logging.info("Computing image embeddings for the provided image...")
|
||||||
backbone_out = self.model.forward_image(input_image)
|
backbone_out = self.model.forward_image(input_image)
|
||||||
(
|
(
|
||||||
@@ -133,17 +133,17 @@ class SAM3InteractiveImagePredictor(nn.Module):
|
|||||||
assert isinstance(image_list, list)
|
assert isinstance(image_list, list)
|
||||||
self._orig_hw = []
|
self._orig_hw = []
|
||||||
for image in image_list:
|
for image in image_list:
|
||||||
assert isinstance(image, np.ndarray), (
|
assert isinstance(
|
||||||
"Images are expected to be an np.ndarray in RGB format, and of shape HWC"
|
image, np.ndarray
|
||||||
)
|
), "Images are expected to be an np.ndarray in RGB format, and of shape HWC"
|
||||||
self._orig_hw.append(image.shape[:2])
|
self._orig_hw.append(image.shape[:2])
|
||||||
# Transform the image to the form expected by the model
|
# Transform the image to the form expected by the model
|
||||||
img_batch = self._transforms.forward_batch(image_list)
|
img_batch = self._transforms.forward_batch(image_list)
|
||||||
img_batch = img_batch.to(self.device)
|
img_batch = img_batch.to(self.device)
|
||||||
batch_size = img_batch.shape[0]
|
batch_size = img_batch.shape[0]
|
||||||
assert len(img_batch.shape) == 4 and img_batch.shape[1] == 3, (
|
assert (
|
||||||
f"img_batch must be of size Bx3xHxW, got {img_batch.shape}"
|
len(img_batch.shape) == 4 and img_batch.shape[1] == 3
|
||||||
)
|
), f"img_batch must be of size Bx3xHxW, got {img_batch.shape}"
|
||||||
logging.info("Computing image embeddings for the provided images...")
|
logging.info("Computing image embeddings for the provided images...")
|
||||||
backbone_out = self.model.forward_image(img_batch)
|
backbone_out = self.model.forward_image(img_batch)
|
||||||
(
|
(
|
||||||
@@ -299,9 +299,9 @@ class SAM3InteractiveImagePredictor(nn.Module):
|
|||||||
):
|
):
|
||||||
unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None
|
unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None
|
||||||
if point_coords is not None:
|
if point_coords is not None:
|
||||||
assert point_labels is not None, (
|
assert (
|
||||||
"point_labels must be supplied if point_coords is supplied."
|
point_labels is not None
|
||||||
)
|
), "point_labels must be supplied if point_coords is supplied."
|
||||||
point_coords = torch.as_tensor(
|
point_coords = torch.as_tensor(
|
||||||
point_coords, dtype=torch.float, device=self.device
|
point_coords, dtype=torch.float, device=self.device
|
||||||
)
|
)
|
||||||
@@ -438,9 +438,9 @@ class SAM3InteractiveImagePredictor(nn.Module):
|
|||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
"An image must be set with .set_image(...) to generate an embedding."
|
"An image must be set with .set_image(...) to generate an embedding."
|
||||||
)
|
)
|
||||||
assert self._features is not None, (
|
assert (
|
||||||
"Features must exist if an image has been set."
|
self._features is not None
|
||||||
)
|
), "Features must exist if an image has been set."
|
||||||
return self._features["image_embed"]
|
return self._features["image_embed"]
|
||||||
|
|
||||||
@property
|
@property
|
||||||
|
|||||||
@@ -0,0 +1,322 @@
|
|||||||
|
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
||||||
|
|
||||||
|
# pyre-unsafe
|
||||||
|
|
||||||
|
"""
|
||||||
|
Base predictor class shared by SAM3 and SAM3.1 (multiplex) video predictors.
|
||||||
|
|
||||||
|
Provides the common handle_request/handle_stream_request API and session management.
|
||||||
|
Subclasses only need to override methods where their behavior differs.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import gc
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from sam3.logger import get_logger
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Sam3BasePredictor:
|
||||||
|
"""
|
||||||
|
Base class for SAM3 video predictors. Provides:
|
||||||
|
- Session management (start, reset, close)
|
||||||
|
- Request dispatch (handle_request / handle_stream_request)
|
||||||
|
- Common add_prompt / propagate_in_video / remove_object / reset_session / close_session
|
||||||
|
|
||||||
|
Subclasses must set `self.model` and `self._all_inference_states` before use.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
# Subclasses must populate these
|
||||||
|
self.model = None
|
||||||
|
self._all_inference_states: Dict[str, dict] = {}
|
||||||
|
|
||||||
|
# ── Request dispatch ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
@torch.inference_mode()
|
||||||
|
def handle_request(self, request):
|
||||||
|
"""Dispatch a request based on its type."""
|
||||||
|
request_type = request["type"]
|
||||||
|
if request_type == "start_session":
|
||||||
|
return self.start_session(
|
||||||
|
resource_path=request["resource_path"],
|
||||||
|
session_id=request.get("session_id", None),
|
||||||
|
offload_video_to_cpu=request.get("offload_video_to_cpu", False),
|
||||||
|
)
|
||||||
|
elif request_type == "add_prompt":
|
||||||
|
return self.add_prompt(
|
||||||
|
session_id=request["session_id"],
|
||||||
|
frame_idx=request["frame_index"],
|
||||||
|
text=request.get("text", None),
|
||||||
|
points=request.get("points", None),
|
||||||
|
point_labels=request.get("point_labels", None),
|
||||||
|
clear_old_points=request.get("clear_old_points", True),
|
||||||
|
bounding_boxes=request.get("bounding_boxes", None),
|
||||||
|
bounding_box_labels=request.get("bounding_box_labels", None),
|
||||||
|
clear_old_boxes=request.get("clear_old_boxes", True),
|
||||||
|
output_prob_thresh=request.get(
|
||||||
|
"output_prob_thresh",
|
||||||
|
getattr(self, "default_output_prob_thresh", 0.5),
|
||||||
|
),
|
||||||
|
obj_id=request.get("obj_id", None),
|
||||||
|
)
|
||||||
|
elif request_type == "remove_object":
|
||||||
|
return self.remove_object(
|
||||||
|
session_id=request["session_id"],
|
||||||
|
frame_idx=request.get("frame_index", 0),
|
||||||
|
obj_id=request["obj_id"],
|
||||||
|
)
|
||||||
|
elif request_type == "reset_session":
|
||||||
|
return self.reset_session(session_id=request["session_id"])
|
||||||
|
elif request_type == "cancel_propagation":
|
||||||
|
return self.cancel_propagation(session_id=request["session_id"])
|
||||||
|
elif request_type == "close_session":
|
||||||
|
return self.close_session(
|
||||||
|
session_id=request["session_id"],
|
||||||
|
run_gc_collect=request.get("run_gc_collect", True),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise RuntimeError(f"invalid request type: {request_type}")
|
||||||
|
|
||||||
|
@torch.inference_mode()
|
||||||
|
def handle_stream_request(self, request):
|
||||||
|
"""Dispatch a stream request based on its type."""
|
||||||
|
request_type = request["type"]
|
||||||
|
if request_type == "propagate_in_video":
|
||||||
|
yield from self.propagate_in_video(
|
||||||
|
session_id=request["session_id"],
|
||||||
|
propagation_direction=request.get("propagation_direction", "both"),
|
||||||
|
start_frame_idx=request.get("start_frame_index", None),
|
||||||
|
max_frame_num_to_track=request.get("max_frame_num_to_track", None),
|
||||||
|
output_prob_thresh=request.get(
|
||||||
|
"output_prob_thresh",
|
||||||
|
getattr(self, "default_output_prob_thresh", 0.5),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise RuntimeError(f"invalid request type: {request_type}")
|
||||||
|
|
||||||
|
# ── Session management ────────────────────────────────────────────
|
||||||
|
|
||||||
|
def start_session(
|
||||||
|
self,
|
||||||
|
resource_path,
|
||||||
|
session_id=None,
|
||||||
|
offload_video_to_cpu=False,
|
||||||
|
):
|
||||||
|
"""Start a new inference session on a video directory or path."""
|
||||||
|
init_kwargs = dict(
|
||||||
|
resource_path=resource_path,
|
||||||
|
offload_video_to_cpu=offload_video_to_cpu,
|
||||||
|
)
|
||||||
|
if hasattr(self, "async_loading_frames"):
|
||||||
|
init_kwargs["async_loading_frames"] = self.async_loading_frames
|
||||||
|
if hasattr(self, "video_loader_type"):
|
||||||
|
init_kwargs["video_loader_type"] = self.video_loader_type
|
||||||
|
inference_state = self.model.init_state(**init_kwargs)
|
||||||
|
|
||||||
|
if not session_id:
|
||||||
|
session_id = str(uuid.uuid4())
|
||||||
|
self._all_inference_states[session_id] = {
|
||||||
|
"state": inference_state,
|
||||||
|
"session_id": session_id,
|
||||||
|
"start_time": time.time(),
|
||||||
|
"last_use_time": time.time(),
|
||||||
|
}
|
||||||
|
logger.info(f"started new session {session_id}")
|
||||||
|
return {"session_id": session_id}
|
||||||
|
|
||||||
|
def add_prompt(
|
||||||
|
self,
|
||||||
|
session_id: str,
|
||||||
|
frame_idx: int,
|
||||||
|
text: Optional[str] = None,
|
||||||
|
points=None,
|
||||||
|
point_labels=None,
|
||||||
|
clear_old_points: bool = True,
|
||||||
|
bounding_boxes=None,
|
||||||
|
bounding_box_labels=None,
|
||||||
|
clear_old_boxes: bool = True,
|
||||||
|
output_prob_thresh: float = 0.5,
|
||||||
|
obj_id: Optional[int] = None,
|
||||||
|
):
|
||||||
|
"""Add text, box and/or point prompt on a specific video frame."""
|
||||||
|
session = self._get_session(session_id)
|
||||||
|
inference_state = session["state"]
|
||||||
|
self._extend_expiration_time(session)
|
||||||
|
|
||||||
|
# Convert lists to tensors if needed
|
||||||
|
if points is not None and not isinstance(points, torch.Tensor):
|
||||||
|
points = torch.tensor(points, dtype=torch.float32)
|
||||||
|
if point_labels is not None and not isinstance(point_labels, torch.Tensor):
|
||||||
|
point_labels = torch.tensor(point_labels, dtype=torch.int32)
|
||||||
|
if bounding_boxes is not None and not isinstance(bounding_boxes, torch.Tensor):
|
||||||
|
bounding_boxes = torch.tensor(bounding_boxes, dtype=torch.float32)
|
||||||
|
if bounding_box_labels is not None and not isinstance(
|
||||||
|
bounding_box_labels, torch.Tensor
|
||||||
|
):
|
||||||
|
bounding_box_labels = torch.tensor(bounding_box_labels, dtype=torch.int32)
|
||||||
|
|
||||||
|
kwargs = dict(
|
||||||
|
inference_state=inference_state,
|
||||||
|
frame_idx=frame_idx,
|
||||||
|
text_str=text,
|
||||||
|
points=points,
|
||||||
|
point_labels=point_labels,
|
||||||
|
clear_old_points=clear_old_points,
|
||||||
|
boxes_xywh=bounding_boxes,
|
||||||
|
box_labels=bounding_box_labels,
|
||||||
|
clear_old_boxes=clear_old_boxes,
|
||||||
|
output_prob_thresh=output_prob_thresh,
|
||||||
|
)
|
||||||
|
if obj_id is not None:
|
||||||
|
kwargs["obj_id"] = obj_id
|
||||||
|
|
||||||
|
# Filter kwargs to only pass what the model accepts
|
||||||
|
# (SAM3 has a simpler add_prompt than SAM3.1)
|
||||||
|
import inspect
|
||||||
|
|
||||||
|
sig = inspect.signature(self.model.add_prompt)
|
||||||
|
valid_params = set(sig.parameters.keys())
|
||||||
|
filtered_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
|
||||||
|
|
||||||
|
frame_idx, outputs = self.model.add_prompt(**filtered_kwargs)
|
||||||
|
return {"frame_index": frame_idx, "outputs": outputs}
|
||||||
|
|
||||||
|
def remove_object(
|
||||||
|
self,
|
||||||
|
session_id: str,
|
||||||
|
frame_idx: int = 0,
|
||||||
|
obj_id: int = 0,
|
||||||
|
is_user_action: bool = True,
|
||||||
|
):
|
||||||
|
"""Remove an object from tracking."""
|
||||||
|
session = self._get_session(session_id)
|
||||||
|
inference_state = session["state"]
|
||||||
|
self._extend_expiration_time(session)
|
||||||
|
|
||||||
|
result = self.model.remove_object(
|
||||||
|
inference_state, obj_id, frame_idx=frame_idx, is_user_action=is_user_action
|
||||||
|
)
|
||||||
|
# Handle both return conventions
|
||||||
|
if result is None or (isinstance(result, tuple) and result[1] is None):
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
out_obj_ids = torch.zeros(0, dtype=torch.int64)
|
||||||
|
out_binary_masks = torch.zeros(
|
||||||
|
0,
|
||||||
|
inference_state["orig_height"],
|
||||||
|
inference_state["orig_width"],
|
||||||
|
dtype=torch.bool,
|
||||||
|
)
|
||||||
|
out_boxes_xywh = torch.zeros(0, 4, dtype=torch.float32)
|
||||||
|
outputs = {
|
||||||
|
"out_obj_ids": out_obj_ids.cpu().numpy(),
|
||||||
|
"out_boxes_xywh": out_boxes_xywh.cpu().numpy(),
|
||||||
|
"out_binary_masks": out_binary_masks.cpu().numpy(),
|
||||||
|
}
|
||||||
|
elif isinstance(result, tuple):
|
||||||
|
_, outputs = result
|
||||||
|
else:
|
||||||
|
outputs = result
|
||||||
|
return {"frame_index": frame_idx, "outputs": outputs}
|
||||||
|
|
||||||
|
def cancel_propagation(self, session_id):
|
||||||
|
"""Cancel any ongoing propagation. No-op if not supported by the model."""
|
||||||
|
session = self._get_session(session_id)
|
||||||
|
inference_state = session["state"]
|
||||||
|
self._extend_expiration_time(session)
|
||||||
|
if hasattr(self.model, "cancel_propagation"):
|
||||||
|
self.model.cancel_propagation(inference_state)
|
||||||
|
return {"is_success": True}
|
||||||
|
|
||||||
|
def propagate_in_video(
|
||||||
|
self,
|
||||||
|
session_id,
|
||||||
|
propagation_direction="both",
|
||||||
|
start_frame_idx=None,
|
||||||
|
max_frame_num_to_track=None,
|
||||||
|
output_prob_thresh=0.5,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
"""Propagate the added prompts to get results on all video frames."""
|
||||||
|
try:
|
||||||
|
session = self._get_session(session_id)
|
||||||
|
inference_state = session["state"]
|
||||||
|
self._extend_expiration_time(session)
|
||||||
|
if propagation_direction not in ["both", "forward", "backward"]:
|
||||||
|
raise ValueError(
|
||||||
|
f"invalid propagation direction: {propagation_direction}"
|
||||||
|
)
|
||||||
|
|
||||||
|
propagate_kwargs = dict(
|
||||||
|
inference_state=inference_state,
|
||||||
|
start_frame_idx=start_frame_idx,
|
||||||
|
max_frame_num_to_track=max_frame_num_to_track,
|
||||||
|
)
|
||||||
|
# Only pass output_prob_thresh / extra kwargs if the model supports them
|
||||||
|
import inspect
|
||||||
|
|
||||||
|
sig = inspect.signature(self.model.propagate_in_video)
|
||||||
|
if "output_prob_thresh" in sig.parameters:
|
||||||
|
propagate_kwargs["output_prob_thresh"] = output_prob_thresh
|
||||||
|
for k, v in kwargs.items():
|
||||||
|
if k in sig.parameters:
|
||||||
|
propagate_kwargs[k] = v
|
||||||
|
|
||||||
|
# Forward propagation
|
||||||
|
if propagation_direction in ["both", "forward"]:
|
||||||
|
for frame_idx, outputs in self.model.propagate_in_video(
|
||||||
|
**propagate_kwargs,
|
||||||
|
reverse=False,
|
||||||
|
):
|
||||||
|
yield {"frame_index": frame_idx, "outputs": outputs}
|
||||||
|
# Backward propagation
|
||||||
|
if propagation_direction in ["both", "backward"]:
|
||||||
|
for frame_idx, outputs in self.model.propagate_in_video(
|
||||||
|
**propagate_kwargs,
|
||||||
|
reverse=True,
|
||||||
|
):
|
||||||
|
yield {"frame_index": frame_idx, "outputs": outputs}
|
||||||
|
finally:
|
||||||
|
logger.info(f"propagation ended in session {session_id}")
|
||||||
|
|
||||||
|
def reset_session(self, session_id):
|
||||||
|
"""Reset the session to its initial state."""
|
||||||
|
session = self._get_session(session_id)
|
||||||
|
inference_state = session["state"]
|
||||||
|
self._extend_expiration_time(session)
|
||||||
|
self.model.reset_state(inference_state)
|
||||||
|
return {"is_success": True}
|
||||||
|
|
||||||
|
def close_session(self, session_id, run_gc_collect=True):
|
||||||
|
"""Close a session. Idempotent."""
|
||||||
|
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")
|
||||||
|
else:
|
||||||
|
del session
|
||||||
|
if run_gc_collect:
|
||||||
|
gc.collect()
|
||||||
|
logger.info(f"removed session {session_id}")
|
||||||
|
return {"is_success": True}
|
||||||
|
|
||||||
|
def _get_session(self, session_id):
|
||||||
|
session = self._all_inference_states.get(session_id, None)
|
||||||
|
if session is None:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Cannot find session {session_id}; it might have expired"
|
||||||
|
)
|
||||||
|
return session
|
||||||
|
|
||||||
|
def _extend_expiration_time(self, session):
|
||||||
|
"""Update last-use time for session expiration tracking."""
|
||||||
|
session["last_use_time"] = time.time()
|
||||||
|
|
||||||
|
def shutdown(self):
|
||||||
|
"""Shutdown the predictor and clear all sessions."""
|
||||||
|
self._all_inference_states.clear()
|
||||||
@@ -16,6 +16,7 @@ from sam3.train.data.collator import BatchedDatapoint
|
|||||||
|
|
||||||
from .act_ckpt_utils import activation_ckpt_wrapper
|
from .act_ckpt_utils import activation_ckpt_wrapper
|
||||||
from .box_ops import box_cxcywh_to_xyxy
|
from .box_ops import box_cxcywh_to_xyxy
|
||||||
|
from .data_misc import FindStage
|
||||||
from .geometry_encoders import Prompt
|
from .geometry_encoders import Prompt
|
||||||
from .model_misc import inverse_sigmoid
|
from .model_misc import inverse_sigmoid
|
||||||
|
|
||||||
@@ -442,6 +443,7 @@ class Sam3Image(torch.nn.Module):
|
|||||||
find_input,
|
find_input,
|
||||||
find_target,
|
find_target,
|
||||||
geometric_prompt: Prompt,
|
geometric_prompt: Prompt,
|
||||||
|
**kwargs,
|
||||||
):
|
):
|
||||||
with torch.profiler.record_function("SAM3Image._encode_prompt"):
|
with torch.profiler.record_function("SAM3Image._encode_prompt"):
|
||||||
prompt, prompt_mask, backbone_out = self._encode_prompt(
|
prompt, prompt_mask, backbone_out = self._encode_prompt(
|
||||||
@@ -474,10 +476,14 @@ class Sam3Image(torch.nn.Module):
|
|||||||
|
|
||||||
# Run segmentation heads
|
# Run segmentation heads
|
||||||
with torch.profiler.record_function("SAM3Image._run_segmentation_heads"):
|
with torch.profiler.record_function("SAM3Image._run_segmentation_heads"):
|
||||||
|
# Apply id_mapping to img_ids if backbone features were recomputed
|
||||||
|
seg_img_ids = find_input.img_ids
|
||||||
|
if "id_mapping" in backbone_out and backbone_out["id_mapping"] is not None:
|
||||||
|
seg_img_ids = backbone_out["id_mapping"][seg_img_ids]
|
||||||
self._run_segmentation_heads(
|
self._run_segmentation_heads(
|
||||||
out=out,
|
out=out,
|
||||||
backbone_out=backbone_out,
|
backbone_out=backbone_out,
|
||||||
img_ids=find_input.img_ids,
|
img_ids=seg_img_ids,
|
||||||
vis_feat_sizes=encoder_out["vis_feat_sizes"],
|
vis_feat_sizes=encoder_out["vis_feat_sizes"],
|
||||||
encoder_hidden_states=out["encoder_hidden_states"],
|
encoder_hidden_states=out["encoder_hidden_states"],
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
@@ -516,6 +522,28 @@ class Sam3Image(torch.nn.Module):
|
|||||||
|
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
def _get_geo_prompt_from_find_input(self, find_input: FindStage):
|
||||||
|
"""Construct an initial geometric prompt from the find input."""
|
||||||
|
point_embeddings, point_mask, point_labels = None, None, None
|
||||||
|
if find_input.input_points_before_embed is not None:
|
||||||
|
# Point embeddings are batch first, switch to seq first
|
||||||
|
point_embeddings = find_input.input_points_before_embed.transpose(0, 1)
|
||||||
|
|
||||||
|
# they are stored as (x,y,label), so we unpack
|
||||||
|
point_labels = point_embeddings[..., -1]
|
||||||
|
point_embeddings = point_embeddings[..., :-1]
|
||||||
|
point_mask = find_input.input_points_mask
|
||||||
|
|
||||||
|
geometric_prompt = Prompt(
|
||||||
|
box_embeddings=find_input.input_boxes_before_embed,
|
||||||
|
box_mask=find_input.input_boxes_mask,
|
||||||
|
box_labels=find_input.input_boxes_label,
|
||||||
|
point_embeddings=point_embeddings,
|
||||||
|
point_mask=point_mask,
|
||||||
|
point_labels=point_labels,
|
||||||
|
)
|
||||||
|
return geometric_prompt
|
||||||
|
|
||||||
def _get_dummy_prompt(self, num_prompts=1):
|
def _get_dummy_prompt(self, num_prompts=1):
|
||||||
device = self.device
|
device = self.device
|
||||||
geometric_prompt = Prompt(
|
geometric_prompt = Prompt(
|
||||||
@@ -656,9 +684,9 @@ class Sam3Image(torch.nn.Module):
|
|||||||
inference_state["original_heights"],
|
inference_state["original_heights"],
|
||||||
inference_state["original_widths"],
|
inference_state["original_widths"],
|
||||||
)
|
)
|
||||||
assert batch_size == len(orig_heights) == len(orig_widths), (
|
assert (
|
||||||
f"Batch size mismatch in predict_inst_batch. Got {batch_size}, {len(orig_heights)}, {len(orig_widths)}"
|
batch_size == len(orig_heights) == len(orig_widths)
|
||||||
)
|
), f"Batch size mismatch in predict_inst_batch. Got {batch_size}, {len(orig_heights)}, {len(orig_widths)}"
|
||||||
feats = [
|
feats = [
|
||||||
feat.permute(1, 2, 0).view(batch_size, -1, *feat_size)
|
feat.permute(1, 2, 0).view(batch_size, -1, *feat_size)
|
||||||
for feat, feat_size in zip(
|
for feat, feat_size in zip(
|
||||||
|
|||||||
@@ -81,9 +81,9 @@ class Sam3Processor:
|
|||||||
if not isinstance(images, list):
|
if not isinstance(images, list):
|
||||||
raise ValueError("Images must be a list of PIL images or tensors")
|
raise ValueError("Images must be a list of PIL images or tensors")
|
||||||
assert len(images) > 0, "Images list must not be empty"
|
assert len(images) > 0, "Images list must not be empty"
|
||||||
assert isinstance(images[0], PIL.Image.Image), (
|
assert isinstance(
|
||||||
"Images must be a list of PIL images"
|
images[0], PIL.Image.Image
|
||||||
)
|
), "Images must be a list of PIL images"
|
||||||
|
|
||||||
state["original_heights"] = [image.height for image in images]
|
state["original_heights"] = [image.height for image in images]
|
||||||
state["original_widths"] = [image.width for image in images]
|
state["original_widths"] = [image.width for image in images]
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,943 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from sam3.model.vl_combiner import SAM3VLBackbone
|
||||||
|
|
||||||
|
try:
|
||||||
|
from sam3.model.vl_combiner import SAM3VLBackboneTri
|
||||||
|
except ImportError:
|
||||||
|
SAM3VLBackboneTri = None
|
||||||
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from sam3.model.data_misc import BatchedDatapoint, FindStage
|
||||||
|
from sam3.model.geometry_encoders import Prompt
|
||||||
|
from sam3.model.model_misc import SAM3Output
|
||||||
|
from sam3.model.sam3_image import Sam3Image
|
||||||
|
from sam3.model.sam3_multiplex_detector_utils import nms_masks
|
||||||
|
|
||||||
|
|
||||||
|
class Sam3MultiplexImageBase(Sam3Image):
|
||||||
|
"""A wrapper class to run Sam3Image on videos for per-frame detection (no tracking)."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*args,
|
||||||
|
tracking_score_thresh: float = 0.0,
|
||||||
|
offload_outputs_to_cpu_for_eval: bool = False,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.tracking_score_thresh = tracking_score_thresh
|
||||||
|
self.offload_outputs_to_cpu_for_eval = offload_outputs_to_cpu_for_eval
|
||||||
|
self.trim_outputs_for_eval = True # dummy option -- it doesn't do anything
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
input: BatchedDatapoint,
|
||||||
|
is_inference=False, # (a dummy parameter not used anymore)
|
||||||
|
):
|
||||||
|
assert (
|
||||||
|
not self.training
|
||||||
|
), "Sam3MultiplexImageBase should only be used in eval mode."
|
||||||
|
|
||||||
|
device = self.device
|
||||||
|
backbone_out = {"img_batch_all_stages": input.img_batch}
|
||||||
|
text_outputs = self.backbone.forward_text(input.find_text_batch, device=device)
|
||||||
|
backbone_out.update(text_outputs)
|
||||||
|
num_frames = len(input.find_inputs)
|
||||||
|
|
||||||
|
previous_stages_out = SAM3Output(
|
||||||
|
iter_mode=SAM3Output.IterMode.LAST_STEP_PER_STAGE
|
||||||
|
)
|
||||||
|
for frame_idx in range(num_frames):
|
||||||
|
find_input = input.find_inputs[frame_idx]
|
||||||
|
find_target = input.find_targets[frame_idx]
|
||||||
|
geometric_prompt = self._get_geo_prompt_from_find_input(find_input)
|
||||||
|
cur_out, _ = self.forward_video_grounding(
|
||||||
|
backbone_out=backbone_out,
|
||||||
|
find_input=find_input,
|
||||||
|
find_target=find_target,
|
||||||
|
geometric_prompt=geometric_prompt,
|
||||||
|
)
|
||||||
|
# offload model outputs to CPU (to save GPU memory) for evaluation
|
||||||
|
if self.offload_outputs_to_cpu_for_eval:
|
||||||
|
cur_out = {k: v.cpu() for k, v in cur_out.items()}
|
||||||
|
|
||||||
|
previous_stages_out.append([cur_out])
|
||||||
|
|
||||||
|
get_queries = None
|
||||||
|
return previous_stages_out, get_queries
|
||||||
|
|
||||||
|
def forward_video_grounding(
|
||||||
|
self,
|
||||||
|
backbone_out,
|
||||||
|
find_input,
|
||||||
|
find_target,
|
||||||
|
geometric_prompt: Prompt,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
# route this to the image grounding forward method
|
||||||
|
out = self.forward_grounding(
|
||||||
|
backbone_out=backbone_out,
|
||||||
|
find_input=find_input,
|
||||||
|
find_target=find_target,
|
||||||
|
geometric_prompt=geometric_prompt,
|
||||||
|
)
|
||||||
|
# trim the output to only include the necessary keys
|
||||||
|
out = {
|
||||||
|
"pred_logits": out["pred_logits"],
|
||||||
|
"pred_boxes": out["pred_boxes"],
|
||||||
|
"pred_boxes_xyxy": out["pred_boxes_xyxy"],
|
||||||
|
"pred_masks": out["pred_masks"],
|
||||||
|
"pred_object_ids": self._get_dummy_object_ids(out["pred_logits"]),
|
||||||
|
}
|
||||||
|
return out, backbone_out
|
||||||
|
|
||||||
|
def _get_dummy_object_ids(self, pred_logits):
|
||||||
|
"""Generate dummy object IDs for the detected objects, based on their detection query indices."""
|
||||||
|
# Assuming pred_logits has shape [batch_size, num_queries, num_classes]
|
||||||
|
B, Q, _ = pred_logits.shape
|
||||||
|
is_above_thresh = pred_logits.squeeze(2) > self.tracking_score_thresh
|
||||||
|
dummy_obj_ids = torch.arange(Q, device=self.device).expand(B, -1)
|
||||||
|
dummy_obj_ids = torch.where(is_above_thresh, dummy_obj_ids, -1)
|
||||||
|
return dummy_obj_ids
|
||||||
|
|
||||||
|
def _trim_outputs(self, *args, **kwargs):
|
||||||
|
pass # not needed for image-on-video
|
||||||
|
|
||||||
|
def _batch_find_inputs(
|
||||||
|
self,
|
||||||
|
find_inputs: List[FindStage],
|
||||||
|
chunk_start: int,
|
||||||
|
chunk_end: int,
|
||||||
|
) -> FindStage:
|
||||||
|
"""
|
||||||
|
Batch multiple FindStage objects into a single batched FindStage.
|
||||||
|
|
||||||
|
For each frame in the chunk, creates img_ids that point to the correct
|
||||||
|
frame index. When processing streaming video, the img_ids are the actual
|
||||||
|
frame indices (e.g., [0, 1, 2, ..., 15] for chunk 0-16), and the modulo
|
||||||
|
for circular buffer access is applied later in _get_img_feats.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
find_inputs: List of FindStage objects for all frames.
|
||||||
|
chunk_start: Start index of the chunk.
|
||||||
|
chunk_end: End index of the chunk (exclusive).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A single FindStage with batched tensors.
|
||||||
|
"""
|
||||||
|
chunk_find_inputs = [
|
||||||
|
find_inputs[i % len(find_inputs)] for i in range(chunk_start, chunk_end)
|
||||||
|
]
|
||||||
|
|
||||||
|
# Generate img_ids based on chunk frame indices
|
||||||
|
# Each frame in the chunk gets its corresponding frame index
|
||||||
|
# The modulo for circular buffer access is handled in _get_img_feats
|
||||||
|
device = chunk_find_inputs[0].img_ids.device
|
||||||
|
dtype = chunk_find_inputs[0].img_ids.dtype
|
||||||
|
img_ids_list = [
|
||||||
|
torch.tensor([i], device=device, dtype=dtype)
|
||||||
|
for i in range(chunk_start, chunk_end)
|
||||||
|
]
|
||||||
|
batched_img_ids = torch.cat(img_ids_list, dim=0)
|
||||||
|
|
||||||
|
# Generate img_ids_np to match
|
||||||
|
img_ids_np_list = [np.array([i]) for i in range(chunk_start, chunk_end)]
|
||||||
|
batched_img_ids_np = np.concatenate(img_ids_np_list, axis=0)
|
||||||
|
|
||||||
|
# Concatenate text_ids
|
||||||
|
text_ids_list = [fi.text_ids for fi in chunk_find_inputs]
|
||||||
|
batched_text_ids = torch.cat(text_ids_list, dim=0)
|
||||||
|
|
||||||
|
# Concatenate input_boxes
|
||||||
|
input_boxes_list = [fi.input_boxes for fi in chunk_find_inputs]
|
||||||
|
batched_input_boxes = (
|
||||||
|
torch.cat(input_boxes_list, dim=0)
|
||||||
|
if input_boxes_list[0] is not None
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
# Concatenate input_boxes_mask
|
||||||
|
input_boxes_mask_list = [fi.input_boxes_mask for fi in chunk_find_inputs]
|
||||||
|
batched_input_boxes_mask = (
|
||||||
|
torch.cat(input_boxes_mask_list, dim=0)
|
||||||
|
if input_boxes_mask_list[0] is not None
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
# Concatenate input_boxes_label
|
||||||
|
input_boxes_label_list = [fi.input_boxes_label for fi in chunk_find_inputs]
|
||||||
|
batched_input_boxes_label = (
|
||||||
|
torch.cat(input_boxes_label_list, dim=0)
|
||||||
|
if input_boxes_label_list[0] is not None
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
# Concatenate input_points
|
||||||
|
input_points_list = [fi.input_points for fi in chunk_find_inputs]
|
||||||
|
batched_input_points = (
|
||||||
|
torch.cat(input_points_list, dim=0)
|
||||||
|
if input_points_list[0] is not None
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
# Concatenate input_points_mask
|
||||||
|
input_points_mask_list = [fi.input_points_mask for fi in chunk_find_inputs]
|
||||||
|
batched_input_points_mask = (
|
||||||
|
torch.cat(input_points_mask_list, dim=0)
|
||||||
|
if input_points_mask_list[0] is not None
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
# Handle optional fields
|
||||||
|
input_boxes_before_embed_list = [
|
||||||
|
fi.input_boxes_before_embed for fi in chunk_find_inputs
|
||||||
|
]
|
||||||
|
batched_input_boxes_before_embed = (
|
||||||
|
torch.cat(input_boxes_before_embed_list, dim=0)
|
||||||
|
if input_boxes_before_embed_list[0] is not None
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
input_points_before_embed_list = [
|
||||||
|
fi.input_points_before_embed for fi in chunk_find_inputs
|
||||||
|
]
|
||||||
|
batched_input_points_before_embed = (
|
||||||
|
torch.cat(input_points_before_embed_list, dim=0)
|
||||||
|
if input_points_before_embed_list[0] is not None
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create batched FindStage
|
||||||
|
batched_find_input = FindStage(
|
||||||
|
img_ids=batched_img_ids,
|
||||||
|
img_ids_np=batched_img_ids_np,
|
||||||
|
text_ids=batched_text_ids,
|
||||||
|
input_boxes=batched_input_boxes,
|
||||||
|
input_boxes_mask=batched_input_boxes_mask,
|
||||||
|
input_boxes_label=batched_input_boxes_label,
|
||||||
|
input_points=batched_input_points,
|
||||||
|
input_points_mask=batched_input_points_mask,
|
||||||
|
ptrs=None, # Not batching pointers for now
|
||||||
|
ptrs_seg=None,
|
||||||
|
object_ids=None,
|
||||||
|
input_boxes_before_embed=batched_input_boxes_before_embed,
|
||||||
|
input_points_before_embed=batched_input_points_before_embed,
|
||||||
|
)
|
||||||
|
|
||||||
|
return batched_find_input
|
||||||
|
|
||||||
|
def _batch_geometric_prompts(
|
||||||
|
self,
|
||||||
|
geometric_prompts: List[Prompt],
|
||||||
|
chunk_start: int,
|
||||||
|
chunk_end: int,
|
||||||
|
) -> Prompt:
|
||||||
|
"""
|
||||||
|
Batch multiple Prompt objects into a single batched Prompt.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
geometric_prompts: List of Prompt objects for all frames.
|
||||||
|
chunk_start: Start index of the chunk.
|
||||||
|
chunk_end: End index of the chunk (exclusive).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A single Prompt with batched tensors.
|
||||||
|
"""
|
||||||
|
chunk_prompts = [geometric_prompts[i] for i in range(chunk_start, chunk_end)]
|
||||||
|
return self._batch_geometric_prompts_from_list(chunk_prompts)
|
||||||
|
|
||||||
|
def _batch_geometric_prompts_from_list(
|
||||||
|
self,
|
||||||
|
chunk_prompts: List[Prompt],
|
||||||
|
) -> Prompt:
|
||||||
|
"""
|
||||||
|
Batch a list of Prompt objects into a single batched Prompt.
|
||||||
|
|
||||||
|
Prompt uses seq-first, batch-second convention:
|
||||||
|
- box_embeddings: N_boxes x B x C_box - batch along dim 1
|
||||||
|
- box_mask: B x N_boxes - batch along dim 0
|
||||||
|
- box_labels: N_boxes x B - batch along dim 1
|
||||||
|
- point_embeddings: N_points x B x C_point - batch along dim 1
|
||||||
|
- point_mask: B x N_points - batch along dim 0
|
||||||
|
- point_labels: N_points x B - batch along dim 1
|
||||||
|
|
||||||
|
Args:
|
||||||
|
chunk_prompts: List of Prompt objects to batch.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A single Prompt with batched tensors.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Helper function to batch tensors along specified dimension
|
||||||
|
def batch_tensors(tensors, dim):
|
||||||
|
if tensors[0] is None:
|
||||||
|
return None
|
||||||
|
return torch.cat(tensors, dim=dim)
|
||||||
|
|
||||||
|
# Batch box embeddings (N_boxes x B x C_box - batch along dim 1)
|
||||||
|
box_embeddings_list = [p.box_embeddings for p in chunk_prompts]
|
||||||
|
batched_box_embeddings = batch_tensors(box_embeddings_list, dim=1)
|
||||||
|
|
||||||
|
# Batch box mask (B x N_boxes - batch along dim 0)
|
||||||
|
box_mask_list = [p.box_mask for p in chunk_prompts]
|
||||||
|
batched_box_mask = batch_tensors(box_mask_list, dim=0)
|
||||||
|
|
||||||
|
# Batch box labels (N_boxes x B - batch along dim 1)
|
||||||
|
box_labels_list = [p.box_labels for p in chunk_prompts]
|
||||||
|
batched_box_labels = batch_tensors(box_labels_list, dim=1)
|
||||||
|
|
||||||
|
# Batch point embeddings (N_points x B x C_point - batch along dim 1)
|
||||||
|
point_embeddings_list = [p.point_embeddings for p in chunk_prompts]
|
||||||
|
batched_point_embeddings = batch_tensors(point_embeddings_list, dim=1)
|
||||||
|
|
||||||
|
# Batch point mask (B x N_points - batch along dim 0)
|
||||||
|
point_mask_list = [p.point_mask for p in chunk_prompts]
|
||||||
|
batched_point_mask = batch_tensors(point_mask_list, dim=0)
|
||||||
|
|
||||||
|
# Batch point labels (N_points x B - batch along dim 1)
|
||||||
|
point_labels_list = [p.point_labels for p in chunk_prompts]
|
||||||
|
batched_point_labels = batch_tensors(point_labels_list, dim=1)
|
||||||
|
|
||||||
|
# Create batched Prompt
|
||||||
|
batched_prompt = Prompt(
|
||||||
|
box_embeddings=batched_box_embeddings,
|
||||||
|
box_mask=batched_box_mask,
|
||||||
|
box_labels=batched_box_labels,
|
||||||
|
point_embeddings=batched_point_embeddings,
|
||||||
|
point_mask=batched_point_mask,
|
||||||
|
point_labels=batched_point_labels,
|
||||||
|
)
|
||||||
|
|
||||||
|
return batched_prompt
|
||||||
|
|
||||||
|
|
||||||
|
class Sam3MultiplexDetector(Sam3MultiplexImageBase):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*args,
|
||||||
|
async_all_gather=True,
|
||||||
|
gather_backbone_out=None,
|
||||||
|
is_multiplex=False,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.rank = int(os.getenv("RANK", "0"))
|
||||||
|
self.world_size = int(os.getenv("WORLD_SIZE", "1"))
|
||||||
|
self.async_all_gather = async_all_gather
|
||||||
|
|
||||||
|
# if gather_backbone is not set, default to gathering only for `SAM3VLBackbone`
|
||||||
|
if gather_backbone_out is None:
|
||||||
|
gather_backbone_out = isinstance(self.backbone, SAM3VLBackbone) or (
|
||||||
|
SAM3VLBackboneTri is not None
|
||||||
|
and isinstance(self.backbone, SAM3VLBackboneTri)
|
||||||
|
)
|
||||||
|
self.gather_backbone_out = gather_backbone_out
|
||||||
|
self.is_multiplex = is_multiplex
|
||||||
|
|
||||||
|
def forward_video_grounding_multigpu(
|
||||||
|
self,
|
||||||
|
backbone_out,
|
||||||
|
find_inputs,
|
||||||
|
geometric_prompt: Prompt,
|
||||||
|
frame_idx,
|
||||||
|
num_frames,
|
||||||
|
# `multigpu_buffer` is a dict to cache FA outputs in a chunk between different calls
|
||||||
|
multigpu_buffer,
|
||||||
|
track_in_reverse=False,
|
||||||
|
# whether to also return the SAM2 backbone features (in addition to FA results)
|
||||||
|
return_sam2_backbone_feats=False,
|
||||||
|
# whether to perform NMS and suppress the scores of those detections removed by NMS
|
||||||
|
run_nms=False,
|
||||||
|
nms_prob_thresh=None,
|
||||||
|
nms_iou_thresh=None,
|
||||||
|
nms_use_iom=False,
|
||||||
|
# tracking bounds to respect max_frame_num_to_track
|
||||||
|
max_frame_num_to_track=None,
|
||||||
|
propagate_in_video_start_frame_idx=None,
|
||||||
|
# feature_cache for buffered backbone computation
|
||||||
|
feature_cache=None,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Compute the FA detection outputs in a distributed manner, where all GPUs process
|
||||||
|
a chunk of frames (equal to the number of GPUs) at once and store them in cache.
|
||||||
|
"""
|
||||||
|
# Calculate valid frame range based on max_frame_num_to_track
|
||||||
|
# We prevent pre-fetching beyond the tracking window relative to current frame
|
||||||
|
if max_frame_num_to_track is not None:
|
||||||
|
if propagate_in_video_start_frame_idx is None:
|
||||||
|
propagate_in_video_start_frame_idx = 0
|
||||||
|
if track_in_reverse:
|
||||||
|
# When going backwards, limit how far back we can go from current frame
|
||||||
|
valid_frame_start = max(
|
||||||
|
0,
|
||||||
|
propagate_in_video_start_frame_idx - max_frame_num_to_track + 1,
|
||||||
|
)
|
||||||
|
valid_frame_end = num_frames
|
||||||
|
else:
|
||||||
|
# When going forwards, limit how far ahead we can go from current frame
|
||||||
|
valid_frame_start = 0
|
||||||
|
valid_frame_end = min(
|
||||||
|
num_frames,
|
||||||
|
propagate_in_video_start_frame_idx + max_frame_num_to_track,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# No tracking limit specified, use full video range
|
||||||
|
valid_frame_start = 0
|
||||||
|
valid_frame_end = num_frames
|
||||||
|
|
||||||
|
# Step 1: fetch the FA outputs in the current chunk from buffer
|
||||||
|
frame_idx_curr_b = frame_idx - frame_idx % self.world_size
|
||||||
|
frame_idx_curr_e = min(frame_idx_curr_b + self.world_size, num_frames)
|
||||||
|
|
||||||
|
# Clamp the current chunk to the valid tracking range
|
||||||
|
frame_idx_curr_b = max(frame_idx_curr_b, valid_frame_start)
|
||||||
|
frame_idx_curr_e = min(frame_idx_curr_e, valid_frame_end)
|
||||||
|
# in case the current frame's FA results are not in the buffer yet, build the current chunk
|
||||||
|
# (this should only happen on the first chunk, since we are also building the next chunk below)
|
||||||
|
if frame_idx not in multigpu_buffer:
|
||||||
|
with torch.profiler.record_function("build_multigpu_buffer_next_chunk1"):
|
||||||
|
self._build_multigpu_buffer_next_chunk(
|
||||||
|
backbone_out=backbone_out,
|
||||||
|
find_inputs=find_inputs,
|
||||||
|
geometric_prompt=geometric_prompt,
|
||||||
|
frame_idx_begin=frame_idx_curr_b,
|
||||||
|
frame_idx_end=frame_idx_curr_e,
|
||||||
|
num_frames=num_frames,
|
||||||
|
multigpu_buffer=multigpu_buffer,
|
||||||
|
run_nms=run_nms,
|
||||||
|
nms_prob_thresh=nms_prob_thresh,
|
||||||
|
nms_iou_thresh=nms_iou_thresh,
|
||||||
|
nms_use_iom=nms_use_iom,
|
||||||
|
feature_cache=feature_cache,
|
||||||
|
)
|
||||||
|
|
||||||
|
# read out the current frame's results from `multigpu_buffer`
|
||||||
|
out = {}
|
||||||
|
for k, (v, handle) in multigpu_buffer[frame_idx].items():
|
||||||
|
if self.is_multiplex:
|
||||||
|
if (
|
||||||
|
k.startswith("interactive_backbone_")
|
||||||
|
or k.startswith("propagation_backbone_")
|
||||||
|
) and not return_sam2_backbone_feats:
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
if k.startswith("sam2_backbone_") and not return_sam2_backbone_feats:
|
||||||
|
continue
|
||||||
|
if handle is not None:
|
||||||
|
handle.wait() # wait for async all-gather to finish
|
||||||
|
out[k] = v
|
||||||
|
|
||||||
|
# Step 2: remove FA outputs of the previous chunk from cache to save GPU memory
|
||||||
|
if not track_in_reverse and frame_idx_curr_b - self.world_size >= 0:
|
||||||
|
frame_idx_prev_e = frame_idx_curr_b
|
||||||
|
frame_idx_prev_b = frame_idx_curr_b - self.world_size
|
||||||
|
elif track_in_reverse and frame_idx_curr_e < num_frames:
|
||||||
|
frame_idx_prev_b = frame_idx_curr_e
|
||||||
|
frame_idx_prev_e = min(frame_idx_prev_b + self.world_size, num_frames)
|
||||||
|
else:
|
||||||
|
frame_idx_prev_b = frame_idx_prev_e = None
|
||||||
|
if frame_idx_prev_b is not None:
|
||||||
|
for frame_idx_rm in range(frame_idx_prev_b, frame_idx_prev_e):
|
||||||
|
multigpu_buffer.pop(frame_idx_rm, None)
|
||||||
|
|
||||||
|
# Step 3: compute and cache FA outputs of the next chunk ahead of time
|
||||||
|
# (so that we can overlap computation with all-gather transfer)
|
||||||
|
# Respect tracking bounds when calculating next chunk
|
||||||
|
|
||||||
|
if not track_in_reverse and frame_idx_curr_e < valid_frame_end:
|
||||||
|
frame_idx_next_b = frame_idx_curr_e
|
||||||
|
frame_idx_next_e = min(frame_idx_next_b + self.world_size, valid_frame_end)
|
||||||
|
elif (
|
||||||
|
track_in_reverse and frame_idx_curr_b - self.world_size >= valid_frame_start
|
||||||
|
):
|
||||||
|
frame_idx_next_e = frame_idx_curr_b
|
||||||
|
frame_idx_next_b = max(
|
||||||
|
frame_idx_curr_b - self.world_size, valid_frame_start
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
frame_idx_next_b = frame_idx_next_e = None
|
||||||
|
if frame_idx_next_b is not None and frame_idx_next_b not in multigpu_buffer:
|
||||||
|
with torch.profiler.record_function("build_multigpu_buffer_next_chunk2"):
|
||||||
|
self._build_multigpu_buffer_next_chunk(
|
||||||
|
backbone_out=backbone_out,
|
||||||
|
find_inputs=find_inputs,
|
||||||
|
geometric_prompt=geometric_prompt,
|
||||||
|
frame_idx_begin=frame_idx_next_b,
|
||||||
|
frame_idx_end=frame_idx_next_e,
|
||||||
|
num_frames=num_frames,
|
||||||
|
multigpu_buffer=multigpu_buffer,
|
||||||
|
run_nms=run_nms,
|
||||||
|
nms_prob_thresh=nms_prob_thresh,
|
||||||
|
nms_iou_thresh=nms_iou_thresh,
|
||||||
|
feature_cache=feature_cache,
|
||||||
|
)
|
||||||
|
|
||||||
|
return out, backbone_out
|
||||||
|
|
||||||
|
def _build_multigpu_buffer_next_chunk(
|
||||||
|
self,
|
||||||
|
backbone_out,
|
||||||
|
find_inputs,
|
||||||
|
geometric_prompt: Prompt,
|
||||||
|
frame_idx_begin,
|
||||||
|
frame_idx_end,
|
||||||
|
num_frames,
|
||||||
|
multigpu_buffer,
|
||||||
|
run_nms=False,
|
||||||
|
nms_prob_thresh=None,
|
||||||
|
nms_iou_thresh=None,
|
||||||
|
nms_use_iom=False,
|
||||||
|
feature_cache=None,
|
||||||
|
):
|
||||||
|
"""Compute FA outputs on a chunk of frames and store their results in multigpu_buffer."""
|
||||||
|
# each GPU computes FA on one frame in the chunk (in a round-robin manner)
|
||||||
|
frame_idx_local_gpu = min(frame_idx_begin + self.rank, frame_idx_end - 1)
|
||||||
|
# `forward_grounding` (from base class `Sam3MultiplexImageBase`) runs FA on a single frame
|
||||||
|
with torch.profiler.record_function("forward_grounding"):
|
||||||
|
out_local = self.forward_grounding(
|
||||||
|
backbone_out=backbone_out,
|
||||||
|
# HACK: Since find_inputs is on GPU having to realloc is expensive so changing the values in place for the prod usecase
|
||||||
|
# i.e. when using the streaming frame loader resource instead of local file. For non-prod is always
|
||||||
|
# frame_idx_local_gpu < len(find_inputs) so should be a no-op
|
||||||
|
find_input=find_inputs[frame_idx_local_gpu % len(find_inputs)],
|
||||||
|
find_target=None,
|
||||||
|
geometric_prompt=geometric_prompt,
|
||||||
|
feature_cache=feature_cache,
|
||||||
|
)
|
||||||
|
if run_nms:
|
||||||
|
with torch.profiler.record_function("nms_masks"):
|
||||||
|
# run NMS as a post-processing step on top of the detection outputs
|
||||||
|
assert nms_prob_thresh is not None and nms_iou_thresh is not None
|
||||||
|
pred_probs = out_local["pred_logits"].squeeze(-1).sigmoid()
|
||||||
|
pred_masks = out_local["pred_masks"]
|
||||||
|
# loop over text prompts (not an overhead for demo where there's only 1 prompt)
|
||||||
|
for prompt_idx in range(pred_probs.size(0)):
|
||||||
|
keep = nms_masks(
|
||||||
|
pred_probs=pred_probs[prompt_idx],
|
||||||
|
pred_masks=pred_masks[prompt_idx],
|
||||||
|
prob_threshold=nms_prob_thresh,
|
||||||
|
iou_threshold=nms_iou_thresh,
|
||||||
|
nms_use_iom=nms_use_iom,
|
||||||
|
do_compile=getattr(self, "compile_model", False),
|
||||||
|
running_in_prod=getattr(self, "running_in_prod", False),
|
||||||
|
)
|
||||||
|
# set a very low threshold for those detections removed by NMS
|
||||||
|
out_local["pred_logits"][prompt_idx, :, 0] -= 1e4 * (~keep).float()
|
||||||
|
|
||||||
|
if self.gather_backbone_out:
|
||||||
|
# gather the SAM 2 backbone features across GPUs
|
||||||
|
if self.is_multiplex:
|
||||||
|
# Note that we should not need to compute the interaction features every frame
|
||||||
|
# TODO: rooms for optimization
|
||||||
|
|
||||||
|
# Interaction features
|
||||||
|
inte_feats = out_local["prev_encoder_out"]["backbone_out"][
|
||||||
|
"interactive"
|
||||||
|
]
|
||||||
|
assert inte_feats["vision_mask"] is None
|
||||||
|
assert (
|
||||||
|
len(inte_feats["backbone_fpn"]) == 3
|
||||||
|
) # SAM2 backbone always have 3 levels
|
||||||
|
assert all(x.mask is None for x in inte_feats["backbone_fpn"])
|
||||||
|
# cast the SAM2 backbone features to bfloat16 for all-gather (this is usually
|
||||||
|
# a no-op, SAM2 backbone features are likely already in bfloat16 due to AMP)
|
||||||
|
inte_backbone_fpn_bf16 = [
|
||||||
|
x.to(torch.bfloat16) for x in inte_feats["backbone_fpn"]
|
||||||
|
]
|
||||||
|
inte_fpn0, inte_fpn_handle0 = self._gather_tensor(
|
||||||
|
inte_backbone_fpn_bf16[0].tensors
|
||||||
|
)
|
||||||
|
inte_fpn1, inte_fpn_handle1 = self._gather_tensor(
|
||||||
|
inte_backbone_fpn_bf16[1].tensors
|
||||||
|
)
|
||||||
|
inte_fpn2, inte_fpn_handle2 = self._gather_tensor(
|
||||||
|
inte_backbone_fpn_bf16[2].tensors
|
||||||
|
)
|
||||||
|
# vision_pos_enc is the same on all frames, so no need to all-gather them
|
||||||
|
inte_vision_pos_enc = inte_feats["vision_pos_enc"]
|
||||||
|
|
||||||
|
feats = out_local["prev_encoder_out"]["backbone_out"]["sam2_backbone_out"]
|
||||||
|
assert feats["vision_mask"] is None
|
||||||
|
assert len(feats["backbone_fpn"]) == 3 # SAM2 backbone always have 3 levels
|
||||||
|
assert all(x.mask is None for x in feats["backbone_fpn"])
|
||||||
|
# cast the SAM2 backbone features to bfloat16 for all-gather (this is usually
|
||||||
|
# a no-op, SAM2 backbone features are likely already in bfloat16 due to AMP)
|
||||||
|
backbone_fpn_bf16 = [x.to(torch.bfloat16) for x in feats["backbone_fpn"]]
|
||||||
|
fpn0, fpn_handle0 = self._gather_tensor(backbone_fpn_bf16[0].tensors)
|
||||||
|
fpn1, fpn_handle1 = self._gather_tensor(backbone_fpn_bf16[1].tensors)
|
||||||
|
fpn2, fpn_handle2 = self._gather_tensor(backbone_fpn_bf16[2].tensors)
|
||||||
|
# vision_pos_enc is the same on all frames, so no need to all-gather them
|
||||||
|
vision_pos_enc = feats["vision_pos_enc"]
|
||||||
|
|
||||||
|
# trim the FA output to only include the necessary keys
|
||||||
|
out_local = {
|
||||||
|
"pred_logits": out_local["pred_logits"],
|
||||||
|
"pred_boxes": out_local["pred_boxes"],
|
||||||
|
"pred_boxes_xyxy": out_local["pred_boxes_xyxy"],
|
||||||
|
"pred_masks": out_local["pred_masks"],
|
||||||
|
"pred_object_ids": self._get_dummy_object_ids(out_local["pred_logits"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
# gather the results: after this step, each GPU will receive FA outputs on
|
||||||
|
# all frames in the chunk and store them in `multigpu_buffer`
|
||||||
|
out_gathered = {k: self._gather_tensor(v) for k, v in out_local.items()}
|
||||||
|
for rank in range(self.world_size):
|
||||||
|
frame_idx_to_save = frame_idx_begin + rank
|
||||||
|
if frame_idx_to_save >= num_frames:
|
||||||
|
continue
|
||||||
|
frame_buffer = {
|
||||||
|
k: (v[rank], handle) for k, (v, handle) in out_gathered.items()
|
||||||
|
}
|
||||||
|
if self.gather_backbone_out:
|
||||||
|
# also add gathered SAM 2 backbone features to frame_buffer
|
||||||
|
if self.is_multiplex:
|
||||||
|
frame_buffer["interactive_backbone_fpn_0"] = (
|
||||||
|
inte_fpn0[rank],
|
||||||
|
inte_fpn_handle0,
|
||||||
|
)
|
||||||
|
frame_buffer["interactive_backbone_fpn_1"] = (
|
||||||
|
inte_fpn1[rank],
|
||||||
|
inte_fpn_handle1,
|
||||||
|
)
|
||||||
|
frame_buffer["interactive_backbone_fpn_2"] = (
|
||||||
|
inte_fpn2[rank],
|
||||||
|
inte_fpn_handle2,
|
||||||
|
)
|
||||||
|
frame_buffer["interactive_backbone_pos_enc"] = (
|
||||||
|
inte_vision_pos_enc,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
frame_buffer["sam2_backbone_fpn_0"] = (fpn0[rank], fpn_handle0)
|
||||||
|
frame_buffer["sam2_backbone_fpn_1"] = (fpn1[rank], fpn_handle1)
|
||||||
|
frame_buffer["sam2_backbone_fpn_2"] = (fpn2[rank], fpn_handle2)
|
||||||
|
frame_buffer["sam2_backbone_pos_enc"] = (vision_pos_enc, None)
|
||||||
|
|
||||||
|
multigpu_buffer[frame_idx_to_save] = frame_buffer
|
||||||
|
|
||||||
|
def _gather_tensor(self, x):
|
||||||
|
if self.world_size == 1:
|
||||||
|
return [x], None
|
||||||
|
|
||||||
|
async_op = self.async_all_gather
|
||||||
|
# here `.contiguous()` is required -- otherwise NCCL all_gather
|
||||||
|
# sometimes gives wrong results (based on Ronghang's observations)
|
||||||
|
x = x.contiguous() # ensure contiguous memory for NCCL
|
||||||
|
output_list = [torch.empty_like(x) for _ in range(self.world_size)]
|
||||||
|
handle = torch.distributed.all_gather(output_list, x, async_op=async_op)
|
||||||
|
return output_list, handle
|
||||||
|
|
||||||
|
def forward_video_grounding_batched_multigpu(
|
||||||
|
self,
|
||||||
|
backbone_out,
|
||||||
|
find_inputs,
|
||||||
|
geometric_prompt: Prompt,
|
||||||
|
frame_idx,
|
||||||
|
num_frames,
|
||||||
|
# `grounding_cache` is a dict to cache FA outputs in a chunk between different calls
|
||||||
|
grounding_cache,
|
||||||
|
track_in_reverse=False,
|
||||||
|
# whether to also return the SAM2 backbone features (in addition to FA results)
|
||||||
|
return_sam2_backbone_feats=False,
|
||||||
|
# whether to perform NMS and suppress the scores of those detections removed by NMS
|
||||||
|
run_nms=False,
|
||||||
|
nms_prob_thresh=None,
|
||||||
|
nms_iou_thresh=None,
|
||||||
|
nms_use_iom=False,
|
||||||
|
# tracking bounds to respect max_frame_num_to_track
|
||||||
|
max_frame_num_to_track=None,
|
||||||
|
propagate_in_video_start_frame_idx=None,
|
||||||
|
# feature_cache for buffered backbone computation
|
||||||
|
feature_cache=None,
|
||||||
|
# batch_size for batched forward_grounding (default: 16)
|
||||||
|
batch_size=16,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Fully batched forward_grounding that processes chunks of frames together on each GPU.
|
||||||
|
|
||||||
|
Unlike forward_video_grounding_multigpu which processes 1 frame per GPU per chunk,
|
||||||
|
this method processes `batch_size` frames at once using the batched forward_grounding
|
||||||
|
approach from Sam3MultiplexImageBase.
|
||||||
|
|
||||||
|
For single-GPU (world_size=1), this is equivalent to forward_grounding_batched.
|
||||||
|
For multi-GPU, each GPU processes batch_size frames in parallel.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
backbone_out: Dictionary containing backbone outputs and image batch.
|
||||||
|
find_inputs: List of FindStage objects for all frames.
|
||||||
|
geometric_prompt: Prompt object (used as template, individual prompts are
|
||||||
|
constructed from find_inputs for batching).
|
||||||
|
frame_idx: Current frame index to process.
|
||||||
|
num_frames: Total number of frames in the video.
|
||||||
|
grounding_cache: Dictionary to cache grounding outputs.
|
||||||
|
track_in_reverse: If True, processing in reverse frame order.
|
||||||
|
return_sam2_backbone_feats: Whether to also return SAM2 backbone features.
|
||||||
|
run_nms: Whether to perform NMS on detection outputs.
|
||||||
|
nms_prob_thresh: Probability threshold for NMS.
|
||||||
|
nms_iou_thresh: IoU threshold for NMS.
|
||||||
|
nms_use_iom: Whether to use IoM for NMS.
|
||||||
|
max_frame_num_to_track: Maximum number of frames to track.
|
||||||
|
propagate_in_video_start_frame_idx: Start frame index for propagation.
|
||||||
|
feature_cache: Optional dictionary for backbone feature caching.
|
||||||
|
batch_size: Number of frames to batch together per GPU (default: 16).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (out, backbone_out) where out contains detection results for frame_idx.
|
||||||
|
"""
|
||||||
|
# Calculate valid frame range based on max_frame_num_to_track
|
||||||
|
if max_frame_num_to_track is not None:
|
||||||
|
if propagate_in_video_start_frame_idx is None:
|
||||||
|
propagate_in_video_start_frame_idx = 0
|
||||||
|
if track_in_reverse:
|
||||||
|
valid_frame_start = (
|
||||||
|
propagate_in_video_start_frame_idx - max_frame_num_to_track + 1
|
||||||
|
)
|
||||||
|
valid_frame_end = propagate_in_video_start_frame_idx
|
||||||
|
else:
|
||||||
|
valid_frame_start = propagate_in_video_start_frame_idx
|
||||||
|
valid_frame_end = (
|
||||||
|
propagate_in_video_start_frame_idx + max_frame_num_to_track
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
valid_frame_start = 0
|
||||||
|
valid_frame_end = num_frames
|
||||||
|
|
||||||
|
# Initialize grounding_buffer if not present
|
||||||
|
if "grounding_buffer" not in grounding_cache:
|
||||||
|
grounding_cache["grounding_buffer"] = {}
|
||||||
|
|
||||||
|
# Calculate chunk boundaries - use batch_size instead of world_size
|
||||||
|
chunk_start = (frame_idx // batch_size) * batch_size
|
||||||
|
chunk_end = min(chunk_start + batch_size, valid_frame_end)
|
||||||
|
chunk_key = (chunk_start, chunk_end)
|
||||||
|
|
||||||
|
# Process chunk if not already cached
|
||||||
|
if chunk_key not in grounding_cache["grounding_buffer"]:
|
||||||
|
with torch.profiler.record_function(
|
||||||
|
"forward_grounding_batched.process_chunk"
|
||||||
|
):
|
||||||
|
chunk_outputs = self._process_grounding_chunk_batched(
|
||||||
|
backbone_out=backbone_out,
|
||||||
|
find_inputs=find_inputs,
|
||||||
|
chunk_start=chunk_start,
|
||||||
|
chunk_end=chunk_end,
|
||||||
|
run_nms=run_nms,
|
||||||
|
nms_prob_thresh=nms_prob_thresh,
|
||||||
|
nms_iou_thresh=nms_iou_thresh,
|
||||||
|
nms_use_iom=nms_use_iom,
|
||||||
|
feature_cache=feature_cache,
|
||||||
|
return_sam2_backbone_feats=return_sam2_backbone_feats,
|
||||||
|
)
|
||||||
|
grounding_cache["grounding_buffer"][chunk_key] = chunk_outputs
|
||||||
|
|
||||||
|
# Auto-cleanup previous chunks
|
||||||
|
self._cleanup_previous_chunks_multigpu(
|
||||||
|
grounding_cache=grounding_cache,
|
||||||
|
current_chunk_key=chunk_key,
|
||||||
|
batch_size=batch_size,
|
||||||
|
num_frames=num_frames,
|
||||||
|
track_in_reverse=track_in_reverse,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Retrieve the cached output for this frame
|
||||||
|
chunk_outputs = grounding_cache["grounding_buffer"][chunk_key]
|
||||||
|
local_idx = frame_idx - chunk_start
|
||||||
|
|
||||||
|
# Slice out the output for this specific frame
|
||||||
|
out = self._slice_batched_output(
|
||||||
|
chunk_outputs, local_idx, return_sam2_backbone_feats
|
||||||
|
)
|
||||||
|
|
||||||
|
return out, backbone_out
|
||||||
|
|
||||||
|
def _process_grounding_chunk_batched(
|
||||||
|
self,
|
||||||
|
backbone_out,
|
||||||
|
find_inputs,
|
||||||
|
chunk_start: int,
|
||||||
|
chunk_end: int,
|
||||||
|
run_nms: bool,
|
||||||
|
nms_prob_thresh,
|
||||||
|
nms_iou_thresh,
|
||||||
|
nms_use_iom: bool,
|
||||||
|
feature_cache,
|
||||||
|
return_sam2_backbone_feats: bool,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Process a chunk of frames through the full forward_grounding pipeline in batch.
|
||||||
|
"""
|
||||||
|
chunk_size = chunk_end - chunk_start
|
||||||
|
|
||||||
|
# Build geometric prompts for the chunk
|
||||||
|
chunk_geo_prompts = [
|
||||||
|
self._get_geo_prompt_from_find_input(find_inputs[i % len(find_inputs)])
|
||||||
|
for i in range(chunk_start, chunk_end)
|
||||||
|
]
|
||||||
|
|
||||||
|
# Batch the find_inputs for this chunk
|
||||||
|
batched_find_input = self._batch_find_inputs(
|
||||||
|
find_inputs, chunk_start, chunk_end
|
||||||
|
)
|
||||||
|
|
||||||
|
# Batch the geometric prompts
|
||||||
|
batched_geometric_prompt = self._batch_geometric_prompts_from_list(
|
||||||
|
chunk_geo_prompts
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run forward_grounding on the batched input
|
||||||
|
with torch.profiler.record_function("forward_grounding_batched.forward"):
|
||||||
|
out = self.forward_grounding(
|
||||||
|
backbone_out=backbone_out,
|
||||||
|
find_input=batched_find_input,
|
||||||
|
find_target=None,
|
||||||
|
geometric_prompt=batched_geometric_prompt,
|
||||||
|
feature_cache=feature_cache,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Apply NMS per frame in the batch
|
||||||
|
if run_nms:
|
||||||
|
with torch.profiler.record_function("forward_grounding_batched.nms"):
|
||||||
|
assert nms_prob_thresh is not None and nms_iou_thresh is not None
|
||||||
|
pred_probs = out["pred_logits"].squeeze(-1).sigmoid()
|
||||||
|
pred_masks = out["pred_masks"]
|
||||||
|
# pred_probs shape: [batch_size, num_queries]
|
||||||
|
# pred_masks shape: [batch_size, num_queries, H, W]
|
||||||
|
# Use batched NMS to process all frames at once
|
||||||
|
keep = nms_masks(
|
||||||
|
pred_probs=pred_probs,
|
||||||
|
pred_masks=pred_masks,
|
||||||
|
prob_threshold=nms_prob_thresh,
|
||||||
|
iou_threshold=nms_iou_thresh,
|
||||||
|
nms_use_iom=nms_use_iom,
|
||||||
|
do_compile=getattr(self, "compile_model", False),
|
||||||
|
running_in_prod=getattr(self, "running_in_prod", False),
|
||||||
|
)
|
||||||
|
# Set a very low threshold for detections removed by NMS
|
||||||
|
# keep shape: [batch_size, num_queries]
|
||||||
|
out["pred_logits"][:, :, 0] -= 1e4 * (~keep).float()
|
||||||
|
|
||||||
|
# Extract SAM2 backbone features if requested
|
||||||
|
if return_sam2_backbone_feats and "prev_encoder_out" in out:
|
||||||
|
backbone_data = out["prev_encoder_out"]["backbone_out"]
|
||||||
|
if self.is_multiplex and "interactive" in backbone_data:
|
||||||
|
out["_interactive_backbone"] = backbone_data["interactive"]
|
||||||
|
if "sam2_backbone_out" in backbone_data:
|
||||||
|
out["_sam2_backbone"] = backbone_data["sam2_backbone_out"]
|
||||||
|
|
||||||
|
out["_chunk_size"] = chunk_size
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _slice_batched_output(
|
||||||
|
self,
|
||||||
|
chunk_outputs,
|
||||||
|
local_idx: int,
|
||||||
|
return_sam2_backbone_feats: bool,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Slice a single frame's output from the batched chunk outputs.
|
||||||
|
"""
|
||||||
|
out = {}
|
||||||
|
|
||||||
|
# Keys to slice at batch dimension
|
||||||
|
batch_dim_keys = {
|
||||||
|
"pred_logits",
|
||||||
|
"pred_boxes",
|
||||||
|
"pred_boxes_xyxy",
|
||||||
|
"pred_masks",
|
||||||
|
"pred_logits_o2m",
|
||||||
|
"pred_boxes_o2m",
|
||||||
|
"pred_boxes_xyxy_o2m",
|
||||||
|
"pred_masks_o2m",
|
||||||
|
"queries",
|
||||||
|
"presence_logit_dec",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Keys to skip
|
||||||
|
skip_keys = {
|
||||||
|
"_chunk_size",
|
||||||
|
"_interactive_backbone",
|
||||||
|
"_sam2_backbone",
|
||||||
|
"prev_encoder_out",
|
||||||
|
"encoder_hidden_states",
|
||||||
|
"aux_outputs",
|
||||||
|
}
|
||||||
|
|
||||||
|
for key, value in chunk_outputs.items():
|
||||||
|
if key in skip_keys:
|
||||||
|
continue
|
||||||
|
if key in batch_dim_keys and isinstance(value, torch.Tensor):
|
||||||
|
out[key] = value[local_idx : local_idx + 1]
|
||||||
|
elif isinstance(value, torch.Tensor):
|
||||||
|
try:
|
||||||
|
out[key] = value[local_idx : local_idx + 1]
|
||||||
|
except (IndexError, RuntimeError):
|
||||||
|
out[key] = value
|
||||||
|
|
||||||
|
# Add object IDs
|
||||||
|
if "pred_logits" in out:
|
||||||
|
out["pred_object_ids"] = self._get_dummy_object_ids(out["pred_logits"])
|
||||||
|
|
||||||
|
# Add SAM2 backbone features if requested
|
||||||
|
if return_sam2_backbone_feats:
|
||||||
|
if "_sam2_backbone" in chunk_outputs:
|
||||||
|
sam2_bb = chunk_outputs["_sam2_backbone"]
|
||||||
|
out["sam2_backbone_fpn_0"] = sam2_bb["backbone_fpn"][0].tensors[
|
||||||
|
local_idx : local_idx + 1
|
||||||
|
]
|
||||||
|
out["sam2_backbone_fpn_1"] = sam2_bb["backbone_fpn"][1].tensors[
|
||||||
|
local_idx : local_idx + 1
|
||||||
|
]
|
||||||
|
out["sam2_backbone_fpn_2"] = sam2_bb["backbone_fpn"][2].tensors[
|
||||||
|
local_idx : local_idx + 1
|
||||||
|
]
|
||||||
|
out["sam2_backbone_pos_enc"] = [
|
||||||
|
x[local_idx : local_idx + 1] for x in sam2_bb["vision_pos_enc"]
|
||||||
|
]
|
||||||
|
|
||||||
|
if self.is_multiplex and "_interactive_backbone" in chunk_outputs:
|
||||||
|
inte_bb = chunk_outputs["_interactive_backbone"]
|
||||||
|
out["interactive_backbone_fpn_0"] = inte_bb["backbone_fpn"][0].tensors[
|
||||||
|
local_idx : local_idx + 1
|
||||||
|
]
|
||||||
|
out["interactive_backbone_fpn_1"] = inte_bb["backbone_fpn"][1].tensors[
|
||||||
|
local_idx : local_idx + 1
|
||||||
|
]
|
||||||
|
out["interactive_backbone_fpn_2"] = inte_bb["backbone_fpn"][2].tensors[
|
||||||
|
local_idx : local_idx + 1
|
||||||
|
]
|
||||||
|
out["interactive_backbone_pos_enc"] = [
|
||||||
|
x[local_idx : local_idx + 1] for x in inte_bb["vision_pos_enc"]
|
||||||
|
]
|
||||||
|
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _cleanup_previous_chunks_multigpu(
|
||||||
|
self,
|
||||||
|
grounding_cache,
|
||||||
|
current_chunk_key,
|
||||||
|
batch_size: int,
|
||||||
|
num_frames: int,
|
||||||
|
track_in_reverse: bool,
|
||||||
|
):
|
||||||
|
"""Remove previous chunks from cache to save GPU memory."""
|
||||||
|
chunk_start, chunk_end = current_chunk_key
|
||||||
|
|
||||||
|
if not track_in_reverse:
|
||||||
|
prev_chunk_start = chunk_start - batch_size
|
||||||
|
if prev_chunk_start >= 0:
|
||||||
|
prev_chunk_end = chunk_start
|
||||||
|
prev_chunk_key = (prev_chunk_start, prev_chunk_end)
|
||||||
|
|
||||||
|
# Cleanup grounding_buffer entry
|
||||||
|
chunk = grounding_cache["grounding_buffer"].pop(prev_chunk_key, None)
|
||||||
|
if chunk is not None:
|
||||||
|
del chunk
|
||||||
|
else:
|
||||||
|
next_chunk_start = chunk_end
|
||||||
|
if next_chunk_start < num_frames:
|
||||||
|
next_chunk_end = min(next_chunk_start + batch_size, num_frames)
|
||||||
|
next_chunk_key = (next_chunk_start, next_chunk_end)
|
||||||
|
grounding_cache["grounding_buffer"].pop(next_chunk_key, None)
|
||||||
@@ -0,0 +1,369 @@
|
|||||||
|
import logging
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from sam3 import perflib
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Ronghang's generic GPU NMS implementation; install via
|
||||||
|
# pip uninstall -y torch_generic_nms; TORCH_CUDA_ARCH_LIST="8.0 9.0" pip install git+https://github.com/ronghanghu/torch_generic_nms
|
||||||
|
from torch_generic_nms import generic_nms
|
||||||
|
|
||||||
|
GENERIC_NMS_AVAILABLE = True
|
||||||
|
except ImportError:
|
||||||
|
GENERIC_NMS_AVAILABLE = False
|
||||||
|
|
||||||
|
from sam3.perflib.masks_ops import mask_iou
|
||||||
|
from sam3.train.masks_ops import mask_iom
|
||||||
|
|
||||||
|
|
||||||
|
def nms_masks(
|
||||||
|
pred_probs: torch.Tensor,
|
||||||
|
pred_masks: torch.Tensor,
|
||||||
|
prob_threshold: float,
|
||||||
|
iou_threshold: float,
|
||||||
|
nms_use_iom: bool = False,
|
||||||
|
do_compile: bool = False,
|
||||||
|
running_in_prod: bool = False,
|
||||||
|
) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
- pred_probs: (num_det,) or (B, num_det) float Tensor, containing the score (probability) of each detection
|
||||||
|
- pred_masks: (num_det, H_mask, W_mask) or (B, num_det, H_mask, W_mask) float Tensor, containing the binary segmentation mask of each detection
|
||||||
|
- prob_threshold: float, score threshold to prefilter detections (NMS is performed on detections above threshold)
|
||||||
|
- iou_threshold: float, mask IoU threshold for NMS (it would also be used as IoM threshold if `nms_use_iom` is True)
|
||||||
|
- nms_use_iom: bool, if True, use IoM instead of IoU for NMS
|
||||||
|
- do_compile: bool, whether to compile the function for optimization
|
||||||
|
- running_in_prod: bool, whether the function is running in production (ie, in Instagram)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- keep: (num_det,) or (B, num_det) bool Tensor, indicating whether each detection is kept after score thresholding + NMS
|
||||||
|
"""
|
||||||
|
if do_compile and perflib.is_enabled:
|
||||||
|
# Apply torch.compile with the same settings as before
|
||||||
|
compiled_fn = torch.compile(
|
||||||
|
_nms_masks_core,
|
||||||
|
mode="max-autotune",
|
||||||
|
fullgraph=True,
|
||||||
|
# dynamic=False,
|
||||||
|
)
|
||||||
|
return compiled_fn(
|
||||||
|
pred_probs, pred_masks, prob_threshold, iou_threshold, nms_use_iom
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
return _nms_masks_core(
|
||||||
|
pred_probs, pred_masks, prob_threshold, iou_threshold, nms_use_iom
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _nms_masks_core(
|
||||||
|
pred_probs: torch.Tensor,
|
||||||
|
pred_masks: torch.Tensor,
|
||||||
|
prob_threshold: float,
|
||||||
|
iou_threshold: float,
|
||||||
|
nms_use_iom: bool = False,
|
||||||
|
) -> torch.Tensor:
|
||||||
|
"""Core NMS implementation without compilation.
|
||||||
|
|
||||||
|
Supports both single-frame and batched inputs:
|
||||||
|
- Single-frame: pred_probs (num_det,), pred_masks (num_det, H, W)
|
||||||
|
- Batched: pred_probs (B, num_det), pred_masks (B, num_det, H, W)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- keep: bool Tensor with same leading dimensions as input, indicating kept detections
|
||||||
|
"""
|
||||||
|
# Check if input is batched (has batch dimension)
|
||||||
|
is_batched = pred_probs.dim() == 2
|
||||||
|
|
||||||
|
if is_batched:
|
||||||
|
return _nms_masks_core_batched(
|
||||||
|
pred_probs, pred_masks, prob_threshold, iou_threshold, nms_use_iom
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Single-frame input: use original logic
|
||||||
|
return _nms_masks_core_single(
|
||||||
|
pred_probs, pred_masks, prob_threshold, iou_threshold, nms_use_iom
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _nms_masks_core_batched(
|
||||||
|
pred_probs: torch.Tensor,
|
||||||
|
pred_masks: torch.Tensor,
|
||||||
|
prob_threshold: float,
|
||||||
|
iou_threshold: float,
|
||||||
|
nms_use_iom: bool = False,
|
||||||
|
) -> torch.Tensor:
|
||||||
|
"""Core NMS implementation for batched inputs using vectorized operations.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- pred_probs: (B, num_det) float Tensor
|
||||||
|
- pred_masks: (B, num_det, H_mask, W_mask) float Tensor
|
||||||
|
- prob_threshold: float, score threshold to prefilter detections
|
||||||
|
- iou_threshold: float, mask IoU/IoM threshold for NMS
|
||||||
|
- nms_use_iom: bool, if True, use IoM instead of IoU for NMS
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- keep: (B, num_det) bool Tensor
|
||||||
|
"""
|
||||||
|
B, num_det, H, W = pred_masks.shape
|
||||||
|
device = pred_masks.device
|
||||||
|
|
||||||
|
is_valid = pred_probs > prob_threshold # (B, num_det)
|
||||||
|
masks_binary = pred_masks > 0 # (B, num_det, H, W)
|
||||||
|
|
||||||
|
if perflib.is_enabled:
|
||||||
|
# Compute batched pairwise IoU/IoM
|
||||||
|
if nms_use_iom:
|
||||||
|
overlaps = _batched_mask_iom(masks_binary) # (B, num_det, num_det)
|
||||||
|
else:
|
||||||
|
overlaps = _batched_mask_iou(masks_binary) # (B, num_det, num_det)
|
||||||
|
keep = _batched_generic_nms_mask(overlaps, pred_probs, is_valid, iou_threshold)
|
||||||
|
return keep
|
||||||
|
|
||||||
|
# Non-perflib path: compute batched IoU/IoM
|
||||||
|
if nms_use_iom:
|
||||||
|
overlaps = _batched_mask_iom(masks_binary) # (B, num_det, num_det)
|
||||||
|
else:
|
||||||
|
overlaps = _batched_mask_iou(masks_binary) # (B, num_det, num_det)
|
||||||
|
|
||||||
|
# Apply batched NMS
|
||||||
|
keep = _batched_generic_nms_mask(overlaps, pred_probs, is_valid, iou_threshold)
|
||||||
|
return keep
|
||||||
|
|
||||||
|
|
||||||
|
def _batched_mask_iou(masks: torch.Tensor) -> torch.Tensor:
|
||||||
|
"""Compute batched pairwise IoU for masks.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- masks: (B, N, H, W) bool Tensor
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- ious: (B, N, N) float Tensor
|
||||||
|
"""
|
||||||
|
B, N, H, W = masks.shape
|
||||||
|
# Flatten spatial dims: (B, N, H*W)
|
||||||
|
masks_flat = masks.reshape(B, N, -1).float()
|
||||||
|
|
||||||
|
# Compute intersection via batched matrix multiplication: (B, N, N)
|
||||||
|
intersection = torch.bmm(masks_flat, masks_flat.transpose(1, 2))
|
||||||
|
|
||||||
|
# Compute areas: (B, N)
|
||||||
|
areas = masks_flat.sum(dim=-1)
|
||||||
|
|
||||||
|
# Compute union: (B, N, N)
|
||||||
|
union = areas.unsqueeze(2) + areas.unsqueeze(1) - intersection
|
||||||
|
|
||||||
|
return intersection / (union + 1e-8)
|
||||||
|
|
||||||
|
|
||||||
|
def _batched_mask_iom(masks: torch.Tensor) -> torch.Tensor:
|
||||||
|
"""Compute batched pairwise IoM (Intersection over Minimum) for masks.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- masks: (B, N, H, W) bool Tensor
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- ioms: (B, N, N) float Tensor
|
||||||
|
"""
|
||||||
|
B, N, H, W = masks.shape
|
||||||
|
# Flatten spatial dims: (B, N, H*W)
|
||||||
|
masks_flat = masks.reshape(B, N, -1).float()
|
||||||
|
|
||||||
|
# Compute intersection via batched matrix multiplication: (B, N, N)
|
||||||
|
intersection = torch.bmm(masks_flat, masks_flat.transpose(1, 2))
|
||||||
|
|
||||||
|
# Compute areas: (B, N)
|
||||||
|
areas = masks_flat.sum(dim=-1)
|
||||||
|
|
||||||
|
# Compute min area: (B, N, N)
|
||||||
|
min_area = torch.minimum(areas.unsqueeze(2), areas.unsqueeze(1))
|
||||||
|
|
||||||
|
return intersection / (min_area + 1e-8)
|
||||||
|
|
||||||
|
|
||||||
|
def _batched_generic_nms_mask(
|
||||||
|
ious: torch.Tensor,
|
||||||
|
scores: torch.Tensor,
|
||||||
|
is_valid: torch.Tensor,
|
||||||
|
iou_threshold: float,
|
||||||
|
) -> torch.Tensor:
|
||||||
|
"""Batched NMS using vectorized operations.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- ious: (B, N, N) float Tensor, pairwise IoU/IoM matrix
|
||||||
|
- scores: (B, N) float Tensor, detection scores
|
||||||
|
- is_valid: (B, N) bool Tensor, valid detections mask
|
||||||
|
- iou_threshold: float, threshold for suppression
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- keep: (B, N) bool Tensor
|
||||||
|
"""
|
||||||
|
B, N = scores.shape
|
||||||
|
device = scores.device
|
||||||
|
|
||||||
|
# Sort by score descending for each batch: (B, N)
|
||||||
|
order = scores.argsort(dim=-1, descending=True)
|
||||||
|
|
||||||
|
# Create batch indices for advanced indexing
|
||||||
|
batch_idx = torch.arange(B, device=device).unsqueeze(1).expand(B, N)
|
||||||
|
|
||||||
|
# Reorder IoU matrix according to sorted scores: (B, N, N)
|
||||||
|
# ious_sorted[b, i, j] = ious[b, order[b, i], order[b, j]]
|
||||||
|
ious_sorted = ious[batch_idx.unsqueeze(2), order.unsqueeze(2), order.unsqueeze(1)]
|
||||||
|
|
||||||
|
# Create threshold mask: (B, N, N)
|
||||||
|
threshold_mask = ious_sorted > iou_threshold
|
||||||
|
|
||||||
|
# Initialize keep mask with valid detections in sorted order: (B, N)
|
||||||
|
keep = is_valid[batch_idx, order]
|
||||||
|
|
||||||
|
# Upper triangular mask to avoid double processing: (N, N)
|
||||||
|
triu = torch.triu(torch.ones(N, N, device=device, dtype=torch.bool), diagonal=1)
|
||||||
|
|
||||||
|
# Vectorized NMS - iterate through detections
|
||||||
|
for i in range(N):
|
||||||
|
# For each position i, suppress later detections with high overlap
|
||||||
|
# Only suppress if current detection is kept
|
||||||
|
suppress = (
|
||||||
|
threshold_mask[:, i, :] & triu[i].unsqueeze(0) & keep[:, i].unsqueeze(1)
|
||||||
|
)
|
||||||
|
keep = keep & ~suppress
|
||||||
|
|
||||||
|
# Return keep mask in original order: (B, N)
|
||||||
|
original_keep = torch.zeros_like(keep)
|
||||||
|
original_keep[batch_idx, order] = keep
|
||||||
|
return original_keep
|
||||||
|
|
||||||
|
|
||||||
|
def _nms_masks_core_single(
|
||||||
|
pred_probs: torch.Tensor,
|
||||||
|
pred_masks: torch.Tensor,
|
||||||
|
prob_threshold: float,
|
||||||
|
iou_threshold: float,
|
||||||
|
nms_use_iom: bool = False,
|
||||||
|
) -> torch.Tensor:
|
||||||
|
"""Core NMS implementation for a single frame (no batch dimension).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- pred_probs: (num_det,) float Tensor
|
||||||
|
- pred_masks: (num_det, H_mask, W_mask) float Tensor
|
||||||
|
- prob_threshold: float, score threshold to prefilter detections
|
||||||
|
- iou_threshold: float, mask IoU/IoM threshold for NMS
|
||||||
|
- nms_use_iom: bool, if True, use IoM instead of IoU for NMS
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- keep: (num_det,) bool Tensor
|
||||||
|
"""
|
||||||
|
is_valid = pred_probs > prob_threshold # (num_det,)
|
||||||
|
|
||||||
|
if perflib.is_enabled:
|
||||||
|
masks_binary = pred_masks > 0 # (num_det, H_mask, W_mask)
|
||||||
|
if nms_use_iom:
|
||||||
|
ious = perf_mask_iom(masks_binary, masks_binary) # (num_det, num_det)
|
||||||
|
else:
|
||||||
|
ious = perf_mask_iou(masks_binary, masks_binary) # (num_det, num_det)
|
||||||
|
kept_mask = generic_nms_mask(ious, pred_probs, is_valid, iou_threshold)
|
||||||
|
return kept_mask
|
||||||
|
# prefilter the detections with prob_threshold ("valid" are those above prob_threshold)
|
||||||
|
probs = pred_probs[is_valid] # (num_valid,)
|
||||||
|
masks_binary = pred_masks[is_valid] > 0 # (num_valid, H_mask, W_mask)
|
||||||
|
if probs.numel() == 0:
|
||||||
|
return is_valid # no valid detection, return empty keep mask
|
||||||
|
|
||||||
|
if nms_use_iom:
|
||||||
|
overlaps = mask_iom(masks_binary, masks_binary) # (num_valid, num_valid)
|
||||||
|
else:
|
||||||
|
overlaps = mask_iou(masks_binary, masks_binary) # (num_valid, num_valid)
|
||||||
|
# kept_inds are the indices among `probs` of those kept detections after NMS
|
||||||
|
if GENERIC_NMS_AVAILABLE:
|
||||||
|
kept_inds = generic_nms(overlaps, probs, iou_threshold, use_iou_matrix=True)
|
||||||
|
else:
|
||||||
|
logging.warning(
|
||||||
|
"Falling back to CPU mask NMS implementation -- please install `torch_generic_nms` via\n\t"
|
||||||
|
'pip uninstall -y torch_generic_nms; TORCH_CUDA_ARCH_LIST="8.0 9.0" pip install git+https://github.com/ronghanghu/torch_generic_nms'
|
||||||
|
)
|
||||||
|
kept_inds = generic_nms_cpu(overlaps, probs, iou_threshold)
|
||||||
|
|
||||||
|
# valid_inds are the indices among `probs` of valid detections before NMS (or -1 for invalid)
|
||||||
|
valid_inds = torch.where(is_valid, is_valid.cumsum(dim=0) - 1, -1) # (num_det,)
|
||||||
|
keep = torch.isin(valid_inds, kept_inds) # (num_det,)
|
||||||
|
return keep
|
||||||
|
|
||||||
|
|
||||||
|
def generic_nms_cpu(
|
||||||
|
ious: torch.Tensor, scores: torch.Tensor, iou_threshold=0.5
|
||||||
|
) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
A generic version of `torchvision.ops.nms` that takes a pairwise IoU matrix. (CPU implementation
|
||||||
|
based on https://github.com/jwyang/faster-rcnn.pytorch/blob/master/lib/model/nms/nms_cpu.py)
|
||||||
|
"""
|
||||||
|
ious_np = ious.float().detach().cpu().numpy()
|
||||||
|
scores_np = scores.float().detach().cpu().numpy()
|
||||||
|
order = scores_np.argsort()[::-1]
|
||||||
|
kept_inds = []
|
||||||
|
while order.size > 0:
|
||||||
|
i = order.item(0)
|
||||||
|
kept_inds.append(i)
|
||||||
|
inds = np.where(ious_np[i, order[1:]] <= iou_threshold)[0]
|
||||||
|
order = order[inds + 1]
|
||||||
|
|
||||||
|
return torch.tensor(kept_inds, dtype=torch.int64, device=scores.device)
|
||||||
|
|
||||||
|
|
||||||
|
def generic_nms_mask(
|
||||||
|
ious: torch.Tensor, scores: torch.Tensor, is_valid: torch.Tensor, iou_threshold=0.5
|
||||||
|
) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
A generic version of `torchvision.ops.nms` that takes a pairwise IoU matrix. (CPU implementation
|
||||||
|
using vectorized operations similar to nms_masks_kernel)
|
||||||
|
"""
|
||||||
|
# Sort by score descending
|
||||||
|
order = scores.argsort(descending=True)
|
||||||
|
|
||||||
|
# Reorder IoU matrix according to sorted scores
|
||||||
|
ious_sorted = ious[order][:, order]
|
||||||
|
|
||||||
|
# Create threshold mask
|
||||||
|
threshold_mask = ious_sorted > iou_threshold
|
||||||
|
|
||||||
|
# Initialize keep mask
|
||||||
|
# keep = torch.ones(len(scores), device=ious.device, dtype=torch.bool)
|
||||||
|
keep = is_valid[order]
|
||||||
|
|
||||||
|
# Upper triangular mask to avoid double processing
|
||||||
|
tr = torch.triu(torch.ones_like(threshold_mask), diagonal=1)
|
||||||
|
|
||||||
|
# Vectorized NMS
|
||||||
|
for i in range(len(scores)):
|
||||||
|
# Suppress all boxes that have high IoU with current box
|
||||||
|
m = threshold_mask[i]
|
||||||
|
keep = torch.where(m & tr[i], torch.zeros_like(keep), keep)
|
||||||
|
|
||||||
|
# Return keep mask in original order
|
||||||
|
original_keep = torch.zeros_like(keep)
|
||||||
|
original_keep[order] = keep
|
||||||
|
return original_keep
|
||||||
|
|
||||||
|
|
||||||
|
def perf_mask_iou(pred_masks: torch.Tensor, gt_masks: torch.Tensor) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
Compute the IoU (Intersection over Union) between predicted masks and ground truth masks.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- pred_masks: (N, H, W) bool Tensor, containing binary predicted segmentation masks
|
||||||
|
- gt_masks: (M, H, W) bool Tensor, containing binary ground truth segmentation masks
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- ious: (N, M) float Tensor, containing IoUs for each pair of predicted and ground truth masks
|
||||||
|
"""
|
||||||
|
assert pred_masks.dtype == gt_masks.dtype == torch.bool
|
||||||
|
from sam3.perflib.iou import pairwise_iou
|
||||||
|
|
||||||
|
return pairwise_iou(pred_masks, gt_masks, eps=None)
|
||||||
|
|
||||||
|
|
||||||
|
def perf_mask_iom(pred_masks: torch.Tensor, gt_masks: torch.Tensor) -> torch.Tensor:
|
||||||
|
assert pred_masks.dtype == gt_masks.dtype == torch.bool
|
||||||
|
from sam3.perflib.iou import pairwise_iom
|
||||||
|
|
||||||
|
return pairwise_iom(pred_masks, gt_masks)
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,63 @@
|
|||||||
|
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
||||||
|
|
||||||
|
# pyre-unsafe
|
||||||
|
|
||||||
|
"""
|
||||||
|
Sam3MultiplexVideoPredictor — user-facing entry point for SAM 3.1 multiplex.
|
||||||
|
|
||||||
|
Ported from onevision Sam3Model (webdemo/ta/models/sam3_model.py).
|
||||||
|
Handles warm-up compilation, bf16 autocast, and session management
|
||||||
|
via the shared Sam3BasePredictor handle_request/handle_stream_request API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Dict, Optional
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from sam3.logger import get_logger
|
||||||
|
from sam3.model.sam3_base_predictor import Sam3BasePredictor
|
||||||
|
|
||||||
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Sam3MultiplexVideoPredictor(Sam3BasePredictor):
|
||||||
|
"""
|
||||||
|
User-facing predictor for SAM 3.1 multiplex video tracking.
|
||||||
|
|
||||||
|
Wraps Sam3MultiplexTrackingWithInteractivity with:
|
||||||
|
- bf16 autocast
|
||||||
|
- Warm-up compilation (when compile=True)
|
||||||
|
- Session expiration management
|
||||||
|
- handle_request / handle_stream_request dispatch API (from Sam3BasePredictor)
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
model,
|
||||||
|
session_expiration_sec=1200,
|
||||||
|
default_output_prob_thresh=0.5,
|
||||||
|
async_loading_frames=True,
|
||||||
|
warm_up=False,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.model = model
|
||||||
|
self.session_expiration_sec = session_expiration_sec
|
||||||
|
self.default_output_prob_thresh = default_output_prob_thresh
|
||||||
|
self.async_loading_frames = async_loading_frames
|
||||||
|
|
||||||
|
# turn on tfloat32 for Ampere GPUs
|
||||||
|
torch.backends.cuda.matmul.allow_tf32 = True
|
||||||
|
torch.backends.cudnn.allow_tf32 = True
|
||||||
|
# use bfloat16 inference for Flash Attention kernel
|
||||||
|
self.bf16_context = torch.autocast(device_type="cuda", dtype=torch.bfloat16)
|
||||||
|
self.bf16_context.__enter__()
|
||||||
|
|
||||||
|
if warm_up:
|
||||||
|
self.model._warm_up_complete = False
|
||||||
|
self.model.warm_up_compilation()
|
||||||
|
self.model._warm_up_complete = True
|
||||||
|
|
||||||
|
def _extend_expiration_time(self, session):
|
||||||
|
"""Update last-use time and store session expiration timeout."""
|
||||||
|
super()._extend_expiration_time(session)
|
||||||
|
if self.session_expiration_sec:
|
||||||
|
session["expiration_sec"] = self.session_expiration_sec
|
||||||
@@ -367,7 +367,17 @@ def get_best_gt_match_from_multimasks(pred_multimasks, gt_masks, pred_scores=Non
|
|||||||
return best_pred_mask
|
return best_pred_mask
|
||||||
|
|
||||||
|
|
||||||
def fill_holes_in_mask_scores(mask, max_area, fill_holes=True, remove_sprinkles=True):
|
def fill_holes_in_mask_scores(
|
||||||
|
mask,
|
||||||
|
max_area=None,
|
||||||
|
fill_holes=True,
|
||||||
|
remove_sprinkles=True,
|
||||||
|
fill_hole_area=None,
|
||||||
|
sprinkle_removal_area=None,
|
||||||
|
):
|
||||||
|
# Support onevision-style keyword args
|
||||||
|
if fill_hole_area is not None and max_area is None:
|
||||||
|
max_area = fill_hole_area
|
||||||
"""
|
"""
|
||||||
A post processor to fill small holes in mask scores with area under `max_area`.
|
A post processor to fill small holes in mask scores with area under `max_area`.
|
||||||
Holes are those small connected components in either background or foreground.
|
Holes are those small connected components in either background or foreground.
|
||||||
|
|||||||
+312
-83
@@ -8,8 +8,9 @@ import math
|
|||||||
import os
|
import os
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
|
from dataclasses import dataclass
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import Any, Dict, List, Set
|
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import numpy.typing as npt
|
import numpy.typing as npt
|
||||||
@@ -22,7 +23,7 @@ from sam3.model.box_ops import fast_diag_box_iou
|
|||||||
from sam3.model.data_misc import BatchedDatapoint
|
from sam3.model.data_misc import BatchedDatapoint
|
||||||
from sam3.model.sam3_tracker_utils import fill_holes_in_mask_scores, mask_to_box
|
from sam3.model.sam3_tracker_utils import fill_holes_in_mask_scores, mask_to_box
|
||||||
from sam3.perflib.masks_ops import mask_iou
|
from sam3.perflib.masks_ops import mask_iou
|
||||||
from sam3.train.masks_ops import rle_encode
|
from sam3.train.masks_ops import mask_iom, rle_encode
|
||||||
from torch import nn, Tensor
|
from torch import nn, Tensor
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
@@ -33,6 +34,226 @@ class MaskletConfirmationStatus(Enum):
|
|||||||
CONFIRMED = 2 # confirmed by at least one detection
|
CONFIRMED = 2 # confirmed by at least one detection
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class RealizedAssociateDetTrkresult:
|
||||||
|
new_det_fa_inds: np.array
|
||||||
|
unmatched_trk_obj_ids: np.array
|
||||||
|
det_to_matched_trk_obj_ids: Dict[int, np.array]
|
||||||
|
trk_id_to_max_iou_high_conf_det: Dict[int, int]
|
||||||
|
empty_trk_obj_ids: np.array
|
||||||
|
new_det_obj_ids: Optional[np.array] = None
|
||||||
|
new_det_gpu_ids: Optional[np.array] = None
|
||||||
|
num_obj_dropped_due_to_limit: Optional[int] = None
|
||||||
|
|
||||||
|
def get_new_det_gpu_ids(
|
||||||
|
self, tracker_metadata_prev, is_image_only, det_scores, tracking_obj
|
||||||
|
):
|
||||||
|
with torch.profiler.record_function("get_new_det_gpu_ids"):
|
||||||
|
if self.new_det_obj_ids is None:
|
||||||
|
det_scores_np: np.ndarray = det_scores.cpu().numpy()
|
||||||
|
prev_obj_num = np.sum(tracker_metadata_prev["num_obj_per_gpu"])
|
||||||
|
new_det_num = len(self.new_det_fa_inds)
|
||||||
|
num_obj_dropped_due_to_limit = 0
|
||||||
|
if (
|
||||||
|
not is_image_only
|
||||||
|
and prev_obj_num + new_det_num > tracking_obj.max_num_objects
|
||||||
|
):
|
||||||
|
logger.warning(
|
||||||
|
f"hitting {tracking_obj.max_num_objects=} with {new_det_num=} and {prev_obj_num=}"
|
||||||
|
)
|
||||||
|
new_det_num_to_keep = tracking_obj.max_num_objects - prev_obj_num
|
||||||
|
num_obj_dropped_due_to_limit = new_det_num - new_det_num_to_keep
|
||||||
|
self.new_det_fa_inds = tracking_obj._drop_new_det_with_obj_limit(
|
||||||
|
self.new_det_fa_inds, det_scores_np, new_det_num_to_keep
|
||||||
|
)
|
||||||
|
assert len(self.new_det_fa_inds) == new_det_num_to_keep
|
||||||
|
new_det_num = len(self.new_det_fa_inds)
|
||||||
|
new_det_start_obj_id = tracker_metadata_prev["max_obj_id"] + 1
|
||||||
|
new_det_obj_ids = new_det_start_obj_id + np.arange(new_det_num)
|
||||||
|
if tracking_obj.is_multiplex:
|
||||||
|
prev_workload_per_gpu = tracker_metadata_prev["num_buc_per_gpu"]
|
||||||
|
else:
|
||||||
|
prev_workload_per_gpu = tracker_metadata_prev["num_obj_per_gpu"]
|
||||||
|
new_det_gpu_ids = tracking_obj._assign_new_det_to_gpus(
|
||||||
|
new_det_num=new_det_num,
|
||||||
|
prev_workload_per_gpu=prev_workload_per_gpu,
|
||||||
|
)
|
||||||
|
self.new_det_obj_ids = new_det_obj_ids
|
||||||
|
self.new_det_gpu_ids = new_det_gpu_ids
|
||||||
|
self.num_obj_dropped_due_to_limit = num_obj_dropped_due_to_limit
|
||||||
|
return (
|
||||||
|
self.new_det_obj_ids,
|
||||||
|
self.new_det_gpu_ids,
|
||||||
|
self.num_obj_dropped_due_to_limit,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def realize_adt_result(adt_lazy_result, tracker_metadata_prev, det_mask_preds):
|
||||||
|
if isinstance(adt_lazy_result, LazyAssociateDetTrkResult):
|
||||||
|
adt_lazy_result._convert_to_numpy()
|
||||||
|
return adt_lazy_result._create_cpu_metadata(
|
||||||
|
tracker_metadata_prev["obj_ids_all_gpu"], det_mask_preds
|
||||||
|
)
|
||||||
|
return adt_lazy_result
|
||||||
|
|
||||||
|
|
||||||
|
class LazyAssociateDetTrkResult:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
trk_is_unmatched: Tensor,
|
||||||
|
trk_is_nonempty: Tensor,
|
||||||
|
is_new_det: Tensor,
|
||||||
|
det_to_max_iou_trk_idx: Tensor,
|
||||||
|
det_is_high_conf: Tensor,
|
||||||
|
det_is_high_iou: Tensor,
|
||||||
|
det_keep: Tensor,
|
||||||
|
im_mask: Tensor,
|
||||||
|
):
|
||||||
|
self.trk_is_unmatched = trk_is_unmatched
|
||||||
|
self.trk_is_nonempty = trk_is_nonempty
|
||||||
|
self.is_new_det = is_new_det
|
||||||
|
self.det_to_max_iou_trk_idx = det_to_max_iou_trk_idx
|
||||||
|
self.det_is_high_conf = det_is_high_conf
|
||||||
|
self.det_is_high_iou = det_is_high_iou
|
||||||
|
self.det_keep = det_keep
|
||||||
|
self.im_mask = im_mask
|
||||||
|
|
||||||
|
def _convert_to_numpy(self):
|
||||||
|
with torch.profiler.record_function("Convert to numpy"):
|
||||||
|
self.trk_is_unmatched = self.trk_is_unmatched.cpu().numpy()
|
||||||
|
self.trk_is_nonempty = self.trk_is_nonempty.cpu().numpy()
|
||||||
|
self.is_new_det = self.is_new_det.cpu().numpy()
|
||||||
|
self.det_to_max_iou_trk_idx = self.det_to_max_iou_trk_idx.cpu().numpy()
|
||||||
|
self.det_is_high_conf = self.det_is_high_conf.cpu().numpy()
|
||||||
|
self.det_is_high_iou = self.det_is_high_iou.cpu().numpy()
|
||||||
|
self.det_keep = self.det_keep.cpu().numpy().tolist()
|
||||||
|
self.im_mask = self.im_mask.cpu().numpy()
|
||||||
|
|
||||||
|
def _create_cpu_metadata(self, trk_obj_ids, det_masks):
|
||||||
|
with torch.profiler.record_function("_create_cpu_metadata"):
|
||||||
|
unmatched_trk_obj_ids = trk_obj_ids[self.trk_is_unmatched]
|
||||||
|
empty_trk_obj_ids = trk_obj_ids[~self.trk_is_nonempty]
|
||||||
|
new_det_fa_inds = np.nonzero(self.is_new_det)[0]
|
||||||
|
det_is_high_conf_and_iou = set(
|
||||||
|
np.nonzero(self.det_is_high_conf & self.det_is_high_iou)[0]
|
||||||
|
)
|
||||||
|
det_to_matched_trk_obj_ids = {}
|
||||||
|
trk_id_to_max_iou_high_conf_det = {}
|
||||||
|
for d in range(det_masks.size(0)):
|
||||||
|
if self.det_keep[d]:
|
||||||
|
det_to_matched_trk_obj_ids[d] = trk_obj_ids[self.im_mask[d, :]]
|
||||||
|
if d in det_is_high_conf_and_iou:
|
||||||
|
trk_obj_id = trk_obj_ids[self.det_to_max_iou_trk_idx[d]].item()
|
||||||
|
trk_id_to_max_iou_high_conf_det[trk_obj_id] = d
|
||||||
|
return RealizedAssociateDetTrkresult(
|
||||||
|
new_det_fa_inds=new_det_fa_inds,
|
||||||
|
unmatched_trk_obj_ids=unmatched_trk_obj_ids,
|
||||||
|
det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
|
||||||
|
trk_id_to_max_iou_high_conf_det=trk_id_to_max_iou_high_conf_det,
|
||||||
|
empty_trk_obj_ids=empty_trk_obj_ids,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _associate_det_trk_compilable(
|
||||||
|
det_masks,
|
||||||
|
det_scores,
|
||||||
|
det_keep,
|
||||||
|
trk_masks,
|
||||||
|
new_det_thresh,
|
||||||
|
iou_threshold_trk,
|
||||||
|
iou_threshold,
|
||||||
|
HIGH_CONF_THRESH,
|
||||||
|
use_iom_recondition,
|
||||||
|
o2o_matching_masklets_enable,
|
||||||
|
iom_thresh_recondition,
|
||||||
|
iou_thresh_recondition,
|
||||||
|
):
|
||||||
|
det_masks_binary = det_masks > 0
|
||||||
|
det_masks_binary[~det_keep] = 0
|
||||||
|
trk_masks_binary = trk_masks > 0
|
||||||
|
intersection_metric = None
|
||||||
|
if use_iom_recondition:
|
||||||
|
intersection_metric = mask_iom(det_masks_binary, trk_masks_binary) # (N, M)
|
||||||
|
else:
|
||||||
|
intersection_metric = mask_iou(det_masks_binary, trk_masks_binary) # (N, M)
|
||||||
|
|
||||||
|
assert not o2o_matching_masklets_enable, "Temporarily disabled support for o2o_matching_masklets_enable, due to optimizations."
|
||||||
|
|
||||||
|
if o2o_matching_masklets_enable:
|
||||||
|
intersection_metric_np = intersection_metric.cpu().numpy()
|
||||||
|
from scipy.optimize import linear_sum_assignment
|
||||||
|
|
||||||
|
cost_matrix = 1 - intersection_metric_np
|
||||||
|
row_ind, col_ind = linear_sum_assignment(cost_matrix)
|
||||||
|
trk_is_matched = np.zeros(trk_masks.size(0), dtype=bool)
|
||||||
|
for d, t in zip(row_ind, col_ind):
|
||||||
|
if intersection_metric_np[d, t] >= iou_threshold_trk:
|
||||||
|
trk_is_matched[t] = True
|
||||||
|
trk_is_matched = torch.from_numpy(trk_is_matched)
|
||||||
|
trk_is_matched = trk_is_matched.to(device=intersection_metric.device)
|
||||||
|
else:
|
||||||
|
trk_is_matched = (intersection_metric >= iou_threshold_trk).any(dim=0)
|
||||||
|
# Non-empty tracks not matched by Hungarian assignment above threshold are unmatched
|
||||||
|
trk_is_nonempty = trk_masks_binary.any(dim=(1, 2))
|
||||||
|
trk_is_unmatched = torch.logical_and(trk_is_nonempty, ~trk_is_matched)
|
||||||
|
|
||||||
|
# For detections: allow many tracks to match to the same detection (many-to-one)
|
||||||
|
# So, a detection is 'new' if it does not match any track above threshold
|
||||||
|
is_new_det = torch.logical_and(
|
||||||
|
torch.logical_and((det_scores >= new_det_thresh), (det_keep)),
|
||||||
|
torch.logical_not(torch.any(intersection_metric >= iou_threshold, dim=1)),
|
||||||
|
)
|
||||||
|
|
||||||
|
intersection_thresh_recond = (
|
||||||
|
iom_thresh_recondition if use_iom_recondition else iou_thresh_recondition
|
||||||
|
)
|
||||||
|
# if a detection matches to many tracks with high IoU or vice versa, we do not consider it for reconditioning as it might be ambiguous
|
||||||
|
det_match_to_many_trk = (intersection_metric >= intersection_thresh_recond).sum(
|
||||||
|
dim=1
|
||||||
|
) > 1
|
||||||
|
trk_match_to_many_det = (intersection_metric >= intersection_thresh_recond).sum(
|
||||||
|
dim=0
|
||||||
|
) > 1
|
||||||
|
# # zero out these ambiguous matches
|
||||||
|
# intersection_metric[:, trk_match_to_many_det] = (
|
||||||
|
# 0.0 # only consider unique matches
|
||||||
|
# )
|
||||||
|
|
||||||
|
# intersection_metric[det_match_to_many_trk, :] = (
|
||||||
|
# 0.0 # only consider unique matches
|
||||||
|
# )
|
||||||
|
|
||||||
|
intersection_metric = torch.where(
|
||||||
|
trk_match_to_many_det.unsqueeze(0),
|
||||||
|
torch.zeros_like(intersection_metric),
|
||||||
|
intersection_metric,
|
||||||
|
)
|
||||||
|
|
||||||
|
intersection_metric = torch.where(
|
||||||
|
det_match_to_many_trk.unsqueeze(1),
|
||||||
|
torch.zeros_like(intersection_metric),
|
||||||
|
intersection_metric,
|
||||||
|
)
|
||||||
|
|
||||||
|
det_to_max_iou_trk_idx = torch.argmax(intersection_metric, dim=1)
|
||||||
|
det_is_high_conf = ((det_scores >= HIGH_CONF_THRESH) & det_keep) & ~is_new_det
|
||||||
|
det_is_high_iou = (
|
||||||
|
torch.amax(intersection_metric, dim=1) >= intersection_thresh_recond
|
||||||
|
)
|
||||||
|
im_mask = intersection_metric >= iou_threshold
|
||||||
|
|
||||||
|
return (
|
||||||
|
trk_is_unmatched,
|
||||||
|
trk_is_nonempty,
|
||||||
|
is_new_det,
|
||||||
|
det_to_max_iou_trk_idx,
|
||||||
|
det_is_high_conf,
|
||||||
|
det_is_high_iou,
|
||||||
|
det_keep,
|
||||||
|
im_mask,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class Sam3VideoBase(nn.Module):
|
class Sam3VideoBase(nn.Module):
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -516,17 +737,7 @@ class Sam3VideoBase(nn.Module):
|
|||||||
is_image_only: bool = False,
|
is_image_only: bool = False,
|
||||||
):
|
):
|
||||||
# initialize new metadata from previous metadata (its values will be updated later)
|
# initialize new metadata from previous metadata (its values will be updated later)
|
||||||
tracker_metadata_new = {
|
tracker_metadata_new = self._create_planning_metadata(tracker_metadata_prev)
|
||||||
"obj_ids_per_gpu": deepcopy(tracker_metadata_prev["obj_ids_per_gpu"]),
|
|
||||||
"obj_ids_all_gpu": None, # will be filled later
|
|
||||||
"num_obj_per_gpu": deepcopy(tracker_metadata_prev["num_obj_per_gpu"]),
|
|
||||||
"obj_id_to_score": deepcopy(tracker_metadata_prev["obj_id_to_score"]),
|
|
||||||
"obj_id_to_tracker_score_frame_wise": deepcopy(
|
|
||||||
tracker_metadata_prev["obj_id_to_tracker_score_frame_wise"]
|
|
||||||
),
|
|
||||||
"obj_id_to_last_occluded": {}, # will be filled later
|
|
||||||
"max_obj_id": deepcopy(tracker_metadata_prev["max_obj_id"]),
|
|
||||||
}
|
|
||||||
|
|
||||||
# Initialize reconditioned_obj_ids early to avoid UnboundLocalError
|
# Initialize reconditioned_obj_ids early to avoid UnboundLocalError
|
||||||
reconditioned_obj_ids = set()
|
reconditioned_obj_ids = set()
|
||||||
@@ -619,9 +830,9 @@ class Sam3VideoBase(nn.Module):
|
|||||||
num_obj_dropped_due_to_limit,
|
num_obj_dropped_due_to_limit,
|
||||||
trk_id_to_max_iou_high_conf_det,
|
trk_id_to_max_iou_high_conf_det,
|
||||||
]
|
]
|
||||||
assert len(update_plan) == NUM_BROADCAST_ITEMS, (
|
assert (
|
||||||
f"Manually update NUM_BROADCAST_ITEMS to be: {len(update_plan)}"
|
len(update_plan) == NUM_BROADCAST_ITEMS
|
||||||
)
|
), f"Manually update NUM_BROADCAST_ITEMS to be: {len(update_plan)}"
|
||||||
self.broadcast_python_obj_cpu(update_plan, src=0)
|
self.broadcast_python_obj_cpu(update_plan, src=0)
|
||||||
elif self.rank > 0 and self.world_size > 1:
|
elif self.rank > 0 and self.world_size > 1:
|
||||||
update_plan = [
|
update_plan = [
|
||||||
@@ -841,9 +1052,9 @@ class Sam3VideoBase(nn.Module):
|
|||||||
binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0
|
binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0
|
||||||
batch_size = tracker_low_res_masks_global.size(0)
|
batch_size = tracker_low_res_masks_global.size(0)
|
||||||
if batch_size > 0:
|
if batch_size > 0:
|
||||||
assert len(obj_ids_global) == batch_size, (
|
assert (
|
||||||
f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}"
|
len(obj_ids_global) == batch_size
|
||||||
)
|
), f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}"
|
||||||
NEVER_OCCLUDED = -1
|
NEVER_OCCLUDED = -1
|
||||||
ALWAYS_OCCLUDED = 100000 # This value should be larger than any possible frame index, indicates that the object was removed by hotstart logic
|
ALWAYS_OCCLUDED = 100000 # This value should be larger than any possible frame index, indicates that the object was removed by hotstart logic
|
||||||
last_occluded_prev = torch.cat(
|
last_occluded_prev = torch.cat(
|
||||||
@@ -901,6 +1112,7 @@ class Sam3VideoBase(nn.Module):
|
|||||||
orig_vid_height: int,
|
orig_vid_height: int,
|
||||||
orig_vid_width: int,
|
orig_vid_width: int,
|
||||||
feature_cache: Dict,
|
feature_cache: Dict,
|
||||||
|
tracker_metadata_new=None,
|
||||||
):
|
):
|
||||||
# initialize tracking scores with detection scores
|
# initialize tracking scores with detection scores
|
||||||
new_det_fa_inds: npt.NDArray = tracker_update_plan["new_det_fa_inds"]
|
new_det_fa_inds: npt.NDArray = tracker_update_plan["new_det_fa_inds"]
|
||||||
@@ -931,8 +1143,31 @@ class Sam3VideoBase(nn.Module):
|
|||||||
if len(obj_ids_newly_removed) > 0:
|
if len(obj_ids_newly_removed) > 0:
|
||||||
self._tracker_remove_objects(tracker_states_local, obj_ids_newly_removed)
|
self._tracker_remove_objects(tracker_states_local, obj_ids_newly_removed)
|
||||||
|
|
||||||
|
self._post_execution_phase_hook(tracker_states_local, tracker_metadata_new)
|
||||||
return tracker_states_local
|
return tracker_states_local
|
||||||
|
|
||||||
|
def _create_planning_metadata(self, tracker_metadata_prev):
|
||||||
|
"""Create the metadata dict for the planning phase from previous metadata."""
|
||||||
|
from copy import deepcopy
|
||||||
|
|
||||||
|
score_key = "obj_id_to_tracker_score_frame_wise"
|
||||||
|
if score_key not in tracker_metadata_prev:
|
||||||
|
score_key = "obj_id_to_sam2_score_frame_wise"
|
||||||
|
metadata = {
|
||||||
|
"obj_ids_per_gpu": deepcopy(tracker_metadata_prev["obj_ids_per_gpu"]),
|
||||||
|
"obj_ids_all_gpu": None,
|
||||||
|
"num_obj_per_gpu": deepcopy(tracker_metadata_prev["num_obj_per_gpu"]),
|
||||||
|
"obj_id_to_score": deepcopy(tracker_metadata_prev["obj_id_to_score"]),
|
||||||
|
score_key: deepcopy(tracker_metadata_prev[score_key]),
|
||||||
|
"obj_id_to_last_occluded": {},
|
||||||
|
"max_obj_id": deepcopy(tracker_metadata_prev["max_obj_id"]),
|
||||||
|
}
|
||||||
|
return metadata
|
||||||
|
|
||||||
|
def _post_execution_phase_hook(self, tracker_states_local, tracker_metadata_new):
|
||||||
|
"""Hook for subclasses to add post-execution logic. Default: no-op."""
|
||||||
|
pass
|
||||||
|
|
||||||
def build_outputs(
|
def build_outputs(
|
||||||
self,
|
self,
|
||||||
frame_idx: int,
|
frame_idx: int,
|
||||||
@@ -1022,9 +1257,9 @@ class Sam3VideoBase(nn.Module):
|
|||||||
reverse: bool = False,
|
reverse: bool = False,
|
||||||
):
|
):
|
||||||
# Suppress overlapping masks for objects that were most recently occluded
|
# Suppress overlapping masks for objects that were most recently occluded
|
||||||
assert binary_low_res_masks.dtype == torch.bool, (
|
assert (
|
||||||
f"Expected boolean tensor, got {binary_low_res_masks.dtype}"
|
binary_low_res_masks.dtype == torch.bool
|
||||||
)
|
), f"Expected boolean tensor, got {binary_low_res_masks.dtype}"
|
||||||
to_suppress = torch.zeros(
|
to_suppress = torch.zeros(
|
||||||
binary_low_res_masks.size(0),
|
binary_low_res_masks.size(0),
|
||||||
device=binary_low_res_masks.device,
|
device=binary_low_res_masks.device,
|
||||||
@@ -1129,9 +1364,9 @@ class Sam3VideoBase(nn.Module):
|
|||||||
num_frames_propagated += 1
|
num_frames_propagated += 1
|
||||||
|
|
||||||
# only 1 frames should be propagated
|
# only 1 frames should be propagated
|
||||||
assert num_frames_propagated == 1 and out_frame_idx == frame_idx, (
|
assert (
|
||||||
f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}"
|
num_frames_propagated == 1 and out_frame_idx == frame_idx
|
||||||
)
|
), f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}"
|
||||||
assert isinstance(out_obj_ids, list)
|
assert isinstance(out_obj_ids, list)
|
||||||
obj_ids_local.extend(out_obj_ids)
|
obj_ids_local.extend(out_obj_ids)
|
||||||
low_res_masks_list.append(out_low_res_masks.squeeze(1))
|
low_res_masks_list.append(out_low_res_masks.squeeze(1))
|
||||||
@@ -1180,6 +1415,7 @@ class Sam3VideoBase(nn.Module):
|
|||||||
to any detections on this frame (for unmatched, we only count masklets with >0 area)
|
to any detections on this frame (for unmatched, we only count masklets with >0 area)
|
||||||
- det_to_matched_trk_obj_ids: dict[int, npt.NDArray]: mapping from detector's detection indices
|
- det_to_matched_trk_obj_ids: dict[int, npt.NDArray]: mapping from detector's detection indices
|
||||||
to the list of matched tracklet object IDs
|
to the list of matched tracklet object IDs
|
||||||
|
- trk_id_to_max_iou_high_conf_det: dict mapping track obj_id to the highest-IoU high-conf detection idx
|
||||||
- empty_trk_obj_ids: array of existing masklet object IDs with zero area in SAM2 prediction
|
- empty_trk_obj_ids: array of existing masklet object IDs with zero area in SAM2 prediction
|
||||||
"""
|
"""
|
||||||
iou_threshold = self.assoc_iou_thresh
|
iou_threshold = self.assoc_iou_thresh
|
||||||
@@ -1188,9 +1424,9 @@ class Sam3VideoBase(nn.Module):
|
|||||||
|
|
||||||
assert det_masks.is_floating_point(), "float tensor expected (do not binarize)"
|
assert det_masks.is_floating_point(), "float tensor expected (do not binarize)"
|
||||||
assert trk_masks.is_floating_point(), "float tensor expected (do not binarize)"
|
assert trk_masks.is_floating_point(), "float tensor expected (do not binarize)"
|
||||||
assert trk_masks.size(0) == len(trk_obj_ids), (
|
assert (
|
||||||
f"trk_masks and trk_obj_ids should have the same length, {trk_masks.size(0)} vs {len(trk_obj_ids)}"
|
trk_masks.size(0) == len(trk_obj_ids)
|
||||||
)
|
), f"trk_masks and trk_obj_ids should have the same length, {trk_masks.size(0)} vs {len(trk_obj_ids)}"
|
||||||
if trk_masks.size(0) == 0:
|
if trk_masks.size(0) == 0:
|
||||||
# all detections are new
|
# all detections are new
|
||||||
new_det_fa_inds = np.arange(det_masks.size(0))
|
new_det_fa_inds = np.arange(det_masks.size(0))
|
||||||
@@ -1239,61 +1475,40 @@ class Sam3VideoBase(nn.Module):
|
|||||||
align_corners=False,
|
align_corners=False,
|
||||||
).squeeze(1)
|
).squeeze(1)
|
||||||
|
|
||||||
det_masks_binary = det_masks > 0
|
# Convert numpy scores to tensor for the compilable function
|
||||||
trk_masks_binary = trk_masks > 0
|
det_scores = torch.from_numpy(det_scores_np).to(det_masks.device)
|
||||||
ious = mask_iou(det_masks_binary, trk_masks_binary) # (N, M)
|
det_keep = torch.ones(
|
||||||
|
det_masks.size(0), dtype=torch.bool, device=det_masks.device
|
||||||
ious_np = ious.cpu().numpy()
|
|
||||||
if self.o2o_matching_masklets_enable:
|
|
||||||
from scipy.optimize import linear_sum_assignment
|
|
||||||
|
|
||||||
# Hungarian matching for tracks (one-to-one: each track matches at most one detection)
|
|
||||||
cost_matrix = 1 - ious_np # Hungarian solves for minimum cost
|
|
||||||
row_ind, col_ind = linear_sum_assignment(cost_matrix)
|
|
||||||
trk_is_matched = np.zeros(trk_masks.size(0), dtype=bool)
|
|
||||||
for d, t in zip(row_ind, col_ind):
|
|
||||||
if ious_np[d, t] >= iou_threshold_trk:
|
|
||||||
trk_is_matched[t] = True
|
|
||||||
else:
|
|
||||||
trk_is_matched = (ious_np >= iou_threshold_trk).any(axis=0)
|
|
||||||
# Non-empty tracks not matched by Hungarian assignment above threshold are unmatched
|
|
||||||
trk_is_nonempty = trk_masks_binary.any(dim=(1, 2)).cpu().numpy()
|
|
||||||
trk_is_unmatched = np.logical_and(trk_is_nonempty, ~trk_is_matched)
|
|
||||||
unmatched_trk_obj_ids = trk_obj_ids[trk_is_unmatched]
|
|
||||||
# also record masklets that have zero area in SAM 2 prediction
|
|
||||||
empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty]
|
|
||||||
|
|
||||||
# For detections: allow many tracks to match to the same detection (many-to-one)
|
|
||||||
# So, a detection is 'new' if it does not match any track above threshold
|
|
||||||
is_new_det = np.logical_and(
|
|
||||||
det_scores_np >= new_det_thresh,
|
|
||||||
np.logical_not(np.any(ious_np >= iou_threshold, axis=1)),
|
|
||||||
)
|
)
|
||||||
new_det_fa_inds = np.nonzero(is_new_det)[0]
|
|
||||||
|
|
||||||
# for each detection, which tracks it matched to (above threshold)
|
# Call the GPU-native compilable function
|
||||||
det_to_matched_trk_obj_ids = {}
|
adt_result_tensors = _associate_det_trk_compilable(
|
||||||
trk_id_to_max_iou_high_conf_det = {} # trk id --> exactly one detection idx
|
det_masks=det_masks,
|
||||||
HIGH_CONF_THRESH = 0.8
|
det_scores=det_scores,
|
||||||
HIGH_IOU_THRESH = 0.8
|
det_keep=det_keep,
|
||||||
det_to_max_iou_trk_idx = np.argmax(ious_np, axis=1)
|
trk_masks=trk_masks,
|
||||||
det_is_high_conf = (det_scores_np >= HIGH_CONF_THRESH) & ~is_new_det
|
new_det_thresh=new_det_thresh,
|
||||||
det_is_high_iou = np.max(ious_np, axis=1) >= HIGH_IOU_THRESH
|
iou_threshold_trk=iou_threshold_trk,
|
||||||
det_is_high_conf_and_iou = set(
|
iou_threshold=iou_threshold,
|
||||||
np.nonzero(det_is_high_conf & det_is_high_iou)[0]
|
HIGH_CONF_THRESH=0.8,
|
||||||
|
use_iom_recondition=getattr(self, "use_iom_recondition", False),
|
||||||
|
o2o_matching_masklets_enable=self.o2o_matching_masklets_enable,
|
||||||
|
iom_thresh_recondition=getattr(self, "iom_thresh_recondition", 0.8),
|
||||||
|
iou_thresh_recondition=getattr(self, "iou_thresh_recondition", 0.8),
|
||||||
)
|
)
|
||||||
for d in range(det_masks.size(0)):
|
|
||||||
det_to_matched_trk_obj_ids[d] = trk_obj_ids[ious_np[d, :] >= iou_threshold]
|
# Wrap in LazyAssociateDetTrkResult and immediately realize to numpy
|
||||||
if d in det_is_high_conf_and_iou:
|
# for backward compatibility with existing callers
|
||||||
trk_obj_id = trk_obj_ids[det_to_max_iou_trk_idx[d]].item()
|
lazy_result = LazyAssociateDetTrkResult(*adt_result_tensors)
|
||||||
trk_id_to_max_iou_high_conf_det[trk_obj_id] = d
|
lazy_result._convert_to_numpy()
|
||||||
|
realized = lazy_result._create_cpu_metadata(trk_obj_ids, det_masks)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
new_det_fa_inds,
|
realized.new_det_fa_inds,
|
||||||
unmatched_trk_obj_ids,
|
realized.unmatched_trk_obj_ids,
|
||||||
det_to_matched_trk_obj_ids,
|
realized.det_to_matched_trk_obj_ids,
|
||||||
trk_id_to_max_iou_high_conf_det,
|
realized.trk_id_to_max_iou_high_conf_det,
|
||||||
empty_trk_obj_ids,
|
realized.empty_trk_obj_ids,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _assign_new_det_to_gpus(self, new_det_num, prev_workload_per_gpu):
|
def _assign_new_det_to_gpus(self, new_det_num, prev_workload_per_gpu):
|
||||||
@@ -1601,21 +1816,35 @@ class Sam3VideoBase(nn.Module):
|
|||||||
|
|
||||||
def _initialize_metadata(self):
|
def _initialize_metadata(self):
|
||||||
"""Initialize metadata for the masklets."""
|
"""Initialize metadata for the masklets."""
|
||||||
|
is_multiplex = getattr(self, "is_multiplex", False)
|
||||||
|
score_key = (
|
||||||
|
"obj_id_to_sam2_score_frame_wise"
|
||||||
|
if is_multiplex
|
||||||
|
else "obj_id_to_tracker_score_frame_wise"
|
||||||
|
)
|
||||||
tracker_metadata = {
|
tracker_metadata = {
|
||||||
"obj_ids_per_gpu": [np.array([], np.int64) for _ in range(self.world_size)],
|
"obj_ids_per_gpu": [np.array([], np.int64) for _ in range(self.world_size)],
|
||||||
"obj_ids_all_gpu": np.array([], np.int64),
|
"obj_ids_all_gpu": np.array([], np.int64),
|
||||||
"num_obj_per_gpu": np.zeros(self.world_size, np.int64),
|
"num_obj_per_gpu": np.zeros(self.world_size, np.int64),
|
||||||
"max_obj_id": -1,
|
"max_obj_id": -1,
|
||||||
"obj_id_to_score": {},
|
"obj_id_to_score": {},
|
||||||
"obj_id_to_tracker_score_frame_wise": defaultdict(dict),
|
score_key: defaultdict(dict),
|
||||||
"obj_id_to_last_occluded": {},
|
"obj_id_to_last_occluded": {},
|
||||||
}
|
}
|
||||||
if self.rank == 0:
|
if is_multiplex:
|
||||||
|
tracker_metadata["gpu_metadata"] = {
|
||||||
|
"N_obj": 0
|
||||||
|
} # GPU-side metadata for sync-free hotstart
|
||||||
|
tracker_metadata["num_buc_per_gpu"] = np.zeros(self.world_size, np.int64)
|
||||||
|
|
||||||
# "rank0_metadata" contains metadata that is only stored on (and accessible to) GPU 0
|
# "rank0_metadata" contains metadata that is only stored on (and accessible to) GPU 0
|
||||||
# - obj_first_frame_idx: obj_id --> first frame index where the object was detected
|
# - obj_first_frame_idx: obj_id --> first frame index where the object was detected
|
||||||
# - unmatched_frame_inds: obj_id --> [mismatched frame indices]
|
# - unmatched_frame_inds: obj_id --> [mismatched frame indices]
|
||||||
# - overlap_pair_to_frame_inds: (first_appear_obj_id, obj_id) --> [overlap frame indices]
|
# - overlap_pair_to_frame_inds: (first_appear_obj_id, obj_id) --> [overlap frame indices]
|
||||||
# - removed_obj_ids: object IDs that are suppressed via hot-start
|
# - removed_obj_ids: object IDs that are suppressed via hot-start
|
||||||
|
# In multiplex mode, rank0_metadata is always included (all GPUs need it).
|
||||||
|
# In non-multiplex mode, only rank 0 stores it.
|
||||||
|
if is_multiplex or self.rank == 0:
|
||||||
rank0_metadata = {
|
rank0_metadata = {
|
||||||
"obj_first_frame_idx": {},
|
"obj_first_frame_idx": {},
|
||||||
"unmatched_frame_inds": defaultdict(list),
|
"unmatched_frame_inds": defaultdict(list),
|
||||||
@@ -1654,9 +1883,9 @@ class Sam3VideoBase(nn.Module):
|
|||||||
# a) first, expand "confirmation_data" to include new masklets added in this frame
|
# a) first, expand "confirmation_data" to include new masklets added in this frame
|
||||||
status_prev = confirmation_data["status"]
|
status_prev = confirmation_data["status"]
|
||||||
consecutive_det_num_prev = confirmation_data["consecutive_det_num"]
|
consecutive_det_num_prev = confirmation_data["consecutive_det_num"]
|
||||||
assert status_prev.shape == obj_ids_all_gpu_prev.shape, (
|
assert (
|
||||||
f"Got {status_prev.shape} vs {obj_ids_all_gpu_prev.shape}"
|
status_prev.shape == obj_ids_all_gpu_prev.shape
|
||||||
)
|
), f"Got {status_prev.shape} vs {obj_ids_all_gpu_prev.shape}"
|
||||||
|
|
||||||
obj_id_to_updated_idx = {
|
obj_id_to_updated_idx = {
|
||||||
obj_id: idx for idx, obj_id in enumerate(obj_ids_all_gpu_updated)
|
obj_id: idx for idx, obj_id in enumerate(obj_ids_all_gpu_updated)
|
||||||
|
|||||||
@@ -554,9 +554,7 @@ class Sam3VideoInference(Sam3VideoBase):
|
|||||||
assert (
|
assert (
|
||||||
"cached_frame_outputs" in inference_state
|
"cached_frame_outputs" in inference_state
|
||||||
and frame_idx in inference_state["cached_frame_outputs"]
|
and frame_idx in inference_state["cached_frame_outputs"]
|
||||||
), (
|
), "No cached outputs found. Ensure normal propagation has run first to populate the cache."
|
||||||
"No cached outputs found. Ensure normal propagation has run first to populate the cache."
|
|
||||||
)
|
|
||||||
cached_outputs = inference_state["cached_frame_outputs"][frame_idx]
|
cached_outputs = inference_state["cached_frame_outputs"][frame_idx]
|
||||||
|
|
||||||
obj_id_to_mask = cached_outputs.copy()
|
obj_id_to_mask = cached_outputs.copy()
|
||||||
@@ -564,9 +562,9 @@ class Sam3VideoInference(Sam3VideoBase):
|
|||||||
# Update with refined masks if provided
|
# Update with refined masks if provided
|
||||||
if refined_obj_id_to_mask is not None:
|
if refined_obj_id_to_mask is not None:
|
||||||
for obj_id, refined_mask in refined_obj_id_to_mask.items():
|
for obj_id, refined_mask in refined_obj_id_to_mask.items():
|
||||||
assert refined_mask is not None, (
|
assert (
|
||||||
f"Refined mask data must be provided for obj_id {obj_id}"
|
refined_mask is not None
|
||||||
)
|
), f"Refined mask data must be provided for obj_id {obj_id}"
|
||||||
obj_id_to_mask[obj_id] = refined_mask
|
obj_id_to_mask[obj_id] = refined_mask
|
||||||
|
|
||||||
return obj_id_to_mask
|
return obj_id_to_mask
|
||||||
@@ -855,12 +853,12 @@ class Sam3VideoInference(Sam3VideoBase):
|
|||||||
logger.debug("Running add_prompt on frame %d", frame_idx)
|
logger.debug("Running add_prompt on frame %d", frame_idx)
|
||||||
|
|
||||||
num_frames = inference_state["num_frames"]
|
num_frames = inference_state["num_frames"]
|
||||||
assert text_str is not None or boxes_xywh is not None, (
|
assert (
|
||||||
"at least one type of prompt (text, boxes) must be provided"
|
text_str is not None or boxes_xywh is not None
|
||||||
)
|
), "at least one type of prompt (text, boxes) must be provided"
|
||||||
assert 0 <= frame_idx < num_frames, (
|
assert (
|
||||||
f"{frame_idx=} is out of range for a total of {num_frames} frames"
|
0 <= frame_idx < num_frames
|
||||||
)
|
), f"{frame_idx=} is out of range for a total of {num_frames} frames"
|
||||||
|
|
||||||
# since it's a semantic prompt, we start over
|
# since it's a semantic prompt, we start over
|
||||||
self.reset_state(inference_state)
|
self.reset_state(inference_state)
|
||||||
@@ -1201,9 +1199,9 @@ class Sam3VideoInferenceWithInstanceInteractivity(Sam3VideoInference):
|
|||||||
"propagation_partial",
|
"propagation_partial",
|
||||||
"propagation_fetch",
|
"propagation_fetch",
|
||||||
]
|
]
|
||||||
assert action_type in instance_actions + propagation_actions, (
|
assert (
|
||||||
f"Invalid action type: {action_type}, must be one of {instance_actions + propagation_actions}"
|
action_type in instance_actions + propagation_actions
|
||||||
)
|
), f"Invalid action type: {action_type}, must be one of {instance_actions + propagation_actions}"
|
||||||
action = {
|
action = {
|
||||||
"type": action_type,
|
"type": action_type,
|
||||||
"frame_idx": frame_idx,
|
"frame_idx": frame_idx,
|
||||||
@@ -1371,12 +1369,12 @@ class Sam3VideoInferenceWithInstanceInteractivity(Sam3VideoInference):
|
|||||||
):
|
):
|
||||||
if points is not None:
|
if points is not None:
|
||||||
# Tracker instance prompts
|
# Tracker instance prompts
|
||||||
assert text_str is None and boxes_xywh is None, (
|
assert (
|
||||||
"When points are provided, text_str and boxes_xywh must be None."
|
text_str is None and boxes_xywh is None
|
||||||
)
|
), "When points are provided, text_str and boxes_xywh must be None."
|
||||||
assert obj_id is not None, (
|
assert (
|
||||||
"When points are provided, obj_id must be provided."
|
obj_id is not None
|
||||||
)
|
), "When points are provided, obj_id must be provided."
|
||||||
return self.add_tracker_new_points(
|
return self.add_tracker_new_points(
|
||||||
inference_state,
|
inference_state,
|
||||||
frame_idx,
|
frame_idx,
|
||||||
@@ -1492,9 +1490,9 @@ class Sam3VideoInferenceWithInstanceInteractivity(Sam3VideoInference):
|
|||||||
tracker_states = self._get_tracker_inference_states_by_obj_ids(
|
tracker_states = self._get_tracker_inference_states_by_obj_ids(
|
||||||
inference_state, [obj_id]
|
inference_state, [obj_id]
|
||||||
)
|
)
|
||||||
assert len(tracker_states) == 1, (
|
assert (
|
||||||
f"[rank={self.rank}] Multiple Tracker inference states found for the same object id."
|
len(tracker_states) == 1
|
||||||
)
|
), f"[rank={self.rank}] Multiple Tracker inference states found for the same object id."
|
||||||
tracker_state = tracker_states[0]
|
tracker_state = tracker_states[0]
|
||||||
|
|
||||||
# log
|
# log
|
||||||
|
|||||||
@@ -17,14 +17,12 @@ from typing import List, Optional
|
|||||||
import psutil
|
import psutil
|
||||||
import torch
|
import torch
|
||||||
from sam3.logger import get_logger
|
from sam3.logger import get_logger
|
||||||
|
from sam3.model.sam3_base_predictor import Sam3BasePredictor
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class Sam3VideoPredictor:
|
class Sam3VideoPredictor(Sam3BasePredictor):
|
||||||
# a global dictionary that holds all inference states for this model (key is session_id)
|
|
||||||
_ALL_INFERENCE_STATES = {}
|
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
checkpoint_path=None,
|
checkpoint_path=None,
|
||||||
@@ -37,6 +35,7 @@ class Sam3VideoPredictor:
|
|||||||
apply_temporal_disambiguation: bool = True,
|
apply_temporal_disambiguation: bool = True,
|
||||||
compile: bool = False,
|
compile: bool = False,
|
||||||
):
|
):
|
||||||
|
super().__init__()
|
||||||
self.async_loading_frames = async_loading_frames
|
self.async_loading_frames = async_loading_frames
|
||||||
self.video_loader_type = video_loader_type
|
self.video_loader_type = video_loader_type
|
||||||
from sam3.model_builder import build_sam3_video_model
|
from sam3.model_builder import build_sam3_video_model
|
||||||
@@ -55,124 +54,14 @@ class Sam3VideoPredictor:
|
|||||||
.eval()
|
.eval()
|
||||||
)
|
)
|
||||||
|
|
||||||
@torch.inference_mode()
|
|
||||||
def handle_request(self, request):
|
|
||||||
"""Dispatch a request based on its type."""
|
|
||||||
request_type = request["type"]
|
|
||||||
if request_type == "start_session":
|
|
||||||
return self.start_session(
|
|
||||||
resource_path=request["resource_path"],
|
|
||||||
session_id=request.get("session_id", None),
|
|
||||||
)
|
|
||||||
elif request_type == "add_prompt":
|
|
||||||
return self.add_prompt(
|
|
||||||
session_id=request["session_id"],
|
|
||||||
frame_idx=request["frame_index"],
|
|
||||||
text=request.get("text", None),
|
|
||||||
points=request.get("points", None),
|
|
||||||
point_labels=request.get("point_labels", None),
|
|
||||||
bounding_boxes=request.get("bounding_boxes", None),
|
|
||||||
bounding_box_labels=request.get("bounding_box_labels", None),
|
|
||||||
obj_id=request.get("obj_id", None),
|
|
||||||
)
|
|
||||||
elif request_type == "remove_object":
|
|
||||||
return self.remove_object(
|
|
||||||
session_id=request["session_id"],
|
|
||||||
obj_id=request["obj_id"],
|
|
||||||
is_user_action=request.get("is_user_action", True),
|
|
||||||
)
|
|
||||||
elif request_type == "reset_session":
|
|
||||||
return self.reset_session(session_id=request["session_id"])
|
|
||||||
elif request_type == "close_session":
|
|
||||||
return self.close_session(session_id=request["session_id"])
|
|
||||||
else:
|
|
||||||
raise RuntimeError(f"invalid request type: {request_type}")
|
|
||||||
|
|
||||||
@torch.inference_mode()
|
|
||||||
def handle_stream_request(self, request):
|
|
||||||
"""Dispatch a stream request based on its type."""
|
|
||||||
request_type = request["type"]
|
|
||||||
if request_type == "propagate_in_video":
|
|
||||||
yield from self.propagate_in_video(
|
|
||||||
session_id=request["session_id"],
|
|
||||||
propagation_direction=request.get("propagation_direction", "both"),
|
|
||||||
start_frame_idx=request.get("start_frame_index", None),
|
|
||||||
max_frame_num_to_track=request.get("max_frame_num_to_track", None),
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
raise RuntimeError(f"invalid request type: {request_type}")
|
|
||||||
|
|
||||||
def start_session(self, resource_path, session_id=None):
|
|
||||||
"""
|
|
||||||
Start a new inference session on an image or a video. Here `resource_path`
|
|
||||||
can be either a path to an image file (for image inference) or an MP4 file
|
|
||||||
or directory with JPEG video frames (for video inference).
|
|
||||||
|
|
||||||
If `session_id` is defined, it will be used as identifier for the
|
|
||||||
session. If it is not defined, the start_session function will create
|
|
||||||
a session id and return it.
|
|
||||||
"""
|
|
||||||
# get an initial inference_state from the model
|
|
||||||
inference_state = self.model.init_state(
|
|
||||||
resource_path=resource_path,
|
|
||||||
async_loading_frames=self.async_loading_frames,
|
|
||||||
video_loader_type=self.video_loader_type,
|
|
||||||
)
|
|
||||||
if not session_id:
|
|
||||||
session_id = str(uuid.uuid4())
|
|
||||||
self._ALL_INFERENCE_STATES[session_id] = {
|
|
||||||
"state": inference_state,
|
|
||||||
"session_id": session_id,
|
|
||||||
"start_time": time.time(),
|
|
||||||
}
|
|
||||||
logger.debug(
|
|
||||||
f"started new session {session_id}; {self._get_session_stats()}; "
|
|
||||||
f"{self._get_torch_and_gpu_properties()}"
|
|
||||||
)
|
|
||||||
return {"session_id": session_id}
|
|
||||||
|
|
||||||
def add_prompt(
|
|
||||||
self,
|
|
||||||
session_id: str,
|
|
||||||
frame_idx: int,
|
|
||||||
text: Optional[str] = None,
|
|
||||||
points: Optional[List[List[float]]] = None,
|
|
||||||
point_labels: Optional[List[int]] = None,
|
|
||||||
bounding_boxes: Optional[List[List[float]]] = None,
|
|
||||||
bounding_box_labels: Optional[List[int]] = None,
|
|
||||||
obj_id: Optional[int] = None,
|
|
||||||
):
|
|
||||||
"""Add text, box and/or point prompt on a specific video frame."""
|
|
||||||
logger.debug(
|
|
||||||
f"add prompt on frame {frame_idx} in session {session_id}: "
|
|
||||||
f"{text=}, {points=}, {point_labels=}, "
|
|
||||||
f"{bounding_boxes=}, {bounding_box_labels=}"
|
|
||||||
)
|
|
||||||
session = self._get_session(session_id)
|
|
||||||
inference_state = session["state"]
|
|
||||||
|
|
||||||
frame_idx, outputs = self.model.add_prompt(
|
|
||||||
inference_state=inference_state,
|
|
||||||
frame_idx=frame_idx,
|
|
||||||
text_str=text,
|
|
||||||
points=points,
|
|
||||||
point_labels=point_labels,
|
|
||||||
boxes_xywh=bounding_boxes,
|
|
||||||
box_labels=bounding_box_labels,
|
|
||||||
obj_id=obj_id,
|
|
||||||
)
|
|
||||||
return {"frame_index": frame_idx, "outputs": outputs}
|
|
||||||
|
|
||||||
def remove_object(
|
def remove_object(
|
||||||
self,
|
self,
|
||||||
session_id: str,
|
session_id: str,
|
||||||
obj_id: int,
|
frame_idx: int = 0,
|
||||||
|
obj_id: int = 0,
|
||||||
is_user_action: bool = True,
|
is_user_action: bool = True,
|
||||||
):
|
):
|
||||||
"""Remove an object from tracking."""
|
"""Remove an object from tracking (SAM3 uses a simpler remove_object API)."""
|
||||||
logger.debug(
|
|
||||||
f"remove object {obj_id} in session {session_id}: {is_user_action=}"
|
|
||||||
)
|
|
||||||
session = self._get_session(session_id)
|
session = self._get_session(session_id)
|
||||||
inference_state = session["state"]
|
inference_state = session["state"]
|
||||||
|
|
||||||
@@ -183,111 +72,29 @@ class Sam3VideoPredictor:
|
|||||||
)
|
)
|
||||||
return {"is_success": True}
|
return {"is_success": True}
|
||||||
|
|
||||||
def propagate_in_video(
|
|
||||||
self,
|
|
||||||
session_id,
|
|
||||||
propagation_direction,
|
|
||||||
start_frame_idx,
|
|
||||||
max_frame_num_to_track,
|
|
||||||
):
|
|
||||||
"""Propagate the added prompts to get grounding results on all video frames."""
|
|
||||||
logger.debug(
|
|
||||||
f"propagate in video in session {session_id}: "
|
|
||||||
f"{propagation_direction=}, {start_frame_idx=}, {max_frame_num_to_track=}"
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
session = self._get_session(session_id)
|
|
||||||
inference_state = session["state"]
|
|
||||||
if propagation_direction not in ["both", "forward", "backward"]:
|
|
||||||
raise ValueError(
|
|
||||||
f"invalid propagation direction: {propagation_direction}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# First doing the forward propagation
|
|
||||||
if propagation_direction in ["both", "forward"]:
|
|
||||||
for frame_idx, outputs in self.model.propagate_in_video(
|
|
||||||
inference_state=inference_state,
|
|
||||||
start_frame_idx=start_frame_idx,
|
|
||||||
max_frame_num_to_track=max_frame_num_to_track,
|
|
||||||
reverse=False,
|
|
||||||
):
|
|
||||||
yield {"frame_index": frame_idx, "outputs": outputs}
|
|
||||||
# Then doing the backward propagation (reverse in time)
|
|
||||||
if propagation_direction in ["both", "backward"]:
|
|
||||||
for frame_idx, outputs in self.model.propagate_in_video(
|
|
||||||
inference_state=inference_state,
|
|
||||||
start_frame_idx=start_frame_idx,
|
|
||||||
max_frame_num_to_track=max_frame_num_to_track,
|
|
||||||
reverse=True,
|
|
||||||
):
|
|
||||||
yield {"frame_index": frame_idx, "outputs": outputs}
|
|
||||||
finally:
|
|
||||||
# Log upon completion (so that e.g. we can see if two propagations happen in parallel).
|
|
||||||
# Using `finally` here to log even when the tracking is aborted with GeneratorExit.
|
|
||||||
logger.debug(
|
|
||||||
f"propagation ended in session {session_id}; {self._get_session_stats()}"
|
|
||||||
)
|
|
||||||
|
|
||||||
def reset_session(self, session_id):
|
|
||||||
"""Reset the session to its initial state (as when it's initial opened)."""
|
|
||||||
logger.debug(f"reset session {session_id}")
|
|
||||||
session = self._get_session(session_id)
|
|
||||||
inference_state = session["state"]
|
|
||||||
self.model.reset_state(inference_state)
|
|
||||||
return {"is_success": True}
|
|
||||||
|
|
||||||
def close_session(self, session_id):
|
|
||||||
"""
|
|
||||||
Close a session. This method is idempotent and can be called multiple
|
|
||||||
times on the same "session_id".
|
|
||||||
"""
|
|
||||||
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 (it might have expired); "
|
|
||||||
f"{self._get_session_stats()}"
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
del session
|
|
||||||
gc.collect()
|
|
||||||
logger.info(f"removed session {session_id}; {self._get_session_stats()}")
|
|
||||||
return {"is_success": True}
|
|
||||||
|
|
||||||
def _get_session(self, session_id):
|
|
||||||
session = self._ALL_INFERENCE_STATES.get(session_id, None)
|
|
||||||
if session is None:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"Cannot find session {session_id}; it might have expired"
|
|
||||||
)
|
|
||||||
return session
|
|
||||||
|
|
||||||
def _get_session_stats(self):
|
def _get_session_stats(self):
|
||||||
"""Get a statistics string for live sessions and their GPU usage."""
|
"""Get a statistics string for live sessions and their GPU usage."""
|
||||||
# print both the session ids and their video frame numbers
|
live_session_strs = []
|
||||||
live_session_strs = [
|
for sid, s in self._all_inference_states.items():
|
||||||
f"'{session_id}' ({session['state']['num_frames']} frames)"
|
nf = s["state"]["num_frames"]
|
||||||
for session_id, session in self._ALL_INFERENCE_STATES.items()
|
live_session_strs.append(f"'{sid}' ({nf} frames)")
|
||||||
]
|
joined = ", ".join(live_session_strs)
|
||||||
session_stats_str = (
|
mem_alloc = torch.cuda.memory_allocated() // 1024**2
|
||||||
f"live sessions: [{', '.join(live_session_strs)}], GPU memory: "
|
mem_res = torch.cuda.memory_reserved() // 1024**2
|
||||||
f"{torch.cuda.memory_allocated() // 1024**2} MiB used and "
|
max_alloc = torch.cuda.max_memory_allocated() // 1024**2
|
||||||
f"{torch.cuda.memory_reserved() // 1024**2} MiB reserved"
|
max_res = torch.cuda.max_memory_reserved() // 1024**2
|
||||||
f" (max over time: {torch.cuda.max_memory_allocated() // 1024**2} MiB used "
|
return (
|
||||||
f"and {torch.cuda.max_memory_reserved() // 1024**2} MiB reserved)"
|
f"live sessions: [{joined}], GPU memory: "
|
||||||
|
f"{mem_alloc} MiB used and {mem_res} MiB reserved"
|
||||||
|
f" (max over time: {max_alloc} MiB used and {max_res} MiB reserved)"
|
||||||
)
|
)
|
||||||
return session_stats_str
|
|
||||||
|
|
||||||
def _get_torch_and_gpu_properties(self):
|
def _get_torch_and_gpu_properties(self):
|
||||||
"""Get a string for PyTorch and GPU properties (for logging and debugging)."""
|
"""Get a string for PyTorch and GPU properties."""
|
||||||
torch_and_gpu_str = (
|
return (
|
||||||
f"torch: {torch.__version__} with CUDA arch {torch.cuda.get_arch_list()}, "
|
f"torch: {torch.__version__} with CUDA arch {torch.cuda.get_arch_list()}, "
|
||||||
f"GPU device: {torch.cuda.get_device_properties(torch.cuda.current_device())}"
|
f"GPU device: {torch.cuda.get_device_properties(torch.cuda.current_device())}"
|
||||||
)
|
)
|
||||||
return torch_and_gpu_str
|
|
||||||
|
|
||||||
def shutdown(self):
|
|
||||||
"""Shutdown the predictor and clear all sessions."""
|
|
||||||
self._ALL_INFERENCE_STATES.clear()
|
|
||||||
|
|
||||||
|
|
||||||
class Sam3VideoPredictorMultiGPU(Sam3VideoPredictor):
|
class Sam3VideoPredictorMultiGPU(Sam3VideoPredictor):
|
||||||
|
|||||||
@@ -318,9 +318,9 @@ class VETextEncoder(nn.Module):
|
|||||||
# The text is already encoded, use as is.
|
# The text is already encoded, use as is.
|
||||||
text_attention_mask, text_memory_resized, tokenized = text
|
text_attention_mask, text_memory_resized, tokenized = text
|
||||||
inputs_embeds = tokenized["inputs_embeds"]
|
inputs_embeds = tokenized["inputs_embeds"]
|
||||||
assert input_boxes is None or len(input_boxes) == 0, (
|
assert (
|
||||||
"Can't replace boxes in text if it's already encoded"
|
input_boxes is None or len(input_boxes) == 0
|
||||||
)
|
), "Can't replace boxes in text if it's already encoded"
|
||||||
|
|
||||||
# Note that the input_embeds are returned in pytorch's convention (sequence first)
|
# Note that the input_embeds are returned in pytorch's convention (sequence first)
|
||||||
return (
|
return (
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+159
-8
@@ -22,13 +22,58 @@ import torch.nn.functional as F
|
|||||||
import torch.utils.checkpoint as checkpoint
|
import torch.utils.checkpoint as checkpoint
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from timm.layers import DropPath, Mlp, trunc_normal_
|
from timm.layers import DropPath, trunc_normal_
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
# compatibility for older timm versions
|
# compatibility for older timm versions
|
||||||
from timm.models.layers import DropPath, Mlp, trunc_normal_
|
from timm.models.layers import DropPath, trunc_normal_
|
||||||
|
from sam3.model.data_misc import NestedTensor
|
||||||
|
from sam3.model.model_misc import AttentionType, LayerScale
|
||||||
|
from sam3.perflib.fused import addmm_act
|
||||||
|
from sam3.sam.rope import apply_rotary_enc_real, VisionRotaryEmbeddingVE
|
||||||
from torch import Tensor
|
from torch import Tensor
|
||||||
|
|
||||||
from .model_misc import LayerScale
|
|
||||||
|
class Mlp(nn.Module):
|
||||||
|
"""MLP as used in Vision Transformer, MLP-Mixer and related networks"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
in_features,
|
||||||
|
hidden_features=None,
|
||||||
|
out_features=None,
|
||||||
|
act_layer=nn.GELU,
|
||||||
|
norm_layer=None,
|
||||||
|
bias=True,
|
||||||
|
drop=0.0,
|
||||||
|
use_conv=False,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
out_features = out_features or in_features
|
||||||
|
hidden_features = hidden_features or in_features
|
||||||
|
if isinstance(bias, bool):
|
||||||
|
bias = (bias, bias)
|
||||||
|
if isinstance(drop, (int, float)):
|
||||||
|
drop_probs = (drop, drop)
|
||||||
|
else:
|
||||||
|
drop_probs = drop
|
||||||
|
linear_layer = partial(nn.Conv2d, kernel_size=1) if use_conv else nn.Linear
|
||||||
|
|
||||||
|
self.fc1 = linear_layer(in_features, hidden_features, bias=bias[0])
|
||||||
|
self.act = act_layer()
|
||||||
|
self.drop1 = nn.Dropout(drop_probs[0])
|
||||||
|
self.norm = (
|
||||||
|
norm_layer(hidden_features) if norm_layer is not None else nn.Identity()
|
||||||
|
)
|
||||||
|
self.fc2 = linear_layer(hidden_features, out_features, bias=bias[1])
|
||||||
|
self.drop2 = nn.Dropout(drop_probs[1])
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
x = addmm_act(type(self.act), self.fc1, x)
|
||||||
|
x = self.drop1(x)
|
||||||
|
x = self.norm(x)
|
||||||
|
x = self.fc2(x)
|
||||||
|
x = self.drop2(x)
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
def init_t_xy(
|
def init_t_xy(
|
||||||
@@ -349,11 +394,16 @@ class Attention(nn.Module):
|
|||||||
use_rel_pos: bool = False,
|
use_rel_pos: bool = False,
|
||||||
rel_pos_zero_init: bool = True,
|
rel_pos_zero_init: bool = True,
|
||||||
input_size: Optional[Tuple[int, int]] = None,
|
input_size: Optional[Tuple[int, int]] = None,
|
||||||
|
attn_type: AttentionType = AttentionType.Vanilla,
|
||||||
cls_token: bool = False,
|
cls_token: bool = False,
|
||||||
use_rope: bool = False,
|
use_rope: bool = False,
|
||||||
rope_theta: float = 10000.0,
|
rope_theta: float = 10000.0,
|
||||||
rope_pt_size: Optional[Tuple[int, int]] = None,
|
rope_pt_size: Optional[Tuple[int, int]] = None,
|
||||||
rope_interp: bool = False,
|
rope_interp: bool = False,
|
||||||
|
rope_tiled: bool = False,
|
||||||
|
use_ve_rope: bool = False,
|
||||||
|
use_fa3: bool = False,
|
||||||
|
use_rope_real: bool = False,
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Args:
|
Args:
|
||||||
@@ -369,7 +419,9 @@ class Attention(nn.Module):
|
|||||||
use_rope: whether to use rope 2d (indep of use_rel_pos, as it can be used together)
|
use_rope: whether to use rope 2d (indep of use_rel_pos, as it can be used together)
|
||||||
rope_theta: control frequencies of rope
|
rope_theta: control frequencies of rope
|
||||||
rope_pt_size: size of rope in previous stage of training, needed for interpolation or tiling
|
rope_pt_size: size of rope in previous stage of training, needed for interpolation or tiling
|
||||||
|
rope_tiled: whether to tile rope or not; tile expected to be of size rope_pt_size x rope_pt_size
|
||||||
rope_interp: whether to interpolate (or extrapolate) rope to match input size
|
rope_interp: whether to interpolate (or extrapolate) rope to match input size
|
||||||
|
use_ve_rope: use ve orig rope implementation, if small numerical differences are important (normally not)
|
||||||
"""
|
"""
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.num_heads = num_heads
|
self.num_heads = num_heads
|
||||||
@@ -377,6 +429,7 @@ class Attention(nn.Module):
|
|||||||
self.scale = self.head_dim**-0.5
|
self.scale = self.head_dim**-0.5
|
||||||
self.cls_token = cls_token
|
self.cls_token = cls_token
|
||||||
|
|
||||||
|
self.attn_type = attn_type
|
||||||
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
||||||
self.proj = nn.Linear(dim, dim)
|
self.proj = nn.Linear(dim, dim)
|
||||||
|
|
||||||
@@ -388,6 +441,10 @@ class Attention(nn.Module):
|
|||||||
self.rope_theta = rope_theta
|
self.rope_theta = rope_theta
|
||||||
self.rope_pt_size = rope_pt_size
|
self.rope_pt_size = rope_pt_size
|
||||||
self.rope_interp = rope_interp
|
self.rope_interp = rope_interp
|
||||||
|
self.rope_tiled = rope_tiled
|
||||||
|
self.use_ve_rope = use_ve_rope
|
||||||
|
self.use_fa3 = use_fa3
|
||||||
|
self.use_rope_real = use_rope_real
|
||||||
|
|
||||||
# init rel_pos embeddings and rope
|
# init rel_pos embeddings and rope
|
||||||
self._setup_rel_pos(rel_pos_zero_init)
|
self._setup_rel_pos(rel_pos_zero_init)
|
||||||
@@ -430,6 +487,15 @@ class Attention(nn.Module):
|
|||||||
if self.rope_pt_size is None:
|
if self.rope_pt_size is None:
|
||||||
self.rope_pt_size = self.input_size
|
self.rope_pt_size = self.input_size
|
||||||
|
|
||||||
|
if self.use_ve_rope:
|
||||||
|
assert not self.rope_tiled, "not supported"
|
||||||
|
self.rope = VisionRotaryEmbeddingVE(
|
||||||
|
dim=self.head_dim // 2,
|
||||||
|
seq_len=self.input_size[0],
|
||||||
|
pt_seq_len=self.rope_pt_size[0],
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
# initialize 2d rope freqs
|
# initialize 2d rope freqs
|
||||||
self.compute_cis = partial(
|
self.compute_cis = partial(
|
||||||
compute_axial_cis,
|
compute_axial_cis,
|
||||||
@@ -437,6 +503,30 @@ class Attention(nn.Module):
|
|||||||
theta=self.rope_theta,
|
theta=self.rope_theta,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if self.rope_pt_size != self.input_size and self.rope_tiled:
|
||||||
|
assert not self.rope_interp
|
||||||
|
# window/tiled rope
|
||||||
|
freqs_cis = self.compute_cis(
|
||||||
|
end_x=self.rope_pt_size[0], end_y=self.rope_pt_size[1]
|
||||||
|
)
|
||||||
|
# check dims are tileable
|
||||||
|
rh, rw = (
|
||||||
|
self.input_size[0] // self.rope_pt_size[0],
|
||||||
|
self.input_size[1] // self.rope_pt_size[1],
|
||||||
|
)
|
||||||
|
assert rh >= 1, rw >= 1
|
||||||
|
assert (
|
||||||
|
self.input_size[0] % self.rope_pt_size[0] == 0
|
||||||
|
and self.input_size[1] % self.rope_pt_size[1] == 0
|
||||||
|
)
|
||||||
|
|
||||||
|
# restore spatial shape, tile and then flatten spatial dims
|
||||||
|
freqs_cis = (
|
||||||
|
freqs_cis.reshape(self.rope_pt_size[0], self.rope_pt_size[1], -1)
|
||||||
|
.tile(rh, rw, 1)
|
||||||
|
.reshape(-1, freqs_cis.shape[-1])
|
||||||
|
)
|
||||||
|
else:
|
||||||
# interpolate rope
|
# interpolate rope
|
||||||
scale_pos = 1.0
|
scale_pos = 1.0
|
||||||
if self.rope_interp:
|
if self.rope_interp:
|
||||||
@@ -457,12 +547,27 @@ class Attention(nn.Module):
|
|||||||
freqs_cis = torch.cat([cls_freqs_cis, freqs_cis], dim=0)
|
freqs_cis = torch.cat([cls_freqs_cis, freqs_cis], dim=0)
|
||||||
|
|
||||||
self.register_buffer("freqs_cis", freqs_cis)
|
self.register_buffer("freqs_cis", freqs_cis)
|
||||||
|
if self.use_rope_real:
|
||||||
|
self.register_buffer("freqs_cis_real", freqs_cis.real)
|
||||||
|
self.register_buffer("freqs_cis_imag", freqs_cis.imag)
|
||||||
|
|
||||||
def _apply_rope(self, q, k) -> Tuple[Tensor, Tensor]:
|
def _apply_rope(self, q, k) -> Tuple[Tensor, Tensor]:
|
||||||
if not self.use_rope:
|
if not self.use_rope:
|
||||||
return q, k
|
return q, k
|
||||||
|
|
||||||
|
if self.use_ve_rope:
|
||||||
|
dtype = q.dtype
|
||||||
|
return self.rope(q).to(dtype), self.rope(k).to(dtype)
|
||||||
|
|
||||||
assert self.freqs_cis is not None
|
assert self.freqs_cis is not None
|
||||||
|
|
||||||
|
if self.use_rope_real:
|
||||||
|
return apply_rotary_enc_real(
|
||||||
|
q,
|
||||||
|
k,
|
||||||
|
freqs_cis_imag=self.freqs_cis_imag,
|
||||||
|
freqs_cis_real=self.freqs_cis_real,
|
||||||
|
)
|
||||||
return apply_rotary_enc(q, k, freqs_cis=self.freqs_cis)
|
return apply_rotary_enc(q, k, freqs_cis=self.freqs_cis)
|
||||||
|
|
||||||
def forward(self, x: Tensor) -> Tensor:
|
def forward(self, x: Tensor) -> Tensor:
|
||||||
@@ -501,7 +606,17 @@ class Attention(nn.Module):
|
|||||||
q = q.reshape(B, self.num_heads, H * W, -1)
|
q = q.reshape(B, self.num_heads, H * W, -1)
|
||||||
k = k.reshape(B, self.num_heads, H * W, -1)
|
k = k.reshape(B, self.num_heads, H * W, -1)
|
||||||
|
|
||||||
|
if self.attn_type == AttentionType.Vanilla:
|
||||||
|
if self.use_fa3:
|
||||||
|
from sam3.perflib.fa3 import flash_attn_func
|
||||||
|
|
||||||
|
x = flash_attn_func(
|
||||||
|
q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
|
||||||
|
).transpose(1, 2)
|
||||||
|
else:
|
||||||
x = F.scaled_dot_product_attention(q, k, v)
|
x = F.scaled_dot_product_attention(q, k, v)
|
||||||
|
else:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
if ndim == 4:
|
if ndim == 4:
|
||||||
x = (
|
x = (
|
||||||
@@ -541,6 +656,9 @@ class Block(nn.Module):
|
|||||||
cls_token: bool = False,
|
cls_token: bool = False,
|
||||||
dropout: float = 0.0,
|
dropout: float = 0.0,
|
||||||
init_values: Optional[float] = None,
|
init_values: Optional[float] = None,
|
||||||
|
attn_type: AttentionType = AttentionType.Vanilla,
|
||||||
|
use_fa3: bool = False,
|
||||||
|
use_rope_real: bool = False,
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Args:
|
Args:
|
||||||
@@ -561,8 +679,10 @@ class Block(nn.Module):
|
|||||||
cls_token: whether a cls_token is present.
|
cls_token: whether a cls_token is present.
|
||||||
use_rope: whether to use rope 2d (indep of use_rel_pos, as it can be used together)
|
use_rope: whether to use rope 2d (indep of use_rel_pos, as it can be used together)
|
||||||
rope_pt_size: size of rope in previous stage of training, needed for interpolation or tiling
|
rope_pt_size: size of rope in previous stage of training, needed for interpolation or tiling
|
||||||
|
rope_tiled: whether to tile rope or not; tile expected to be of size rope_pt_size x rope_pt_size
|
||||||
rope_interp: whether to interpolate (or extrapolate) rope to match target input size,
|
rope_interp: whether to interpolate (or extrapolate) rope to match target input size,
|
||||||
expected to specify source size as rope_pt_size.
|
expected to specify source size as rope_pt_size.
|
||||||
|
use_ve_rope: use ve orig rope implementation, if small numerical differences are important (normally not)
|
||||||
"""
|
"""
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.norm1 = norm_layer(dim)
|
self.norm1 = norm_layer(dim)
|
||||||
@@ -573,10 +693,15 @@ class Block(nn.Module):
|
|||||||
use_rel_pos=use_rel_pos,
|
use_rel_pos=use_rel_pos,
|
||||||
rel_pos_zero_init=rel_pos_zero_init,
|
rel_pos_zero_init=rel_pos_zero_init,
|
||||||
input_size=input_size if window_size == 0 else (window_size, window_size),
|
input_size=input_size if window_size == 0 else (window_size, window_size),
|
||||||
|
attn_type=attn_type,
|
||||||
use_rope=use_rope,
|
use_rope=use_rope,
|
||||||
rope_pt_size=rope_pt_size,
|
rope_pt_size=rope_pt_size,
|
||||||
|
rope_tiled=rope_tiled,
|
||||||
rope_interp=rope_interp,
|
rope_interp=rope_interp,
|
||||||
|
use_ve_rope=use_ve_rope,
|
||||||
cls_token=cls_token,
|
cls_token=cls_token,
|
||||||
|
use_fa3=use_fa3,
|
||||||
|
use_rope_real=use_rope_real,
|
||||||
)
|
)
|
||||||
self.ls1 = (
|
self.ls1 = (
|
||||||
LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
||||||
@@ -642,19 +767,24 @@ class ViT(nn.Module):
|
|||||||
window_size: int = 14,
|
window_size: int = 14,
|
||||||
global_att_blocks: Tuple[int, ...] = (2, 5, 8, 11),
|
global_att_blocks: Tuple[int, ...] = (2, 5, 8, 11),
|
||||||
use_rope: bool = False,
|
use_rope: bool = False,
|
||||||
|
use_tiled_rope: bool = False,
|
||||||
rope_pt_size: Optional[int] = None,
|
rope_pt_size: Optional[int] = None,
|
||||||
use_interp_rope: bool = False,
|
use_interp_rope: bool = False,
|
||||||
|
use_ve_rope: bool = False,
|
||||||
|
use_act_checkpoint: bool = True,
|
||||||
pretrain_img_size: int = 224,
|
pretrain_img_size: int = 224,
|
||||||
pretrain_use_cls_token: bool = True,
|
pretrain_use_cls_token: bool = True,
|
||||||
retain_cls_token: bool = True,
|
retain_cls_token: bool = True,
|
||||||
dropout: float = 0.0,
|
dropout: float = 0.0,
|
||||||
return_interm_layers: bool = False,
|
return_interm_layers: bool = False,
|
||||||
init_values: Optional[float] = None, # for layerscale
|
init_values: Optional[float] = None, # for layerscale
|
||||||
|
attn_type: AttentionType = AttentionType.Vanilla,
|
||||||
ln_pre: bool = False,
|
ln_pre: bool = False,
|
||||||
ln_post: bool = False,
|
ln_post: bool = False,
|
||||||
bias_patch_embed: bool = True,
|
bias_patch_embed: bool = True,
|
||||||
compile_mode: Optional[str] = None,
|
compile_mode: Optional[str] = None,
|
||||||
use_act_checkpoint: bool = True,
|
use_fa3: bool = False,
|
||||||
|
use_rope_real: bool = False,
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
Args:
|
Args:
|
||||||
@@ -708,9 +838,9 @@ class ViT(nn.Module):
|
|||||||
self.retain_cls_token = retain_cls_token
|
self.retain_cls_token = retain_cls_token
|
||||||
if self.retain_cls_token:
|
if self.retain_cls_token:
|
||||||
assert pretrain_use_cls_token
|
assert pretrain_use_cls_token
|
||||||
assert len(window_block_indexes) == 0, (
|
assert (
|
||||||
"windowing not supported with cls token"
|
len(window_block_indexes) == 0
|
||||||
)
|
), "windowing not supported with cls token"
|
||||||
|
|
||||||
assert sum(self.rel_pos_blocks) == 0, "rel pos not supported with cls token"
|
assert sum(self.rel_pos_blocks) == 0, "rel pos not supported with cls token"
|
||||||
|
|
||||||
@@ -768,10 +898,15 @@ class ViT(nn.Module):
|
|||||||
if rope_pt_size is None
|
if rope_pt_size is None
|
||||||
else (rope_pt_size, rope_pt_size)
|
else (rope_pt_size, rope_pt_size)
|
||||||
),
|
),
|
||||||
|
rope_tiled=use_tiled_rope,
|
||||||
|
use_ve_rope=use_ve_rope,
|
||||||
rope_interp=use_interp_rope,
|
rope_interp=use_interp_rope,
|
||||||
cls_token=self.retain_cls_token,
|
cls_token=self.retain_cls_token,
|
||||||
dropout=dropout,
|
dropout=dropout,
|
||||||
init_values=init_values,
|
init_values=init_values,
|
||||||
|
attn_type=attn_type,
|
||||||
|
use_fa3=use_fa3,
|
||||||
|
use_rope_real=use_rope_real,
|
||||||
)
|
)
|
||||||
|
|
||||||
if i not in window_block_indexes:
|
if i not in window_block_indexes:
|
||||||
@@ -812,7 +947,14 @@ class ViT(nn.Module):
|
|||||||
nn.init.constant_(m.bias, 0)
|
nn.init.constant_(m.bias, 0)
|
||||||
nn.init.constant_(m.weight, 1.0)
|
nn.init.constant_(m.weight, 1.0)
|
||||||
|
|
||||||
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
|
def forward(self, tensor_list):
|
||||||
|
if isinstance(tensor_list, NestedTensor):
|
||||||
|
x = tensor_list.tensors
|
||||||
|
mask = tensor_list.mask
|
||||||
|
else:
|
||||||
|
x = tensor_list
|
||||||
|
mask = None
|
||||||
|
|
||||||
x = self.patch_embed(x)
|
x = self.patch_embed(x)
|
||||||
h, w = x.shape[1], x.shape[2]
|
h, w = x.shape[1], x.shape[2]
|
||||||
|
|
||||||
@@ -835,6 +977,7 @@ class ViT(nn.Module):
|
|||||||
x = self.ln_pre(x)
|
x = self.ln_pre(x)
|
||||||
|
|
||||||
outputs = []
|
outputs = []
|
||||||
|
masks = None
|
||||||
for i, blk in enumerate(self.blocks):
|
for i, blk in enumerate(self.blocks):
|
||||||
if self.use_act_checkpoint and self.training:
|
if self.use_act_checkpoint and self.training:
|
||||||
x = checkpoint.checkpoint(blk, x, use_reentrant=False)
|
x = checkpoint.checkpoint(blk, x, use_reentrant=False)
|
||||||
@@ -856,6 +999,14 @@ class ViT(nn.Module):
|
|||||||
feats.shape[0], h, w, feats.shape[-1]
|
feats.shape[0], h, w, feats.shape[-1]
|
||||||
).permute(0, 3, 1, 2)
|
).permute(0, 3, 1, 2)
|
||||||
|
|
||||||
|
if isinstance(tensor_list, NestedTensor):
|
||||||
|
# Optimization, if the mask is all False, just ignore it
|
||||||
|
if mask is not None and mask.any() and masks is None:
|
||||||
|
masks = F.interpolate(
|
||||||
|
mask[None].float(), size=feats.shape[-2:]
|
||||||
|
).bool()[0]
|
||||||
|
outputs.append(NestedTensor(feats, masks))
|
||||||
|
else:
|
||||||
outputs.append(feats)
|
outputs.append(feats)
|
||||||
|
|
||||||
return outputs
|
return outputs
|
||||||
|
|||||||
+254
-1
@@ -12,7 +12,8 @@ import torch.nn as nn
|
|||||||
from torch.nn.attention import sdpa_kernel, SDPBackend
|
from torch.nn.attention import sdpa_kernel, SDPBackend
|
||||||
|
|
||||||
from .act_ckpt_utils import activation_ckpt_wrapper
|
from .act_ckpt_utils import activation_ckpt_wrapper
|
||||||
from .necks import Sam3DualViTDetNeck
|
from .data_misc import NestedTensor
|
||||||
|
from .necks import Sam3DualViTDetNeck, Sam3TriViTDetNeck
|
||||||
|
|
||||||
|
|
||||||
class SAM3VLBackbone(nn.Module):
|
class SAM3VLBackbone(nn.Module):
|
||||||
@@ -175,3 +176,255 @@ class SAM3VLBackbone(nn.Module):
|
|||||||
)
|
)
|
||||||
|
|
||||||
return output
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
class SAM3VLBackboneTri(SAM3VLBackbone):
|
||||||
|
"""VL backbone with triple-head vision (sam3, interactive, propagation) + text encoder."""
|
||||||
|
|
||||||
|
def __init__(self, visual, text, compile_visual=False, scalp=0):
|
||||||
|
super().__init__(
|
||||||
|
visual=visual, text=text, compile_visual=compile_visual, scalp=scalp
|
||||||
|
)
|
||||||
|
assert isinstance(
|
||||||
|
self.vision_backbone, Sam3TriViTDetNeck
|
||||||
|
), f"Expected vision backbone to be of type Sam3TriViTDetNeck, got {type(self.vision_backbone)}"
|
||||||
|
|
||||||
|
def forward_image(
|
||||||
|
self,
|
||||||
|
samples,
|
||||||
|
*,
|
||||||
|
need_sam3_out: bool = True,
|
||||||
|
need_interactive_out: bool = True,
|
||||||
|
need_propagation_out: bool = True,
|
||||||
|
):
|
||||||
|
return activation_ckpt_wrapper(self._forward_image_tri_no_act_ckpt)(
|
||||||
|
samples=samples,
|
||||||
|
need_sam3_out=need_sam3_out,
|
||||||
|
need_interactive_out=need_interactive_out,
|
||||||
|
need_propagation_out=need_propagation_out,
|
||||||
|
act_ckpt_enable=self.act_ckpt_whole_vision_backbone and self.training,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _forward_image_tri_no_act_ckpt(
|
||||||
|
self,
|
||||||
|
samples,
|
||||||
|
need_sam3_out=True,
|
||||||
|
need_interactive_out=True,
|
||||||
|
need_propagation_out=True,
|
||||||
|
):
|
||||||
|
(
|
||||||
|
sam3_features,
|
||||||
|
sam3_pos,
|
||||||
|
interactive_features,
|
||||||
|
interactive_pos,
|
||||||
|
propagation_features,
|
||||||
|
propagation_pos,
|
||||||
|
) = self.vision_backbone.forward(
|
||||||
|
samples,
|
||||||
|
need_sam3_out=need_sam3_out,
|
||||||
|
need_interactive_out=need_interactive_out,
|
||||||
|
need_propagation_out=need_propagation_out,
|
||||||
|
)
|
||||||
|
if self.scalp > 0:
|
||||||
|
sam3_features, sam3_pos = (
|
||||||
|
sam3_features[: -self.scalp],
|
||||||
|
sam3_pos[: -self.scalp],
|
||||||
|
)
|
||||||
|
interactive_features, interactive_pos = (
|
||||||
|
interactive_features[: -self.scalp],
|
||||||
|
interactive_pos[: -self.scalp],
|
||||||
|
)
|
||||||
|
propagation_features, propagation_pos = (
|
||||||
|
propagation_features[: -self.scalp],
|
||||||
|
propagation_pos[: -self.scalp],
|
||||||
|
)
|
||||||
|
|
||||||
|
output = {}
|
||||||
|
if need_sam3_out:
|
||||||
|
sam3_last = sam3_features[-1]
|
||||||
|
output.update(
|
||||||
|
{
|
||||||
|
"vision_features": sam3_last.tensors,
|
||||||
|
"vision_mask": sam3_last.mask,
|
||||||
|
"vision_pos_enc": sam3_pos,
|
||||||
|
"backbone_fpn": sam3_features,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if need_interactive_out:
|
||||||
|
inte_last = interactive_features[-1]
|
||||||
|
output["interactive"] = {
|
||||||
|
"vision_features": inte_last.tensors,
|
||||||
|
"vision_mask": inte_last.mask,
|
||||||
|
"vision_pos_enc": interactive_pos,
|
||||||
|
"backbone_fpn": interactive_features,
|
||||||
|
}
|
||||||
|
if need_propagation_out:
|
||||||
|
prop_last = propagation_features[-1]
|
||||||
|
output["sam2_backbone_out"] = {
|
||||||
|
"vision_features": prop_last.tensors,
|
||||||
|
"vision_mask": prop_last.mask,
|
||||||
|
"vision_pos_enc": propagation_pos,
|
||||||
|
"backbone_fpn": propagation_features,
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
class VisionOnly(nn.Module):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
visual,
|
||||||
|
n_features,
|
||||||
|
forward_in_chunk_for_eval=False,
|
||||||
|
eval_chunk_size=4,
|
||||||
|
eval_cast_to_cpu=False,
|
||||||
|
scalp=0,
|
||||||
|
compile_mode: str = None,
|
||||||
|
compile_extra_args: Optional[dict] = None,
|
||||||
|
):
|
||||||
|
super().__init__()
|
||||||
|
self.vision_backbone = visual
|
||||||
|
self.should_compile = compile_mode is not None or compile_extra_args is not None
|
||||||
|
self.compile_mode = compile_mode
|
||||||
|
self.compile_extra_args = compile_extra_args or {}
|
||||||
|
self.compiled = False
|
||||||
|
self.n_features = n_features
|
||||||
|
self.forward_in_chunk_for_eval = forward_in_chunk_for_eval
|
||||||
|
self.eval_chunk_size = eval_chunk_size
|
||||||
|
self.eval_cast_to_cpu = eval_cast_to_cpu
|
||||||
|
self.scalp = scalp
|
||||||
|
|
||||||
|
def _compile(self):
|
||||||
|
if self.should_compile and not self.compiled:
|
||||||
|
self.vision_backbone = torch.compile(
|
||||||
|
self.vision_backbone, mode=self.compile_mode, **self.compile_extra_args
|
||||||
|
)
|
||||||
|
self.compiled = True
|
||||||
|
|
||||||
|
def forward_image(self, samples):
|
||||||
|
self._compile()
|
||||||
|
# Forward through backbone
|
||||||
|
features, pos = self.vision_backbone(samples)
|
||||||
|
if self.scalp > 0:
|
||||||
|
features, pos = features[: -self.scalp], pos[: -self.scalp]
|
||||||
|
elif self.scalp < 0:
|
||||||
|
features.pop(self.scalp)
|
||||||
|
pos.pop(self.scalp)
|
||||||
|
|
||||||
|
src, mask = features[-1].decompose()
|
||||||
|
output = {
|
||||||
|
"vision_features": src,
|
||||||
|
"vision_mask": mask,
|
||||||
|
"vision_pos_enc": pos,
|
||||||
|
"backbone_fpn": features,
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
|
||||||
|
def forward_text(
|
||||||
|
self,
|
||||||
|
captions,
|
||||||
|
input_boxes=None,
|
||||||
|
additional_text=None,
|
||||||
|
device="cuda",
|
||||||
|
):
|
||||||
|
bs = len(captions)
|
||||||
|
output = {
|
||||||
|
"language_features": torch.zeros((0, bs, self.n_features), device=device),
|
||||||
|
"language_mask": torch.zeros((bs, 0), device=device),
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
class TriHeadVisionOnly(VisionOnly):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
visual,
|
||||||
|
n_features,
|
||||||
|
forward_in_chunk_for_eval=False,
|
||||||
|
eval_chunk_size=4,
|
||||||
|
eval_cast_to_cpu=False,
|
||||||
|
scalp=0,
|
||||||
|
compile_mode: str = None,
|
||||||
|
compile_extra_args: Optional[dict] = None,
|
||||||
|
):
|
||||||
|
super().__init__(
|
||||||
|
visual=visual,
|
||||||
|
n_features=n_features,
|
||||||
|
forward_in_chunk_for_eval=forward_in_chunk_for_eval,
|
||||||
|
eval_chunk_size=eval_chunk_size,
|
||||||
|
eval_cast_to_cpu=eval_cast_to_cpu,
|
||||||
|
scalp=scalp,
|
||||||
|
compile_mode=compile_mode,
|
||||||
|
compile_extra_args=compile_extra_args,
|
||||||
|
)
|
||||||
|
assert isinstance(
|
||||||
|
self.vision_backbone, Sam3TriViTDetNeck
|
||||||
|
), f"Expected vision backbone to be of type Sam3TriViTDetNeck, got {type(self.vision_backbone)}"
|
||||||
|
|
||||||
|
def forward_image(
|
||||||
|
self,
|
||||||
|
samples,
|
||||||
|
*,
|
||||||
|
need_sam3_out: bool = True,
|
||||||
|
need_interactive_out: bool = True,
|
||||||
|
need_propagation_out: bool = True,
|
||||||
|
):
|
||||||
|
self._compile()
|
||||||
|
# Forward through backbone
|
||||||
|
(
|
||||||
|
sam3_features,
|
||||||
|
sam3_pos,
|
||||||
|
interactive_features,
|
||||||
|
interactive_pos,
|
||||||
|
propagation_features,
|
||||||
|
propagation_pos,
|
||||||
|
) = self.vision_backbone(
|
||||||
|
samples,
|
||||||
|
need_sam3_out=need_sam3_out,
|
||||||
|
need_interactive_out=need_interactive_out,
|
||||||
|
need_propagation_out=need_propagation_out,
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.scalp > 0:
|
||||||
|
sam3_features, sam3_pos = (
|
||||||
|
sam3_features[: -self.scalp],
|
||||||
|
sam3_pos[: -self.scalp],
|
||||||
|
)
|
||||||
|
interactive_features, interactive_pos = (
|
||||||
|
interactive_features[: -self.scalp],
|
||||||
|
interactive_pos[: -self.scalp],
|
||||||
|
)
|
||||||
|
propagation_features, propagation_pos = (
|
||||||
|
propagation_features[: -self.scalp],
|
||||||
|
propagation_pos[: -self.scalp],
|
||||||
|
)
|
||||||
|
|
||||||
|
output = {}
|
||||||
|
|
||||||
|
if need_sam3_out:
|
||||||
|
sam3_last = sam3_features[-1]
|
||||||
|
output.update(
|
||||||
|
{
|
||||||
|
"vision_features": sam3_last.tensors,
|
||||||
|
"vision_mask": sam3_last.mask,
|
||||||
|
"vision_pos_enc": sam3_pos,
|
||||||
|
"backbone_fpn": sam3_features,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if need_interactive_out:
|
||||||
|
inte_last = interactive_features[-1]
|
||||||
|
output["interactive"] = {
|
||||||
|
"vision_features": inte_last.tensors,
|
||||||
|
"vision_mask": inte_last.mask,
|
||||||
|
"vision_pos_enc": interactive_pos,
|
||||||
|
"backbone_fpn": interactive_features,
|
||||||
|
}
|
||||||
|
if need_propagation_out:
|
||||||
|
prop_last = propagation_features[-1]
|
||||||
|
output["sam2_backbone_out"] = {
|
||||||
|
"vision_features": prop_last.tensors,
|
||||||
|
"vision_mask": prop_last.mask,
|
||||||
|
"vision_pos_enc": propagation_pos,
|
||||||
|
"backbone_fpn": propagation_features,
|
||||||
|
}
|
||||||
|
|
||||||
|
return output
|
||||||
|
|||||||
+538
-17
@@ -11,10 +11,13 @@ import torch.nn as nn
|
|||||||
from huggingface_hub import hf_hub_download
|
from huggingface_hub import hf_hub_download
|
||||||
from iopath.common.file_io import g_pathmgr
|
from iopath.common.file_io import g_pathmgr
|
||||||
from sam3.model.decoder import (
|
from sam3.model.decoder import (
|
||||||
|
DecoupledTransformerDecoderLayerv2,
|
||||||
|
SimpleRoPEAttention,
|
||||||
TransformerDecoder,
|
TransformerDecoder,
|
||||||
TransformerDecoderLayer,
|
TransformerDecoderLayer,
|
||||||
TransformerDecoderLayerv2,
|
TransformerDecoderLayerv2,
|
||||||
TransformerEncoderCrossAttention,
|
TransformerEncoderCrossAttention,
|
||||||
|
TransformerEncoderDecoupledCrossAttention,
|
||||||
)
|
)
|
||||||
from sam3.model.encoder import TransformerEncoderFusion, TransformerEncoderLayer
|
from sam3.model.encoder import TransformerEncoderFusion, TransformerEncoderLayer
|
||||||
from sam3.model.geometry_encoders import SequenceGeometryEncoder
|
from sam3.model.geometry_encoders import SequenceGeometryEncoder
|
||||||
@@ -31,7 +34,8 @@ from sam3.model.model_misc import (
|
|||||||
MultiheadAttentionWrapper as MultiheadAttention,
|
MultiheadAttentionWrapper as MultiheadAttention,
|
||||||
TransformerWrapper,
|
TransformerWrapper,
|
||||||
)
|
)
|
||||||
from sam3.model.necks import Sam3DualViTDetNeck
|
from sam3.model.multiplex_utils import MultiplexController
|
||||||
|
from sam3.model.necks import Sam3DualViTDetNeck, Sam3TriViTDetNeck
|
||||||
from sam3.model.position_encoding import PositionEmbeddingSine
|
from sam3.model.position_encoding import PositionEmbeddingSine
|
||||||
from sam3.model.sam1_task_predictor import SAM3InteractiveImagePredictor
|
from sam3.model.sam1_task_predictor import SAM3InteractiveImagePredictor
|
||||||
from sam3.model.sam3_image import Sam3Image, Sam3ImageOnVideoMultiGPU
|
from sam3.model.sam3_image import Sam3Image, Sam3ImageOnVideoMultiGPU
|
||||||
@@ -40,8 +44,9 @@ from sam3.model.sam3_video_inference import Sam3VideoInferenceWithInstanceIntera
|
|||||||
from sam3.model.sam3_video_predictor import Sam3VideoPredictorMultiGPU
|
from sam3.model.sam3_video_predictor import Sam3VideoPredictorMultiGPU
|
||||||
from sam3.model.text_encoder_ve import VETextEncoder
|
from sam3.model.text_encoder_ve import VETextEncoder
|
||||||
from sam3.model.tokenizer_ve import SimpleTokenizer
|
from sam3.model.tokenizer_ve import SimpleTokenizer
|
||||||
|
from sam3.model.video_tracking_multiplex import VideoTrackingDynamicMultiplex
|
||||||
from sam3.model.vitdet import ViT
|
from sam3.model.vitdet import ViT
|
||||||
from sam3.model.vl_combiner import SAM3VLBackbone
|
from sam3.model.vl_combiner import SAM3VLBackbone, SAM3VLBackboneTri, TriHeadVisionOnly
|
||||||
from sam3.sam.transformer import RoPEAttention
|
from sam3.sam.transformer import RoPEAttention
|
||||||
|
|
||||||
|
|
||||||
@@ -69,7 +74,7 @@ def _create_position_encoding(precompute_resolution=None):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _create_vit_backbone(compile_mode=None):
|
def _create_vit_backbone(compile_mode=None, use_fa3=False, use_rope_real=False):
|
||||||
"""Create ViT backbone for visual feature extraction."""
|
"""Create ViT backbone for visual feature extraction."""
|
||||||
return ViT(
|
return ViT(
|
||||||
img_size=1008,
|
img_size=1008,
|
||||||
@@ -96,6 +101,8 @@ def _create_vit_backbone(compile_mode=None):
|
|||||||
return_interm_layers=False,
|
return_interm_layers=False,
|
||||||
bias_patch_embed=False,
|
bias_patch_embed=False,
|
||||||
compile_mode=compile_mode,
|
compile_mode=compile_mode,
|
||||||
|
use_fa3=use_fa3,
|
||||||
|
use_rope_real=use_rope_real,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -115,7 +122,7 @@ def _create_vl_backbone(vit_neck, text_encoder):
|
|||||||
return SAM3VLBackbone(visual=vit_neck, text=text_encoder, scalp=1)
|
return SAM3VLBackbone(visual=vit_neck, text=text_encoder, scalp=1)
|
||||||
|
|
||||||
|
|
||||||
def _create_transformer_encoder() -> TransformerEncoderFusion:
|
def _create_transformer_encoder(use_fa3=False) -> TransformerEncoderFusion:
|
||||||
"""Create transformer encoder with its layer."""
|
"""Create transformer encoder with its layer."""
|
||||||
encoder_layer = TransformerEncoderLayer(
|
encoder_layer = TransformerEncoderLayer(
|
||||||
activation="relu",
|
activation="relu",
|
||||||
@@ -131,12 +138,14 @@ def _create_transformer_encoder() -> TransformerEncoderFusion:
|
|||||||
dropout=0.1,
|
dropout=0.1,
|
||||||
embed_dim=256,
|
embed_dim=256,
|
||||||
batch_first=True,
|
batch_first=True,
|
||||||
|
use_fa3=use_fa3,
|
||||||
),
|
),
|
||||||
cross_attention=MultiheadAttention(
|
cross_attention=MultiheadAttention(
|
||||||
num_heads=8,
|
num_heads=8,
|
||||||
dropout=0.1,
|
dropout=0.1,
|
||||||
embed_dim=256,
|
embed_dim=256,
|
||||||
batch_first=True,
|
batch_first=True,
|
||||||
|
use_fa3=use_fa3,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -153,7 +162,7 @@ def _create_transformer_encoder() -> TransformerEncoderFusion:
|
|||||||
return encoder
|
return encoder
|
||||||
|
|
||||||
|
|
||||||
def _create_transformer_decoder() -> TransformerDecoder:
|
def _create_transformer_decoder(use_fa3=False) -> TransformerDecoder:
|
||||||
"""Create transformer decoder with its layer."""
|
"""Create transformer decoder with its layer."""
|
||||||
decoder_layer = TransformerDecoderLayer(
|
decoder_layer = TransformerDecoderLayer(
|
||||||
activation="relu",
|
activation="relu",
|
||||||
@@ -164,6 +173,7 @@ def _create_transformer_decoder() -> TransformerDecoder:
|
|||||||
num_heads=8,
|
num_heads=8,
|
||||||
dropout=0.1,
|
dropout=0.1,
|
||||||
embed_dim=256,
|
embed_dim=256,
|
||||||
|
use_fa3=use_fa3,
|
||||||
),
|
),
|
||||||
n_heads=8,
|
n_heads=8,
|
||||||
use_text_cross_attention=True,
|
use_text_cross_attention=True,
|
||||||
@@ -204,7 +214,7 @@ def _create_dot_product_scoring():
|
|||||||
return DotProductScoring(d_model=256, d_proj=256, prompt_mlp=prompt_mlp)
|
return DotProductScoring(d_model=256, d_proj=256, prompt_mlp=prompt_mlp)
|
||||||
|
|
||||||
|
|
||||||
def _create_segmentation_head(compile_mode=None):
|
def _create_segmentation_head(compile_mode=None, use_fa3=False):
|
||||||
"""Create segmentation head with pixel decoder."""
|
"""Create segmentation head with pixel decoder."""
|
||||||
pixel_decoder = PixelDecoder(
|
pixel_decoder = PixelDecoder(
|
||||||
num_upsampling_stages=3,
|
num_upsampling_stages=3,
|
||||||
@@ -217,6 +227,7 @@ def _create_segmentation_head(compile_mode=None):
|
|||||||
num_heads=8,
|
num_heads=8,
|
||||||
dropout=0,
|
dropout=0,
|
||||||
embed_dim=256,
|
embed_dim=256,
|
||||||
|
use_fa3=use_fa3,
|
||||||
)
|
)
|
||||||
|
|
||||||
segmentation_head = UniversalSegmentationHead(
|
segmentation_head = UniversalSegmentationHead(
|
||||||
@@ -515,10 +526,12 @@ def _create_vision_backbone(
|
|||||||
return vit_neck
|
return vit_neck
|
||||||
|
|
||||||
|
|
||||||
def _create_sam3_transformer(has_presence_token: bool = True) -> TransformerWrapper:
|
def _create_sam3_transformer(
|
||||||
|
has_presence_token: bool = True, use_fa3: bool = False
|
||||||
|
) -> TransformerWrapper:
|
||||||
"""Create SAM3 transformer encoder and decoder."""
|
"""Create SAM3 transformer encoder and decoder."""
|
||||||
encoder: TransformerEncoderFusion = _create_transformer_encoder()
|
encoder: TransformerEncoderFusion = _create_transformer_encoder(use_fa3=use_fa3)
|
||||||
decoder: TransformerDecoder = _create_transformer_decoder()
|
decoder: TransformerDecoder = _create_transformer_decoder(use_fa3=use_fa3)
|
||||||
|
|
||||||
return TransformerWrapper(encoder=encoder, decoder=decoder, d_model=256)
|
return TransformerWrapper(encoder=encoder, decoder=decoder, d_model=256)
|
||||||
|
|
||||||
@@ -630,7 +643,7 @@ def build_sam3_image_model(
|
|||||||
eval_mode,
|
eval_mode,
|
||||||
)
|
)
|
||||||
if load_from_HF and checkpoint_path is None:
|
if load_from_HF and checkpoint_path is None:
|
||||||
checkpoint_path = download_ckpt_from_hf()
|
checkpoint_path = download_ckpt_from_hf(version="sam3")
|
||||||
# Load checkpoint if provided
|
# Load checkpoint if provided
|
||||||
if checkpoint_path is not None:
|
if checkpoint_path is not None:
|
||||||
_load_checkpoint(model, checkpoint_path)
|
_load_checkpoint(model, checkpoint_path)
|
||||||
@@ -641,12 +654,22 @@ def build_sam3_image_model(
|
|||||||
return model
|
return model
|
||||||
|
|
||||||
|
|
||||||
def download_ckpt_from_hf():
|
def download_ckpt_from_hf(version="sam3"):
|
||||||
SAM3_MODEL_ID = "facebook/sam3"
|
"""Download model checkpoint from HuggingFace Hub.
|
||||||
SAM3_CKPT_NAME = "sam3.pt"
|
|
||||||
SAM3_CFG_NAME = "config.json"
|
Args:
|
||||||
_ = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CFG_NAME)
|
version: "sam3" or "sam3.1"
|
||||||
checkpoint_path = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CKPT_NAME)
|
"""
|
||||||
|
if version == "sam3.1":
|
||||||
|
repo_id = "facebook/sam3.1"
|
||||||
|
ckpt_name = "sam3.1_multiplex.pt"
|
||||||
|
cfg_name = "config.json"
|
||||||
|
else:
|
||||||
|
repo_id = "facebook/sam3"
|
||||||
|
ckpt_name = "sam3.pt"
|
||||||
|
cfg_name = "config.json"
|
||||||
|
_ = hf_hub_download(repo_id=repo_id, filename=cfg_name)
|
||||||
|
checkpoint_path = hf_hub_download(repo_id=repo_id, filename=ckpt_name)
|
||||||
return checkpoint_path
|
return checkpoint_path
|
||||||
|
|
||||||
|
|
||||||
@@ -772,7 +795,7 @@ def build_sam3_video_model(
|
|||||||
|
|
||||||
# Load checkpoint if provided
|
# Load checkpoint if provided
|
||||||
if load_from_HF and checkpoint_path is None:
|
if load_from_HF and checkpoint_path is None:
|
||||||
checkpoint_path = download_ckpt_from_hf()
|
checkpoint_path = download_ckpt_from_hf(version="sam3")
|
||||||
if checkpoint_path is not None:
|
if checkpoint_path is not None:
|
||||||
with g_pathmgr.open(checkpoint_path, "rb") as f:
|
with g_pathmgr.open(checkpoint_path, "rb") as f:
|
||||||
ckpt = torch.load(f, map_location="cpu", weights_only=True)
|
ckpt = torch.load(f, map_location="cpu", weights_only=True)
|
||||||
@@ -795,3 +818,501 @@ def build_sam3_video_predictor(*model_args, gpus_to_use=None, **model_kwargs):
|
|||||||
return Sam3VideoPredictorMultiGPU(
|
return Sam3VideoPredictorMultiGPU(
|
||||||
*model_args, gpus_to_use=gpus_to_use, **model_kwargs
|
*model_args, gpus_to_use=gpus_to_use, **model_kwargs
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _create_multiplex_maskmem_backbone(multiplex_count=16):
|
||||||
|
"""Create the multiplex memory encoder with per-object mask channels."""
|
||||||
|
position_encoding = PositionEmbeddingSine(
|
||||||
|
num_pos_feats=256,
|
||||||
|
normalize=True,
|
||||||
|
scale=None,
|
||||||
|
temperature=10000,
|
||||||
|
precompute_resolution=1008,
|
||||||
|
)
|
||||||
|
|
||||||
|
mask_downsampler = SimpleMaskDownSampler(
|
||||||
|
kernel_size=3,
|
||||||
|
stride=2,
|
||||||
|
padding=1,
|
||||||
|
interpol_size=[1152, 1152],
|
||||||
|
multiplex_count=multiplex_count,
|
||||||
|
starting_out_chan=4,
|
||||||
|
input_channel_multiplier=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
cx_block_layer = CXBlock(
|
||||||
|
dim=256,
|
||||||
|
kernel_size=7,
|
||||||
|
padding=3,
|
||||||
|
layer_scale_init_value=1.0e-06,
|
||||||
|
use_dwconv=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
fuser = SimpleFuser(layer=cx_block_layer, num_layers=2)
|
||||||
|
|
||||||
|
maskmem_backbone = SimpleMaskEncoder(
|
||||||
|
out_dim=256,
|
||||||
|
position_encoding=position_encoding,
|
||||||
|
mask_downsampler=mask_downsampler,
|
||||||
|
fuser=fuser,
|
||||||
|
)
|
||||||
|
|
||||||
|
return maskmem_backbone
|
||||||
|
|
||||||
|
|
||||||
|
def _create_multiplex_transformer(use_fa3=False, use_rope_real=False):
|
||||||
|
"""Create the decoupled transformer for multiplex memory attention."""
|
||||||
|
self_attention_rope = SimpleRoPEAttention(
|
||||||
|
d_model=256,
|
||||||
|
num_heads=8,
|
||||||
|
dropout_p=0.1,
|
||||||
|
rope_theta=10000.0,
|
||||||
|
feat_sizes=[72, 72],
|
||||||
|
use_fa3=use_fa3,
|
||||||
|
use_rope_real=use_rope_real,
|
||||||
|
)
|
||||||
|
|
||||||
|
cross_attention_rope = SimpleRoPEAttention(
|
||||||
|
d_model=256,
|
||||||
|
num_heads=8,
|
||||||
|
dropout_p=0.1,
|
||||||
|
rope_theta=10000.0,
|
||||||
|
feat_sizes=[72, 72],
|
||||||
|
rope_k_repeat=True,
|
||||||
|
use_fa3=use_fa3,
|
||||||
|
use_rope_real=use_rope_real,
|
||||||
|
)
|
||||||
|
|
||||||
|
encoder_layer = DecoupledTransformerDecoderLayerv2(
|
||||||
|
activation="gelu",
|
||||||
|
d_model=256,
|
||||||
|
num_heads=8,
|
||||||
|
dropout=0.1,
|
||||||
|
dim_feedforward=2048,
|
||||||
|
pos_enc_at_attn=False,
|
||||||
|
pre_norm=True,
|
||||||
|
pos_enc_at_cross_attn_keys=True,
|
||||||
|
pos_enc_at_cross_attn_queries=False,
|
||||||
|
self_attention_rope=self_attention_rope,
|
||||||
|
cross_attention_rope=cross_attention_rope,
|
||||||
|
)
|
||||||
|
|
||||||
|
encoder = TransformerEncoderDecoupledCrossAttention(
|
||||||
|
d_model=256,
|
||||||
|
frozen=False,
|
||||||
|
pos_enc_at_input=True,
|
||||||
|
use_image_in_output=False,
|
||||||
|
layer=encoder_layer,
|
||||||
|
num_layers=4,
|
||||||
|
use_act_checkpoint=False,
|
||||||
|
batch_first=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
transformer = TransformerWrapper(
|
||||||
|
encoder=encoder,
|
||||||
|
decoder=None,
|
||||||
|
d_model=256,
|
||||||
|
)
|
||||||
|
|
||||||
|
return transformer
|
||||||
|
|
||||||
|
|
||||||
|
def _create_multiplex_tri_backbone(
|
||||||
|
compile_mode=None, use_fa3=False, use_rope_real=False
|
||||||
|
):
|
||||||
|
"""Create the TriHead vision backbone for multiplex model."""
|
||||||
|
position_encoding = _create_position_encoding(precompute_resolution=1008)
|
||||||
|
vit_backbone = _create_vit_backbone(
|
||||||
|
compile_mode=compile_mode, use_fa3=use_fa3, use_rope_real=use_rope_real
|
||||||
|
)
|
||||||
|
tri_neck = Sam3TriViTDetNeck(
|
||||||
|
trunk=vit_backbone,
|
||||||
|
position_encoding=position_encoding,
|
||||||
|
d_model=256,
|
||||||
|
scale_factors=[4.0, 2.0, 1.0],
|
||||||
|
)
|
||||||
|
return tri_neck
|
||||||
|
|
||||||
|
|
||||||
|
def build_sam3_multiplex_video_model(
|
||||||
|
checkpoint_path: Optional[str] = None,
|
||||||
|
load_from_HF=True,
|
||||||
|
multiplex_count: int = 16,
|
||||||
|
use_fa3: bool = False,
|
||||||
|
use_rope_real: bool = False,
|
||||||
|
strict_state_dict_loading: bool = True,
|
||||||
|
device="cuda" if torch.cuda.is_available() else "cpu",
|
||||||
|
compile=False,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Build SAM3 multiplex video tracking model.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
checkpoint_path: Optional path to checkpoint file
|
||||||
|
multiplex_count: Number of objects per multiplex bucket
|
||||||
|
use_fa3: Whether to use FlashAttention 3
|
||||||
|
use_rope_real: Whether to use real-valued RoPE (for compile compat)
|
||||||
|
strict_state_dict_loading: Whether to use strict state dict loading
|
||||||
|
device: Device to place model on
|
||||||
|
compile: Whether to compile model components
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
VideoTrackingDynamicMultiplex: The instantiated multiplex tracking model
|
||||||
|
"""
|
||||||
|
# Build multiplex-specific components
|
||||||
|
maskmem_backbone = _create_multiplex_maskmem_backbone(
|
||||||
|
multiplex_count=multiplex_count
|
||||||
|
)
|
||||||
|
transformer = _create_multiplex_transformer(
|
||||||
|
use_fa3=use_fa3, use_rope_real=use_rope_real
|
||||||
|
)
|
||||||
|
tri_neck = _create_multiplex_tri_backbone(
|
||||||
|
compile_mode="max-autotune" if compile else None
|
||||||
|
)
|
||||||
|
backbone = TriHeadVisionOnly(
|
||||||
|
visual=tri_neck,
|
||||||
|
n_features=256,
|
||||||
|
scalp=0,
|
||||||
|
)
|
||||||
|
multiplex_controller = MultiplexController(
|
||||||
|
multiplex_count=multiplex_count,
|
||||||
|
eval_multiplex_count=multiplex_count,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Build the multiplex model (use demo class for init_state and other demo methods)
|
||||||
|
from sam3.model.video_tracking_multiplex_demo import Sam3VideoTrackingMultiplexDemo
|
||||||
|
|
||||||
|
model = Sam3VideoTrackingMultiplexDemo(
|
||||||
|
backbone=backbone,
|
||||||
|
transformer=transformer,
|
||||||
|
maskmem_backbone=maskmem_backbone,
|
||||||
|
multiplex_controller=multiplex_controller,
|
||||||
|
image_size=1008,
|
||||||
|
backbone_stride=14,
|
||||||
|
num_maskmem=7,
|
||||||
|
# Multiplex-specific settings
|
||||||
|
use_high_res_features_in_sam=True,
|
||||||
|
use_obj_ptrs_in_encoder=True,
|
||||||
|
max_obj_ptrs_in_encoder=16,
|
||||||
|
add_tpos_enc_to_obj_ptrs=True,
|
||||||
|
proj_tpos_enc_in_obj_ptrs=True,
|
||||||
|
use_mlp_for_obj_ptr_proj=True,
|
||||||
|
pred_obj_scores=True,
|
||||||
|
pred_obj_scores_mlp=True,
|
||||||
|
fixed_no_obj_ptr=True,
|
||||||
|
use_no_obj_ptr=True,
|
||||||
|
use_linear_no_obj_ptr=True,
|
||||||
|
no_obj_embed_spatial=True,
|
||||||
|
sincos_tpos_enc=True,
|
||||||
|
# Multimask settings
|
||||||
|
multimask_output_in_sam=True,
|
||||||
|
multimask_output_for_tracking=True,
|
||||||
|
multimask_min_pt_num=0,
|
||||||
|
multimask_max_pt_num=1,
|
||||||
|
use_multimask_token_for_obj_ptr=True,
|
||||||
|
num_multimask_outputs=3,
|
||||||
|
# Memory encoder settings
|
||||||
|
apply_sigmoid_to_mask_logits_for_mem_enc=True,
|
||||||
|
sigmoid_scale_for_mem_enc=2.0,
|
||||||
|
sigmoid_bias_for_mem_enc=-1.0,
|
||||||
|
non_overlap_masks_for_mem_enc=False,
|
||||||
|
# Suppression/conditional embeddings
|
||||||
|
add_output_suppression_embeddings=True,
|
||||||
|
add_object_conditional_embeddings=False,
|
||||||
|
condition_as_mask_input=True,
|
||||||
|
condition_as_mask_input_fg=1.0,
|
||||||
|
condition_as_mask_input_bg=0.0,
|
||||||
|
# Memory settings
|
||||||
|
use_maskmem_tpos_v2=True,
|
||||||
|
save_image_features=True,
|
||||||
|
randomness_fix=True,
|
||||||
|
# Interaction settings
|
||||||
|
use_mask_input_as_output_without_sam=True,
|
||||||
|
directly_add_no_mem_embed=True,
|
||||||
|
iou_prediction_use_sigmoid=False,
|
||||||
|
forward_backbone_per_frame_for_eval=True,
|
||||||
|
offload_output_to_cpu_for_eval=False,
|
||||||
|
trim_past_non_cond_mem_for_eval=False,
|
||||||
|
max_cond_frames_in_attn=4,
|
||||||
|
# Dynamic multiplex settings
|
||||||
|
is_dynamic_model=True,
|
||||||
|
# SAM mask decoder extra args
|
||||||
|
sam_mask_decoder_extra_args={
|
||||||
|
"dynamic_multimask_via_stability": True,
|
||||||
|
"dynamic_multimask_stability_delta": 0.05,
|
||||||
|
"dynamic_multimask_stability_thresh": 0.98,
|
||||||
|
},
|
||||||
|
compile_all_components=compile,
|
||||||
|
use_memory_selection=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Load checkpoint if provided
|
||||||
|
if load_from_HF and checkpoint_path is None:
|
||||||
|
checkpoint_path = download_ckpt_from_hf(version="sam3.1")
|
||||||
|
if checkpoint_path is not None:
|
||||||
|
with g_pathmgr.open(checkpoint_path, "rb") as f:
|
||||||
|
ckpt = torch.load(f, map_location="cpu", weights_only=True)
|
||||||
|
if "model" in ckpt and isinstance(ckpt["model"], dict):
|
||||||
|
ckpt = ckpt["model"]
|
||||||
|
|
||||||
|
missing_keys, unexpected_keys = model.load_state_dict(
|
||||||
|
ckpt, strict=strict_state_dict_loading
|
||||||
|
)
|
||||||
|
if missing_keys:
|
||||||
|
print(f"Missing keys: {missing_keys}")
|
||||||
|
if unexpected_keys:
|
||||||
|
print(f"Unexpected keys: {unexpected_keys}")
|
||||||
|
|
||||||
|
model.to(device=device)
|
||||||
|
return model
|
||||||
|
|
||||||
|
|
||||||
|
def build_sam3_multiplex_video_predictor(
|
||||||
|
checkpoint_path: Optional[str] = None,
|
||||||
|
bpe_path: Optional[str] = None,
|
||||||
|
max_num_objects: int = 16,
|
||||||
|
multiplex_count: int = 16,
|
||||||
|
use_fa3: bool = True,
|
||||||
|
use_rope_real: bool = True,
|
||||||
|
compile: bool = False,
|
||||||
|
warm_up: bool = False,
|
||||||
|
session_expiration_sec: int = 1200,
|
||||||
|
default_output_prob_thresh: float = 0.5,
|
||||||
|
async_loading_frames: bool = True,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Build a fully-initialized Sam3MultiplexVideoPredictor.
|
||||||
|
|
||||||
|
This is the recommended entry point for SAM 3.1 multiplex video tracking.
|
||||||
|
It builds the full model stack (tracker + detector + demo model), loads
|
||||||
|
the checkpoint, and wraps everything in Sam3MultiplexVideoPredictor with
|
||||||
|
handle_request / handle_stream_request API.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
checkpoint_path: Path to the merged multiplex checkpoint
|
||||||
|
bpe_path: Path to the BPE tokenizer vocabulary
|
||||||
|
max_num_objects: Maximum number of tracked objects
|
||||||
|
multiplex_count: Number of objects per multiplex bucket
|
||||||
|
use_fa3: Whether to use FlashAttention 3
|
||||||
|
use_rope_real: Whether to use real-valued RoPE (for compile compat)
|
||||||
|
compile: Whether to enable torch.compile on model components
|
||||||
|
warm_up: Whether to run warm-up compilation (requires compile=True)
|
||||||
|
session_expiration_sec: Session expiration timeout in seconds
|
||||||
|
default_output_prob_thresh: Default probability threshold for output masks
|
||||||
|
async_loading_frames: Whether to load frames asynchronously
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Sam3MultiplexVideoPredictor: The fully-initialized predictor
|
||||||
|
"""
|
||||||
|
if bpe_path is None:
|
||||||
|
bpe_path = pkg_resources.resource_filename(
|
||||||
|
"sam3", "assets/bpe_simple_vocab_16e6.txt.gz"
|
||||||
|
)
|
||||||
|
|
||||||
|
from sam3.model.sam3_multiplex_base import Sam3MultiplexPredictorWrapper
|
||||||
|
from sam3.model.sam3_multiplex_detector import Sam3MultiplexDetector
|
||||||
|
from sam3.model.sam3_multiplex_tracking import (
|
||||||
|
Sam3MultiplexTrackingWithInteractivity,
|
||||||
|
)
|
||||||
|
from sam3.model.sam3_multiplex_video_predictor import Sam3MultiplexVideoPredictor
|
||||||
|
|
||||||
|
# Build tracker
|
||||||
|
tracker_model = build_sam3_multiplex_video_model(
|
||||||
|
checkpoint_path=checkpoint_path,
|
||||||
|
load_from_HF=False,
|
||||||
|
multiplex_count=multiplex_count,
|
||||||
|
use_fa3=use_fa3,
|
||||||
|
use_rope_real=use_rope_real,
|
||||||
|
compile=False,
|
||||||
|
strict_state_dict_loading=False,
|
||||||
|
)
|
||||||
|
del tracker_model.backbone
|
||||||
|
tracker_model.backbone = None
|
||||||
|
|
||||||
|
sam2_predictor = Sam3MultiplexPredictorWrapper(
|
||||||
|
model=tracker_model,
|
||||||
|
per_obj_inference=False,
|
||||||
|
fill_hole_area=0,
|
||||||
|
is_multiplex=True,
|
||||||
|
is_multiplex_dynamic=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Build detector
|
||||||
|
tri_neck = _create_multiplex_tri_backbone(
|
||||||
|
compile_mode=None, use_fa3=use_fa3, use_rope_real=use_rope_real
|
||||||
|
)
|
||||||
|
text_encoder = _create_text_encoder(bpe_path)
|
||||||
|
backbone = SAM3VLBackboneTri(scalp=0, visual=tri_neck, text=text_encoder)
|
||||||
|
transformer = _create_sam3_transformer(use_fa3=use_fa3)
|
||||||
|
segmentation_head = _create_segmentation_head(use_fa3=use_fa3)
|
||||||
|
geometry_encoder = _create_geometry_encoder()
|
||||||
|
dot_prod_scoring = _create_dot_product_scoring()
|
||||||
|
|
||||||
|
detector = Sam3MultiplexDetector(
|
||||||
|
num_feature_levels=1,
|
||||||
|
backbone=backbone,
|
||||||
|
transformer=transformer,
|
||||||
|
segmentation_head=segmentation_head,
|
||||||
|
semantic_segmentation_head=None,
|
||||||
|
input_geometry_encoder=geometry_encoder,
|
||||||
|
use_early_fusion=True,
|
||||||
|
use_dot_prod_scoring=True,
|
||||||
|
dot_prod_scoring=dot_prod_scoring,
|
||||||
|
supervise_joint_box_scores=True,
|
||||||
|
is_multiplex=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Assemble demo model
|
||||||
|
demo_model = Sam3MultiplexTrackingWithInteractivity(
|
||||||
|
tracker=sam2_predictor,
|
||||||
|
detector=detector,
|
||||||
|
score_threshold_detection=0.4,
|
||||||
|
det_nms_thresh=0.1,
|
||||||
|
det_nms_use_iom=True,
|
||||||
|
assoc_iou_thresh=0.1,
|
||||||
|
new_det_thresh=0.65,
|
||||||
|
hotstart_delay=15,
|
||||||
|
hotstart_unmatch_thresh=8,
|
||||||
|
hotstart_dup_thresh=8,
|
||||||
|
suppress_unmatched_only_within_hotstart=False,
|
||||||
|
suppress_overlapping_based_on_recent_occlusion_threshold=0.7,
|
||||||
|
suppress_det_close_to_boundary=True,
|
||||||
|
fill_hole_area=0, # OV effectively 0 (Sam3MultiplexTrackerPredictor Hydra override clobbers yaml's 16)
|
||||||
|
recondition_every_nth_frame=16,
|
||||||
|
use_iom_recondition=True,
|
||||||
|
iom_thresh_recondition=0.5,
|
||||||
|
masklet_confirmation_enable=True,
|
||||||
|
reconstruction_bbox_iou_thresh=-1,
|
||||||
|
reconstruction_bbox_det_score=0.8,
|
||||||
|
max_num_objects=max_num_objects,
|
||||||
|
postprocess_batch_size=16,
|
||||||
|
use_batched_grounding=True,
|
||||||
|
batched_grounding_batch_size=16,
|
||||||
|
max_num_kboxes=0,
|
||||||
|
sprinkle_removal_area=0,
|
||||||
|
is_multiplex=True,
|
||||||
|
image_size=1008,
|
||||||
|
image_mean=(0.5, 0.5, 0.5),
|
||||||
|
image_std=(0.5, 0.5, 0.5),
|
||||||
|
compile_model=compile,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Load checkpoint (auto-download from HuggingFace if not provided)
|
||||||
|
if checkpoint_path is None:
|
||||||
|
checkpoint_path = download_ckpt_from_hf(version="sam3.1")
|
||||||
|
if checkpoint_path is not None:
|
||||||
|
ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
|
||||||
|
if "model" in ckpt and isinstance(ckpt["model"], dict):
|
||||||
|
ckpt = ckpt["model"]
|
||||||
|
# Remap checkpoint keys if needed (internal naming -> OSS naming)
|
||||||
|
# HF checkpoints are already remapped; local checkpoints may use old naming
|
||||||
|
needs_remap = any(
|
||||||
|
k.startswith("sam3_model.") or k.startswith("sam2_predictor.") for k in ckpt
|
||||||
|
)
|
||||||
|
if needs_remap:
|
||||||
|
remapped_ckpt = {}
|
||||||
|
for k, v in ckpt.items():
|
||||||
|
new_k = k
|
||||||
|
if k.startswith("sam3_model."):
|
||||||
|
new_k = "detector." + k[len("sam3_model.") :]
|
||||||
|
elif k.startswith("sam2_predictor."):
|
||||||
|
new_k = "tracker." + k[len("sam2_predictor.") :]
|
||||||
|
remapped_ckpt[new_k] = v
|
||||||
|
ckpt = remapped_ckpt
|
||||||
|
missing_keys, unexpected_keys = demo_model.load_state_dict(ckpt, strict=False)
|
||||||
|
if missing_keys:
|
||||||
|
print(f"Missing keys ({len(missing_keys)}): {missing_keys[:10]}...")
|
||||||
|
if unexpected_keys:
|
||||||
|
print(
|
||||||
|
f"Unexpected keys ({len(unexpected_keys)}): {unexpected_keys[:10]}..."
|
||||||
|
)
|
||||||
|
|
||||||
|
demo_model.cuda().eval()
|
||||||
|
|
||||||
|
# Wrap in predictor
|
||||||
|
predictor = Sam3MultiplexVideoPredictor(
|
||||||
|
model=demo_model,
|
||||||
|
session_expiration_sec=session_expiration_sec,
|
||||||
|
default_output_prob_thresh=default_output_prob_thresh,
|
||||||
|
async_loading_frames=async_loading_frames,
|
||||||
|
warm_up=warm_up,
|
||||||
|
)
|
||||||
|
return predictor
|
||||||
|
|
||||||
|
|
||||||
|
def build_sam3_predictor(
|
||||||
|
checkpoint_path: Optional[str] = None,
|
||||||
|
bpe_path: Optional[str] = None,
|
||||||
|
version: str = "sam3.1", # "sam3" or "sam3.1"
|
||||||
|
compile: bool = False,
|
||||||
|
warm_up: bool = False,
|
||||||
|
# SAM 3.1 specific
|
||||||
|
max_num_objects: int = 16,
|
||||||
|
multiplex_count: int = 16,
|
||||||
|
# Common
|
||||||
|
use_fa3: bool = True,
|
||||||
|
use_rope_real: bool = True,
|
||||||
|
async_loading_frames: bool = True,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Build a SAM3 video predictor.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
checkpoint_path: Path to model checkpoint
|
||||||
|
bpe_path: Path to BPE tokenizer vocabulary
|
||||||
|
version: Model version - "sam3" for base or "sam3.1" for multiplex
|
||||||
|
compile: Enable torch.compile for ~2x speedup (SAM 3.1 only currently)
|
||||||
|
warm_up: Run warm-up compilation passes
|
||||||
|
max_num_objects: Maximum tracked objects (SAM 3.1 only)
|
||||||
|
multiplex_count: Objects per multiplex bucket (SAM 3.1 only)
|
||||||
|
use_fa3: Use Flash Attention 3
|
||||||
|
use_rope_real: Use real-valued RoPE
|
||||||
|
async_loading_frames: Load video frames asynchronously
|
||||||
|
**kwargs: Additional arguments passed to the underlying builder
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A predictor with handle_request() and handle_stream_request() API.
|
||||||
|
Both versions support: start_session, add_prompt, propagate_in_video,
|
||||||
|
remove_object, reset_session, close_session.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
# SAM 3.1 (auto-downloads from HuggingFace):
|
||||||
|
predictor = build_sam3_predictor(version="sam3.1", compile=True)
|
||||||
|
|
||||||
|
# SAM 3 (auto-downloads from HuggingFace):
|
||||||
|
predictor = build_sam3_predictor(version="sam3")
|
||||||
|
|
||||||
|
# Or with a local checkpoint:
|
||||||
|
predictor = build_sam3_predictor(checkpoint_path="path/to/ckpt.pt", version="sam3.1")
|
||||||
|
|
||||||
|
# Both use the same API:
|
||||||
|
response = predictor.handle_request({"type": "start_session", "resource_path": video_dir})
|
||||||
|
session_id = response["session_id"]
|
||||||
|
predictor.handle_request({"type": "add_prompt", "session_id": session_id, "frame_index": 0, "text": "person"})
|
||||||
|
for out in predictor.handle_stream_request({"type": "propagate_in_video", "session_id": session_id}):
|
||||||
|
masks = out["out_binary_masks"]
|
||||||
|
"""
|
||||||
|
if version == "sam3.1":
|
||||||
|
return build_sam3_multiplex_video_predictor(
|
||||||
|
checkpoint_path=checkpoint_path,
|
||||||
|
bpe_path=bpe_path,
|
||||||
|
max_num_objects=max_num_objects,
|
||||||
|
multiplex_count=multiplex_count,
|
||||||
|
use_fa3=use_fa3,
|
||||||
|
use_rope_real=use_rope_real,
|
||||||
|
compile=compile,
|
||||||
|
warm_up=warm_up,
|
||||||
|
async_loading_frames=async_loading_frames,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
elif version == "sam3":
|
||||||
|
return build_sam3_video_predictor(
|
||||||
|
checkpoint_path=checkpoint_path,
|
||||||
|
bpe_path=bpe_path,
|
||||||
|
compile=compile,
|
||||||
|
async_loading_frames=async_loading_frames,
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unknown version: {version!r}. Use 'sam3' or 'sam3.1'.")
|
||||||
|
|||||||
+38
-16
@@ -2,7 +2,11 @@
|
|||||||
|
|
||||||
# pyre-unsafe
|
# pyre-unsafe
|
||||||
|
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
|
from sam3.model.data_misc import BatchedDatapoint, NestedTensor
|
||||||
|
from torch.utils._pytree import tree_map_only
|
||||||
|
|
||||||
|
|
||||||
def recursive_fn_factory(fn):
|
def recursive_fn_factory(fn):
|
||||||
@@ -13,15 +17,18 @@ def recursive_fn_factory(fn):
|
|||||||
return [recursive_fn(t) for t in b]
|
return [recursive_fn(t) for t in b]
|
||||||
if isinstance(b, tuple):
|
if isinstance(b, tuple):
|
||||||
return tuple(recursive_fn(t) for t in b)
|
return tuple(recursive_fn(t) for t in b)
|
||||||
|
if isinstance(b, NestedTensor):
|
||||||
|
tensors = fn(b.tensors)
|
||||||
|
if b.mask is None:
|
||||||
|
mask = None
|
||||||
|
else:
|
||||||
|
mask = fn(b.mask)
|
||||||
|
return NestedTensor(tensors=tensors, mask=mask)
|
||||||
if isinstance(b, torch.Tensor):
|
if isinstance(b, torch.Tensor):
|
||||||
return fn(b)
|
return fn(b)
|
||||||
# Yes, writing out an explicit white list of
|
|
||||||
# trivial types is tedious, but so are bugs that
|
|
||||||
# come from not applying fn, when expected to have
|
|
||||||
# applied it.
|
|
||||||
if b is None:
|
if b is None:
|
||||||
return b
|
return b
|
||||||
trivial_types = [bool, int]
|
trivial_types = [bool, int, float]
|
||||||
for t in trivial_types:
|
for t in trivial_types:
|
||||||
if isinstance(b, t):
|
if isinstance(b, t):
|
||||||
return b
|
return b
|
||||||
@@ -34,20 +41,41 @@ recursive_contiguous = recursive_fn_factory(lambda x: x.contiguous())
|
|||||||
recursive_clone = recursive_fn_factory(torch.clone)
|
recursive_clone = recursive_fn_factory(torch.clone)
|
||||||
|
|
||||||
|
|
||||||
|
def clone_output_wrapper(f):
|
||||||
|
"""
|
||||||
|
Clone the CUDA output tensors of a function to avoid in-place operations.
|
||||||
|
Uses tree_map_only (C-optimized pytree traversal) matching onevision's pattern.
|
||||||
|
Requires NestedTensor to be registered as a pytree node (see data_misc.py).
|
||||||
|
"""
|
||||||
|
|
||||||
|
@wraps(f)
|
||||||
|
def wrapped(*args, **kwargs):
|
||||||
|
outputs = f(*args, **kwargs)
|
||||||
|
return tree_map_only(
|
||||||
|
torch.Tensor, lambda t: t.clone() if t.is_cuda else t, outputs
|
||||||
|
)
|
||||||
|
|
||||||
|
return wrapped
|
||||||
|
|
||||||
|
|
||||||
def compile_wrapper(
|
def compile_wrapper(
|
||||||
fn, *, mode="max-autotune", fullgraph=True, dynamic=False, name=None
|
fn, *, mode="max-autotune", fullgraph=True, dynamic=False, name=None
|
||||||
):
|
):
|
||||||
|
"""Compile with recursive_contiguous on inputs and recursive_clone on outputs.
|
||||||
|
Used for SAM2 tracker components that need contiguous inputs for CUDA graphs."""
|
||||||
compiled_fn = torch.compile(fn, mode=mode, fullgraph=fullgraph, dynamic=dynamic)
|
compiled_fn = torch.compile(fn, mode=mode, fullgraph=fullgraph, dynamic=dynamic)
|
||||||
|
|
||||||
def compiled_fn_wrapper(*args, **kwargs):
|
def compiled_fn_wrapper(*args, **kwargs):
|
||||||
with torch.autograd.profiler.record_function(
|
with torch.autograd.profiler.record_function(
|
||||||
f"compiled {fn}" if name is None else name
|
f"compiled {fn}" if name is None else name
|
||||||
):
|
):
|
||||||
cont_args = recursive_contiguous(args)
|
CUDAGRAPH_MODES = ["max-autotune", "reduce-overhead"]
|
||||||
cont_kwargs = recursive_contiguous(kwargs)
|
args = recursive_contiguous(args)
|
||||||
result = compiled_fn(*cont_args, **cont_kwargs)
|
kwargs = recursive_contiguous(kwargs)
|
||||||
cloned_result = recursive_clone(result)
|
result = compiled_fn(*args, **kwargs)
|
||||||
return cloned_result
|
if mode in CUDAGRAPH_MODES:
|
||||||
|
result = recursive_clone(result)
|
||||||
|
return result
|
||||||
|
|
||||||
return compiled_fn_wrapper
|
return compiled_fn_wrapper
|
||||||
|
|
||||||
@@ -56,11 +84,6 @@ def shape_logging_wrapper(fn, keep_kwargs, enable_logging=False):
|
|||||||
"""
|
"""
|
||||||
Wraps a function and prints the shapes of all tensor inputs.
|
Wraps a function and prints the shapes of all tensor inputs.
|
||||||
Only prints when a new combination of shapes is seen.
|
Only prints when a new combination of shapes is seen.
|
||||||
Thread-safe.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
fn: Function to wrap
|
|
||||||
enable_logging: Boolean flag to enable/disable logging
|
|
||||||
"""
|
"""
|
||||||
seen_shapes = set()
|
seen_shapes = set()
|
||||||
|
|
||||||
@@ -89,7 +112,6 @@ def shape_logging_wrapper(fn, keep_kwargs, enable_logging=False):
|
|||||||
print(f"[ShapeLogger] New input shapes for {fn.__qualname__}: {shapes}")
|
print(f"[ShapeLogger] New input shapes for {fn.__qualname__}: {shapes}")
|
||||||
return fn(*args, **kwargs)
|
return fn(*args, **kwargs)
|
||||||
|
|
||||||
# Allow toggling the flag at runtime
|
|
||||||
wrapper.enable_logging = enable_logging
|
wrapper.enable_logging = enable_logging
|
||||||
|
|
||||||
def set_logging(enabled=False):
|
def set_logging(enabled=False):
|
||||||
|
|||||||
@@ -36,9 +36,9 @@ def connected_components_cpu(input_tensor: torch.Tensor):
|
|||||||
if input_tensor.dim() == 4 and input_tensor.shape[1] == 1:
|
if input_tensor.dim() == 4 and input_tensor.shape[1] == 1:
|
||||||
input_tensor = input_tensor.squeeze(1)
|
input_tensor = input_tensor.squeeze(1)
|
||||||
else:
|
else:
|
||||||
assert input_tensor.dim() == 3, (
|
assert (
|
||||||
"Input tensor must be (B, H, W) or (B, 1, H, W)."
|
input_tensor.dim() == 3
|
||||||
)
|
), "Input tensor must be (B, H, W) or (B, 1, H, W)."
|
||||||
|
|
||||||
batch_size = input_tensor.shape[0]
|
batch_size = input_tensor.shape[0]
|
||||||
labels_list = []
|
labels_list = []
|
||||||
@@ -67,9 +67,9 @@ def connected_components(input_tensor: torch.Tensor):
|
|||||||
if input_tensor.dim() == 3:
|
if input_tensor.dim() == 3:
|
||||||
input_tensor = input_tensor.unsqueeze(1)
|
input_tensor = input_tensor.unsqueeze(1)
|
||||||
|
|
||||||
assert input_tensor.dim() == 4 and input_tensor.shape[1] == 1, (
|
assert (
|
||||||
"Input tensor must be (B, H, W) or (B, 1, H, W)."
|
input_tensor.dim() == 4 and input_tensor.shape[1] == 1
|
||||||
)
|
), "Input tensor must be (B, H, W) or (B, 1, H, W)."
|
||||||
|
|
||||||
if input_tensor.is_cuda:
|
if input_tensor.is_cuda:
|
||||||
if HAS_CC_TORCH:
|
if HAS_CC_TORCH:
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
||||||
|
|
||||||
|
# pyre-unsafe
|
||||||
|
|
||||||
|
import torch
|
||||||
|
|
||||||
|
addmm_act_op = torch.ops.aten._addmm_activation
|
||||||
|
|
||||||
|
|
||||||
|
def addmm_act(activation, linear, mat1):
|
||||||
|
if torch.is_grad_enabled():
|
||||||
|
raise ValueError("Expected grad to be disabled.")
|
||||||
|
self = linear.bias.detach()
|
||||||
|
mat2 = linear.weight.detach()
|
||||||
|
self = self.to(torch.bfloat16)
|
||||||
|
mat1 = mat1.to(torch.bfloat16)
|
||||||
|
mat2 = mat2.to(torch.bfloat16)
|
||||||
|
mat1_flat = mat1.view(-1, mat1.shape[-1])
|
||||||
|
if activation in [torch.nn.functional.relu, torch.nn.ReLU]:
|
||||||
|
y = addmm_act_op(self, mat1_flat, mat2.t(), beta=1, alpha=1, use_gelu=False)
|
||||||
|
return y.view(mat1.shape[:-1] + (y.shape[-1],))
|
||||||
|
if activation in [torch.nn.functional.gelu, torch.nn.GELU]:
|
||||||
|
y = addmm_act_op(self, mat1_flat, mat2.t(), beta=1, alpha=1, use_gelu=True)
|
||||||
|
return y.view(mat1.shape[:-1] + (y.shape[-1],))
|
||||||
|
raise ValueError(f"Unexpected activation {activation}")
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import torch
|
||||||
|
|
||||||
|
|
||||||
|
def pairwise_iou(pred_masks, gt_masks, eps=1e-6):
|
||||||
|
N, H, W = pred_masks.shape
|
||||||
|
M = gt_masks.shape[0]
|
||||||
|
# Flatten and convert to float for matmul
|
||||||
|
pred_flat = pred_masks.reshape(N, -1).float()
|
||||||
|
gt_flat = gt_masks.reshape(M, -1).float()
|
||||||
|
# Intersection: (N, M)
|
||||||
|
intersection = torch.matmul(pred_flat, gt_flat.t())
|
||||||
|
# Areas
|
||||||
|
area_pred = pred_flat.sum(dim=1, keepdim=True) # (N, 1)
|
||||||
|
area_gt = gt_flat.sum(dim=1, keepdim=True) # (M, 1)
|
||||||
|
# Union: (N, M)
|
||||||
|
union = area_pred + area_gt.t() - intersection
|
||||||
|
if eps is None:
|
||||||
|
iou = intersection / union.clamp(min=1)
|
||||||
|
else:
|
||||||
|
iou = intersection / (union + eps)
|
||||||
|
return iou # shape: (N, M)
|
||||||
|
|
||||||
|
|
||||||
|
def pairwise_iom(pred_masks, gt_masks, eps=1e-8):
|
||||||
|
N, H, W = pred_masks.shape
|
||||||
|
M = gt_masks.shape[0]
|
||||||
|
# Flatten and convert to float for matmul
|
||||||
|
pred_flat = pred_masks.reshape(N, -1).float()
|
||||||
|
gt_flat = gt_masks.reshape(M, -1).float()
|
||||||
|
# Intersection: (N, M)
|
||||||
|
intersection = torch.matmul(pred_flat, gt_flat.t())
|
||||||
|
# Areas
|
||||||
|
area_pred = pred_flat.sum(dim=1, keepdim=True) # (N, 1)
|
||||||
|
area_gt = gt_flat.sum(dim=1, keepdim=True) # (M, 1)
|
||||||
|
# Union: (N, M)
|
||||||
|
min_area = torch.min(area_pred, area_gt)
|
||||||
|
iou = intersection / (min_area + eps)
|
||||||
|
return iou # shape: (N, M)
|
||||||
+11
-10
@@ -50,6 +50,8 @@ def masks_to_boxes(masks: torch.Tensor, obj_ids: list[int]):
|
|||||||
def mask_iou(pred_masks: torch.Tensor, gt_masks: torch.Tensor) -> torch.Tensor:
|
def mask_iou(pred_masks: torch.Tensor, gt_masks: torch.Tensor) -> torch.Tensor:
|
||||||
"""
|
"""
|
||||||
Compute the IoU (Intersection over Union) between predicted masks and ground truth masks.
|
Compute the IoU (Intersection over Union) between predicted masks and ground truth masks.
|
||||||
|
Uses matmul-based vectorized intersection for Tensor Core acceleration.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
- pred_masks: (N, H, W) bool Tensor, containing binary predicted segmentation masks
|
- pred_masks: (N, H, W) bool Tensor, containing binary predicted segmentation masks
|
||||||
- gt_masks: (M, H, W) bool Tensor, containing binary ground truth segmentation masks
|
- gt_masks: (M, H, W) bool Tensor, containing binary ground truth segmentation masks
|
||||||
@@ -57,15 +59,14 @@ def mask_iou(pred_masks: torch.Tensor, gt_masks: torch.Tensor) -> torch.Tensor:
|
|||||||
- ious: (N, M) float Tensor, containing IoUs for each pair of predicted and ground truth masks
|
- ious: (N, M) float Tensor, containing IoUs for each pair of predicted and ground truth masks
|
||||||
"""
|
"""
|
||||||
assert pred_masks.dtype == gt_masks.dtype == torch.bool
|
assert pred_masks.dtype == gt_masks.dtype == torch.bool
|
||||||
N, H, W = pred_masks.shape
|
assert pred_masks.shape[1:] == gt_masks.shape[1:]
|
||||||
M, _, _ = gt_masks.shape
|
|
||||||
|
|
||||||
# Flatten masks: (N, 1, H*W) and (1, M, H*W)
|
# Matmul-based intersection (uses Tensor Cores via float mm)
|
||||||
pred_flat = pred_masks.view(N, 1, H * W)
|
m1_flat = pred_masks.flatten(1).float()
|
||||||
gt_flat = gt_masks.view(1, M, H * W)
|
m2_flat = gt_masks.flatten(1).float()
|
||||||
|
intersection = torch.mm(m1_flat, m2_flat.t())
|
||||||
|
|
||||||
# Compute intersection and union: (N, M)
|
area1 = m1_flat.sum(dim=1)
|
||||||
intersection = (pred_flat & gt_flat).sum(dim=2).float()
|
area2 = m2_flat.sum(dim=1)
|
||||||
union = (pred_flat | gt_flat).sum(dim=2).float()
|
union = area1[:, None] + area2[None, :] - intersection
|
||||||
ious = intersection / union.clamp(min=1)
|
return intersection / union.clamp(min=1)
|
||||||
return ious # shape: (N, M)
|
|
||||||
|
|||||||
@@ -407,16 +407,16 @@ def connected_components_triton(input_tensor: torch.Tensor):
|
|||||||
- A BxHxW output tensor with dense labels. Background is 0.
|
- A BxHxW output tensor with dense labels. Background is 0.
|
||||||
- A BxHxW tensor with the size of the connected component for each pixel.
|
- A BxHxW tensor with the size of the connected component for each pixel.
|
||||||
"""
|
"""
|
||||||
assert input_tensor.is_cuda and input_tensor.is_contiguous(), (
|
assert (
|
||||||
"Input tensor must be a contiguous CUDA tensor."
|
input_tensor.is_cuda and input_tensor.is_contiguous()
|
||||||
)
|
), "Input tensor must be a contiguous CUDA tensor."
|
||||||
out_shape = input_tensor.shape
|
out_shape = input_tensor.shape
|
||||||
if input_tensor.dim() == 4 and input_tensor.shape[1] == 1:
|
if input_tensor.dim() == 4 and input_tensor.shape[1] == 1:
|
||||||
input_tensor = input_tensor.squeeze(1)
|
input_tensor = input_tensor.squeeze(1)
|
||||||
else:
|
else:
|
||||||
assert input_tensor.dim() == 3, (
|
assert (
|
||||||
"Input tensor must be (B, H, W) or (B, 1, H, W)."
|
input_tensor.dim() == 3
|
||||||
)
|
), "Input tensor must be (B, H, W) or (B, 1, H, W)."
|
||||||
|
|
||||||
B, H, W = input_tensor.shape
|
B, H, W = input_tensor.shape
|
||||||
numel = B * H * W
|
numel = B * H * W
|
||||||
|
|||||||
@@ -202,9 +202,9 @@ class MaskDecoder(nn.Module):
|
|||||||
assert image_embeddings.shape[0] == tokens.shape[0]
|
assert image_embeddings.shape[0] == tokens.shape[0]
|
||||||
src = image_embeddings
|
src = image_embeddings
|
||||||
src = src + dense_prompt_embeddings
|
src = src + dense_prompt_embeddings
|
||||||
assert image_pe.size(0) == 1, (
|
assert (
|
||||||
"image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
|
image_pe.size(0) == 1
|
||||||
)
|
), "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
|
||||||
pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
|
pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
|
||||||
b, c, h, w = src.shape
|
b, c, h, w = src.shape
|
||||||
|
|
||||||
|
|||||||
@@ -204,9 +204,9 @@ class Attention(nn.Module):
|
|||||||
self.internal_dim = embedding_dim // downsample_rate
|
self.internal_dim = embedding_dim // downsample_rate
|
||||||
self.num_heads = num_heads
|
self.num_heads = num_heads
|
||||||
self.use_fa3 = use_fa3
|
self.use_fa3 = use_fa3
|
||||||
assert self.internal_dim % num_heads == 0, (
|
assert (
|
||||||
"num_heads must divide embedding_dim."
|
self.internal_dim % num_heads == 0
|
||||||
)
|
), "num_heads must divide embedding_dim."
|
||||||
|
|
||||||
self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
|
self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
|
||||||
self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
|
self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
|
||||||
|
|||||||
@@ -142,9 +142,9 @@ class COCO_FROM_JSON:
|
|||||||
self.prompts = {}
|
self.prompts = {}
|
||||||
for loc_dict in prompts:
|
for loc_dict in prompts:
|
||||||
self.prompts[int(loc_dict["id"])] = loc_dict["name"]
|
self.prompts[int(loc_dict["id"])] = loc_dict["name"]
|
||||||
assert len(self.prompts) == len(self._sorted_cat_ids), (
|
assert len(self.prompts) == len(
|
||||||
"Number of prompts must match number of categories"
|
self._sorted_cat_ids
|
||||||
)
|
), "Number of prompts must match number of categories"
|
||||||
|
|
||||||
def getDatapointIds(self):
|
def getDatapointIds(self):
|
||||||
"""Return all datapoint indices for training."""
|
"""Return all datapoint indices for training."""
|
||||||
|
|||||||
@@ -216,9 +216,9 @@ def collate_fn_api(
|
|||||||
text_batch.append(q.query_text)
|
text_batch.append(q.query_text)
|
||||||
stages[stage_id].text_ids.append(text_batch.index(q.query_text))
|
stages[stage_id].text_ids.append(text_batch.index(q.query_text))
|
||||||
|
|
||||||
assert q.inference_metadata is not None, (
|
assert (
|
||||||
"inference_metadata must be provided when FindQueryLoaded is created."
|
q.inference_metadata is not None
|
||||||
)
|
), "inference_metadata must be provided when FindQueryLoaded is created."
|
||||||
for f in fields(q.inference_metadata):
|
for f in fields(q.inference_metadata):
|
||||||
getattr(find_metadatas[stage_id], f.name).append(
|
getattr(find_metadatas[stage_id], f.name).append(
|
||||||
getattr(q.inference_metadata, f.name)
|
getattr(q.inference_metadata, f.name)
|
||||||
|
|||||||
@@ -233,9 +233,9 @@ class CustomCocoDetectionAPI(VisionDataset):
|
|||||||
if self.coco is not None:
|
if self.coco is not None:
|
||||||
return
|
return
|
||||||
|
|
||||||
assert g_pathmgr.isfile(self.annFile), (
|
assert g_pathmgr.isfile(
|
||||||
f"please provide valid annotation file. Missing: {self.annFile}"
|
self.annFile
|
||||||
)
|
), f"please provide valid annotation file. Missing: {self.annFile}"
|
||||||
annFile = g_pathmgr.get_local_path(self.annFile)
|
annFile = g_pathmgr.get_local_path(self.annFile)
|
||||||
|
|
||||||
if self.coco is not None:
|
if self.coco is not None:
|
||||||
@@ -325,9 +325,9 @@ class CustomCocoDetectionAPI(VisionDataset):
|
|||||||
else:
|
else:
|
||||||
num_queries_per_stage = stage2num_queries.most_common(1)[0][1]
|
num_queries_per_stage = stage2num_queries.most_common(1)[0][1]
|
||||||
for stage, num_queries in stage2num_queries.items():
|
for stage, num_queries in stage2num_queries.items():
|
||||||
assert num_queries == num_queries_per_stage, (
|
assert (
|
||||||
f"Number of queries in stage {stage} is {num_queries}, expected {num_queries_per_stage}"
|
num_queries == num_queries_per_stage
|
||||||
)
|
), f"Number of queries in stage {stage} is {num_queries}, expected {num_queries_per_stage}"
|
||||||
|
|
||||||
for query in queries:
|
for query in queries:
|
||||||
h, w = id2imsize[query["image_id"]]
|
h, w = id2imsize[query["image_id"]]
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from typing import Any, Dict, List, Optional, Set, Tuple, Union
|
|||||||
|
|
||||||
import torch
|
import torch
|
||||||
import torchvision
|
import torchvision
|
||||||
|
|
||||||
# from decord import cpu, VideoReader
|
# from decord import cpu, VideoReader
|
||||||
|
|
||||||
from iopath.common.file_io import PathManager
|
from iopath.common.file_io import PathManager
|
||||||
@@ -218,9 +219,9 @@ class VideoGroundingDataset(Sam3ImageDataset):
|
|||||||
for query in filtered_queries:
|
for query in filtered_queries:
|
||||||
ptr_x_is_empty = query["ptr_x_query_id"] in [None, -1]
|
ptr_x_is_empty = query["ptr_x_query_id"] in [None, -1]
|
||||||
ptr_y_is_empty = query["ptr_y_query_id"] in [None, -1]
|
ptr_y_is_empty = query["ptr_y_query_id"] in [None, -1]
|
||||||
assert ptr_x_is_empty and ptr_y_is_empty, (
|
assert (
|
||||||
"Remapping stage ids is not supported for queries with non-empty ptr_x or ptr_y pointers"
|
ptr_x_is_empty and ptr_y_is_empty
|
||||||
)
|
), "Remapping stage ids is not supported for queries with non-empty ptr_x or ptr_y pointers"
|
||||||
query["query_processing_order"] = stage_id_old2new[
|
query["query_processing_order"] = stage_id_old2new[
|
||||||
query["query_processing_order"]
|
query["query_processing_order"]
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -324,9 +324,7 @@ class IABCEMdetr(LossWithWeights):
|
|||||||
if num_det_queries is not None:
|
if num_det_queries is not None:
|
||||||
logging.warning("note: it's not needed to set num_det_queries anymore")
|
logging.warning("note: it's not needed to set num_det_queries anymore")
|
||||||
if self.use_separate_loss_for_det_and_trk:
|
if self.use_separate_loss_for_det_and_trk:
|
||||||
assert not self.weak_loss, (
|
assert not self.weak_loss, "Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
|
||||||
"Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
|
|
||||||
)
|
|
||||||
self.det_exhaustive_loss_scale_pos = det_exhaustive_loss_scale_pos
|
self.det_exhaustive_loss_scale_pos = det_exhaustive_loss_scale_pos
|
||||||
self.det_exhaustive_loss_scale_neg = det_exhaustive_loss_scale_neg
|
self.det_exhaustive_loss_scale_neg = det_exhaustive_loss_scale_neg
|
||||||
self.det_non_exhaustive_loss_scale_pos = det_non_exhaustive_loss_scale_pos
|
self.det_non_exhaustive_loss_scale_pos = det_non_exhaustive_loss_scale_pos
|
||||||
@@ -341,9 +339,7 @@ class IABCEMdetr(LossWithWeights):
|
|||||||
and det_non_exhaustive_loss_scale_neg == 1.0
|
and det_non_exhaustive_loss_scale_neg == 1.0
|
||||||
and trk_loss_scale_pos == 1.0
|
and trk_loss_scale_pos == 1.0
|
||||||
and trk_loss_scale_neg == 1.0
|
and trk_loss_scale_neg == 1.0
|
||||||
), (
|
), "If not using separate loss for detection and tracking queries, separate detection and tracking loss scales should all be 1.0"
|
||||||
"If not using separate loss for detection and tracking queries, separate detection and tracking loss scales should all be 1.0"
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_loss(self, outputs, targets, indices, num_boxes):
|
def get_loss(self, outputs, targets, indices, num_boxes):
|
||||||
assert len(outputs["pred_logits"].shape) > 2, "Incorrect predicted logits shape"
|
assert len(outputs["pred_logits"].shape) > 2, "Incorrect predicted logits shape"
|
||||||
@@ -444,9 +440,7 @@ class IABCEMdetr(LossWithWeights):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
if self.weak_loss:
|
if self.weak_loss:
|
||||||
assert not self.use_separate_loss_for_det_and_trk, (
|
assert not self.use_separate_loss_for_det_and_trk, "Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
|
||||||
"Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
|
|
||||||
)
|
|
||||||
|
|
||||||
# nullify the negative loss for the non-exhaustive classes
|
# nullify the negative loss for the non-exhaustive classes
|
||||||
assert loss_bce.shape[0] == targets["is_exhaustive"].shape[0]
|
assert loss_bce.shape[0] == targets["is_exhaustive"].shape[0]
|
||||||
@@ -500,9 +494,9 @@ class IABCEMdetr(LossWithWeights):
|
|||||||
loss_bce = loss_bce.mean()
|
loss_bce = loss_bce.mean()
|
||||||
else:
|
else:
|
||||||
assert isinstance(self.pad_n_queries, int)
|
assert isinstance(self.pad_n_queries, int)
|
||||||
assert loss_bce.size(1) < self.pad_n_queries, (
|
assert (
|
||||||
f"The number of predictions is more than the expected total after padding. Got {loss_bce.size(1)} predictions."
|
loss_bce.size(1) < self.pad_n_queries
|
||||||
)
|
), f"The number of predictions is more than the expected total after padding. Got {loss_bce.size(1)} predictions."
|
||||||
loss_bce = loss_bce.sum() / (self.pad_n_queries * loss_bce.size(0))
|
loss_bce = loss_bce.sum() / (self.pad_n_queries * loss_bce.size(0))
|
||||||
|
|
||||||
bce_f1 = torchmetrics.functional.f1_score(
|
bce_f1 = torchmetrics.functional.f1_score(
|
||||||
|
|||||||
+21
-5
@@ -36,6 +36,23 @@ def instance_masks_to_semantic_masks(
|
|||||||
return torch.stack([torch.any(masks, dim=0) for masks in masks_per_query], dim=0)
|
return torch.stack([torch.any(masks, dim=0) for masks in masks_per_query], dim=0)
|
||||||
|
|
||||||
|
|
||||||
|
def mask_intersection_vectorized(masks1, masks2):
|
||||||
|
"""
|
||||||
|
Vectorized computation of mask intersection using Matrix Multiplication.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
masks1: tensor of shape (N, H, W)
|
||||||
|
masks2: tensor of shape (M, H, W)
|
||||||
|
Returns:
|
||||||
|
tensor of shape (N, M)
|
||||||
|
"""
|
||||||
|
# Cast to float for Tensor Core acceleration via torch.mm
|
||||||
|
m1_flat = masks1.flatten(1).float()
|
||||||
|
m2_flat = masks2.flatten(1).float()
|
||||||
|
intersection = torch.mm(m1_flat, m2_flat.t())
|
||||||
|
return intersection.long()
|
||||||
|
|
||||||
|
|
||||||
def mask_intersection(masks1, masks2, block_size=16):
|
def mask_intersection(masks1, masks2, block_size=16):
|
||||||
"""Compute the intersection of two sets of masks, without blowing the memory"""
|
"""Compute the intersection of two sets of masks, without blowing the memory"""
|
||||||
|
|
||||||
@@ -63,8 +80,7 @@ def mask_iom(masks1, masks2):
|
|||||||
assert masks1.shape[1:] == masks2.shape[1:]
|
assert masks1.shape[1:] == masks2.shape[1:]
|
||||||
assert masks1.dtype == torch.bool and masks2.dtype == torch.bool
|
assert masks1.dtype == torch.bool and masks2.dtype == torch.bool
|
||||||
|
|
||||||
# intersection = (masks1[:, None] * masks2[None]).flatten(-2).sum(-1)
|
intersection = mask_intersection_vectorized(masks1, masks2)
|
||||||
intersection = mask_intersection(masks1, masks2)
|
|
||||||
area1 = masks1.flatten(-2).sum(-1)
|
area1 = masks1.flatten(-2).sum(-1)
|
||||||
area2 = masks2.flatten(-2).sum(-1)
|
area2 = masks2.flatten(-2).sum(-1)
|
||||||
min_area = torch.min(area1[:, None], area2[None, :])
|
min_area = torch.min(area1[:, None], area2[None, :])
|
||||||
@@ -103,9 +119,9 @@ def dilation(mask, kernel_size):
|
|||||||
|
|
||||||
assert mask.ndim == 3
|
assert mask.ndim == 3
|
||||||
kernel_size = int(kernel_size)
|
kernel_size = int(kernel_size)
|
||||||
assert kernel_size % 2 == 1, (
|
assert (
|
||||||
f"Dilation expects a odd kernel size, got {kernel_size}"
|
kernel_size % 2 == 1
|
||||||
)
|
), f"Dilation expects a odd kernel size, got {kernel_size}"
|
||||||
|
|
||||||
if mask.is_cuda:
|
if mask.is_cuda:
|
||||||
m = mask.unsqueeze(1).to(torch.float16)
|
m = mask.unsqueeze(1).to(torch.float16)
|
||||||
|
|||||||
+12
-12
@@ -59,9 +59,9 @@ class HungarianMatcher(nn.Module):
|
|||||||
self.cost_bbox = cost_bbox
|
self.cost_bbox = cost_bbox
|
||||||
self.cost_giou = cost_giou
|
self.cost_giou = cost_giou
|
||||||
self.norm = nn.Sigmoid() if focal_loss else nn.Softmax(-1)
|
self.norm = nn.Sigmoid() if focal_loss else nn.Softmax(-1)
|
||||||
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
|
assert (
|
||||||
"all costs cant be 0"
|
cost_class != 0 or cost_bbox != 0 or cost_giou != 0
|
||||||
)
|
), "all costs cant be 0"
|
||||||
self.focal_loss = focal_loss
|
self.focal_loss = focal_loss
|
||||||
self.focal_alpha = focal_alpha
|
self.focal_alpha = focal_alpha
|
||||||
self.focal_gamma = focal_gamma
|
self.focal_gamma = focal_gamma
|
||||||
@@ -196,9 +196,9 @@ class BinaryHungarianMatcher(nn.Module):
|
|||||||
self.cost_bbox = cost_bbox
|
self.cost_bbox = cost_bbox
|
||||||
self.cost_giou = cost_giou
|
self.cost_giou = cost_giou
|
||||||
self.norm = nn.Sigmoid()
|
self.norm = nn.Sigmoid()
|
||||||
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
|
assert (
|
||||||
"all costs cant be 0"
|
cost_class != 0 or cost_bbox != 0 or cost_giou != 0
|
||||||
)
|
), "all costs cant be 0"
|
||||||
|
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def forward(self, outputs, batched_targets, repeats=0, repeat_batch=1):
|
def forward(self, outputs, batched_targets, repeats=0, repeat_batch=1):
|
||||||
@@ -321,9 +321,9 @@ class BinaryFocalHungarianMatcher(nn.Module):
|
|||||||
self.alpha = alpha
|
self.alpha = alpha
|
||||||
self.gamma = gamma
|
self.gamma = gamma
|
||||||
self.stable = stable
|
self.stable = stable
|
||||||
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
|
assert (
|
||||||
"all costs cant be 0"
|
cost_class != 0 or cost_bbox != 0 or cost_giou != 0
|
||||||
)
|
), "all costs cant be 0"
|
||||||
|
|
||||||
@torch.no_grad()
|
@torch.no_grad()
|
||||||
def forward(self, outputs, batched_targets, repeats=1, repeat_batch=1):
|
def forward(self, outputs, batched_targets, repeats=1, repeat_batch=1):
|
||||||
@@ -469,9 +469,9 @@ class BinaryHungarianMatcherV2(nn.Module):
|
|||||||
self.cost_bbox = cost_bbox
|
self.cost_bbox = cost_bbox
|
||||||
self.cost_giou = cost_giou
|
self.cost_giou = cost_giou
|
||||||
self.norm = nn.Sigmoid()
|
self.norm = nn.Sigmoid()
|
||||||
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
|
assert (
|
||||||
"all costs cant be 0"
|
cost_class != 0 or cost_bbox != 0 or cost_giou != 0
|
||||||
)
|
), "all costs cant be 0"
|
||||||
self.focal = focal
|
self.focal = focal
|
||||||
if focal:
|
if focal:
|
||||||
self.alpha = alpha
|
self.alpha = alpha
|
||||||
|
|||||||
@@ -211,9 +211,9 @@ def unix_module_cls_pattern_to_parameter_names(
|
|||||||
"match any classes in the model"
|
"match any classes in the model"
|
||||||
)
|
)
|
||||||
matching_parameters = module_cls_to_param_names[module_cls]
|
matching_parameters = module_cls_to_param_names[module_cls]
|
||||||
assert len(matching_parameters) > 0, (
|
assert (
|
||||||
f"module_cls_name {module_cls_name} does not contain any parameters in the model"
|
len(matching_parameters) > 0
|
||||||
)
|
), f"module_cls_name {module_cls_name} does not contain any parameters in the model"
|
||||||
logging.info(
|
logging.info(
|
||||||
f"Matches for module_cls_name [{module_cls_name}]: {matching_parameters} "
|
f"Matches for module_cls_name [{module_cls_name}]: {matching_parameters} "
|
||||||
)
|
)
|
||||||
@@ -239,9 +239,9 @@ def unix_param_pattern_to_parameter_names(
|
|||||||
allowed_parameter_names = []
|
allowed_parameter_names = []
|
||||||
for param_name in filter_param_names:
|
for param_name in filter_param_names:
|
||||||
matching_parameters = set(fnmatch.filter(parameter_names, param_name))
|
matching_parameters = set(fnmatch.filter(parameter_names, param_name))
|
||||||
assert len(matching_parameters) >= 1, (
|
assert (
|
||||||
f"param_name {param_name} does not match any parameters in the model"
|
len(matching_parameters) >= 1
|
||||||
)
|
), f"param_name {param_name} does not match any parameters in the model"
|
||||||
logging.info(f"Matches for param_name [{param_name}]: {matching_parameters}")
|
logging.info(f"Matches for param_name [{param_name}]: {matching_parameters}")
|
||||||
allowed_parameter_names.append(matching_parameters)
|
allowed_parameter_names.append(matching_parameters)
|
||||||
return set.union(*allowed_parameter_names)
|
return set.union(*allowed_parameter_names)
|
||||||
|
|||||||
+3
-3
@@ -209,9 +209,9 @@ def main(args) -> None:
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
if "include_nodes" in submitit_conf:
|
if "include_nodes" in submitit_conf:
|
||||||
assert len(submitit_conf["include_nodes"]) >= cfg.launcher.num_nodes, (
|
assert (
|
||||||
"Not enough nodes"
|
len(submitit_conf["include_nodes"]) >= cfg.launcher.num_nodes
|
||||||
)
|
), "Not enough nodes"
|
||||||
job_kwargs["slurm_additional_parameters"]["nodelist"] = " ".join(
|
job_kwargs["slurm_additional_parameters"]["nodelist"] = " ".join(
|
||||||
submitit_conf["include_nodes"]
|
submitit_conf["include_nodes"]
|
||||||
)
|
)
|
||||||
|
|||||||
+21
-21
@@ -209,9 +209,9 @@ class Trainer:
|
|||||||
set_seeds(seed_value, self.max_epochs, self.distributed_rank)
|
set_seeds(seed_value, self.max_epochs, self.distributed_rank)
|
||||||
log_env_variables()
|
log_env_variables()
|
||||||
|
|
||||||
assert is_dist_avail_and_initialized(), (
|
assert (
|
||||||
"Torch distributed needs to be initialized before calling the trainer."
|
is_dist_avail_and_initialized()
|
||||||
)
|
), "Torch distributed needs to be initialized before calling the trainer."
|
||||||
|
|
||||||
self._setup_components() # Except Optimizer everything is setup here.
|
self._setup_components() # Except Optimizer everything is setup here.
|
||||||
self._move_to_device()
|
self._move_to_device()
|
||||||
@@ -221,9 +221,9 @@ class Trainer:
|
|||||||
self.time_elapsed_meter = DurationMeter("Time Elapsed", self.device, ":.2f")
|
self.time_elapsed_meter = DurationMeter("Time Elapsed", self.device, ":.2f")
|
||||||
|
|
||||||
if self.checkpoint_conf.resume_from is not None:
|
if self.checkpoint_conf.resume_from is not None:
|
||||||
assert os.path.exists(self.checkpoint_conf.resume_from), (
|
assert os.path.exists(
|
||||||
f"The 'resume_from' checkpoint {self.checkpoint_conf.resume_from} does not exist!"
|
self.checkpoint_conf.resume_from
|
||||||
)
|
), f"The 'resume_from' checkpoint {self.checkpoint_conf.resume_from} does not exist!"
|
||||||
dst = os.path.join(self.checkpoint_conf.save_dir, "checkpoint.pt")
|
dst = os.path.join(self.checkpoint_conf.save_dir, "checkpoint.pt")
|
||||||
if self.distributed_rank == 0 and not os.path.exists(dst):
|
if self.distributed_rank == 0 and not os.path.exists(dst):
|
||||||
# Copy the "resume_from" checkpoint to the checkpoint folder
|
# Copy the "resume_from" checkpoint to the checkpoint folder
|
||||||
@@ -471,9 +471,9 @@ class Trainer:
|
|||||||
return self.loss[key]
|
return self.loss[key]
|
||||||
|
|
||||||
assert key != "all", "Loss must be specified for key='all'"
|
assert key != "all", "Loss must be specified for key='all'"
|
||||||
assert "default" in self.loss, (
|
assert (
|
||||||
f"Key {key} not found in losss, and no default provided"
|
"default" in self.loss
|
||||||
)
|
), f"Key {key} not found in losss, and no default provided"
|
||||||
return self.loss["default"]
|
return self.loss["default"]
|
||||||
|
|
||||||
def _find_meter(self, phase: str, key: str):
|
def _find_meter(self, phase: str, key: str):
|
||||||
@@ -916,12 +916,12 @@ class Trainer:
|
|||||||
self.optim.zero_grad(set_to_none=True)
|
self.optim.zero_grad(set_to_none=True)
|
||||||
|
|
||||||
if self.gradient_accumulation_steps > 1:
|
if self.gradient_accumulation_steps > 1:
|
||||||
assert isinstance(batch, list), (
|
assert isinstance(
|
||||||
f"Expected a list of batches, got {type(batch)}"
|
batch, list
|
||||||
)
|
), f"Expected a list of batches, got {type(batch)}"
|
||||||
assert len(batch) == self.gradient_accumulation_steps, (
|
assert (
|
||||||
f"Expected {self.gradient_accumulation_steps} batches, got {len(batch)}"
|
len(batch) == self.gradient_accumulation_steps
|
||||||
)
|
), f"Expected {self.gradient_accumulation_steps} batches, got {len(batch)}"
|
||||||
accum_steps = len(batch)
|
accum_steps = len(batch)
|
||||||
else:
|
else:
|
||||||
accum_steps = 1
|
accum_steps = 1
|
||||||
@@ -1033,9 +1033,9 @@ class Trainer:
|
|||||||
def _check_val_key_match(self, val_keys, phase):
|
def _check_val_key_match(self, val_keys, phase):
|
||||||
if val_keys is not None:
|
if val_keys is not None:
|
||||||
# Check if there are any duplicates
|
# Check if there are any duplicates
|
||||||
assert len(val_keys) == len(set(val_keys)), (
|
assert len(val_keys) == len(
|
||||||
f"Duplicate keys in val datasets, keys: {val_keys}"
|
set(val_keys)
|
||||||
)
|
), f"Duplicate keys in val datasets, keys: {val_keys}"
|
||||||
|
|
||||||
# Check that the keys match the meter keys
|
# Check that the keys match the meter keys
|
||||||
if self.meters_conf is not None and phase in self.meters_conf:
|
if self.meters_conf is not None and phase in self.meters_conf:
|
||||||
@@ -1049,9 +1049,9 @@ class Trainer:
|
|||||||
loss_keys = set(self.loss_conf.keys()) - set(["all"])
|
loss_keys = set(self.loss_conf.keys()) - set(["all"])
|
||||||
if "default" not in loss_keys:
|
if "default" not in loss_keys:
|
||||||
for k in val_keys:
|
for k in val_keys:
|
||||||
assert k in loss_keys, (
|
assert (
|
||||||
f"Error: key {k} is not defined in the losses, and no default is set"
|
k in loss_keys
|
||||||
)
|
), f"Error: key {k} is not defined in the losses, and no default is set"
|
||||||
|
|
||||||
def _setup_components(self):
|
def _setup_components(self):
|
||||||
# Get the keys for all the val datasets, if any
|
# Get the keys for all the val datasets, if any
|
||||||
|
|||||||
@@ -276,9 +276,9 @@ class RandomSizeCrop:
|
|||||||
max(0, minY - h + 1), max(maxY - 1, max(0, minY - h + 1))
|
max(0, minY - h + 1), max(maxY - 1, max(0, minY - h + 1))
|
||||||
)
|
)
|
||||||
result_img, result_target = crop(img, target, [j, i, h, w])
|
result_img, result_target = crop(img, target, [j, i, h, w])
|
||||||
assert len(result_target["boxes"]) == init_boxes, (
|
assert (
|
||||||
f"img_w={img.width}\timg_h={img.height}\tminX={minX}\tminY={minY}\tmaxX={maxX}\tmaxY={maxY}\tminW={minW}\tminH={minH}\tmaxW={maxW}\tmaxH={maxH}\tw={w}\th={h}\ti={i}\tj={j}\tinit_boxes={init_boxes_tensor}\tresults={result_target['boxes']}"
|
len(result_target["boxes"]) == init_boxes
|
||||||
)
|
), f"img_w={img.width}\timg_h={img.height}\tminX={minX}\tminY={minY}\tmaxX={maxX}\tmaxY={maxY}\tminW={minW}\tminH={minH}\tmaxW={maxW}\tmaxH={maxH}\tw={w}\th={h}\ti={i}\tj={j}\tinit_boxes={init_boxes_tensor}\tresults={result_target['boxes']}"
|
||||||
|
|
||||||
return result_img, result_target
|
return result_img, result_target
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -379,9 +379,9 @@ class FlexibleFilterFindGetQueries:
|
|||||||
if len(new_find_queries) == 0:
|
if len(new_find_queries) == 0:
|
||||||
start_with_zero_check = True
|
start_with_zero_check = True
|
||||||
|
|
||||||
assert start_with_zero_check, (
|
assert (
|
||||||
"Invalid Find queries, they need to start at query_processing_order = 0"
|
start_with_zero_check
|
||||||
)
|
), "Invalid Find queries, they need to start at query_processing_order = 0"
|
||||||
|
|
||||||
datapoint.find_queries = new_find_queries
|
datapoint.find_queries = new_find_queries
|
||||||
|
|
||||||
|
|||||||
@@ -249,9 +249,9 @@ class RandomGeometricInputsAPI:
|
|||||||
def _get_target_object(self, datapoint, query):
|
def _get_target_object(self, datapoint, query):
|
||||||
img = datapoint.images[query.image_id]
|
img = datapoint.images[query.image_id]
|
||||||
targets = query.object_ids_output
|
targets = query.object_ids_output
|
||||||
assert len(targets) == 1, (
|
assert (
|
||||||
"Geometric queries only support a single target object."
|
len(targets) == 1
|
||||||
)
|
), "Geometric queries only support a single target object."
|
||||||
target_idx = targets[0]
|
target_idx = targets[0]
|
||||||
return img.objects[target_idx]
|
return img.objects[target_idx]
|
||||||
|
|
||||||
|
|||||||
@@ -36,9 +36,9 @@ def unix_pattern_to_parameter_names(
|
|||||||
parameter_names = []
|
parameter_names = []
|
||||||
for param_name in constraints:
|
for param_name in constraints:
|
||||||
matching_parameters = set(fnmatch.filter(all_parameter_names, param_name))
|
matching_parameters = set(fnmatch.filter(all_parameter_names, param_name))
|
||||||
assert len(matching_parameters) > 0, (
|
assert (
|
||||||
f"param_names {param_name} don't match any param in the given names."
|
len(matching_parameters) > 0
|
||||||
)
|
), f"param_names {param_name} don't match any param in the given names."
|
||||||
parameter_names.append(matching_parameters)
|
parameter_names.append(matching_parameters)
|
||||||
return set.union(*parameter_names)
|
return set.union(*parameter_names)
|
||||||
|
|
||||||
|
|||||||
@@ -82,9 +82,9 @@ def get_machine_local_and_dist_rank():
|
|||||||
"""
|
"""
|
||||||
local_rank = int(os.environ.get("LOCAL_RANK", None))
|
local_rank = int(os.environ.get("LOCAL_RANK", None))
|
||||||
distributed_rank = int(os.environ.get("RANK", None))
|
distributed_rank = int(os.environ.get("RANK", None))
|
||||||
assert local_rank is not None and distributed_rank is not None, (
|
assert (
|
||||||
"Please the set the RANK and LOCAL_RANK environment variables."
|
local_rank is not None and distributed_rank is not None
|
||||||
)
|
), "Please the set the RANK and LOCAL_RANK environment variables."
|
||||||
return local_rank, distributed_rank
|
return local_rank, distributed_rank
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+15
-15
@@ -158,22 +158,22 @@ def plot_mask(mask, color="r", ax=None):
|
|||||||
def normalize_bbox(bbox_xywh, img_w, img_h):
|
def normalize_bbox(bbox_xywh, img_w, img_h):
|
||||||
# Assumes bbox_xywh is in XYWH format
|
# Assumes bbox_xywh is in XYWH format
|
||||||
if isinstance(bbox_xywh, list):
|
if isinstance(bbox_xywh, list):
|
||||||
assert len(bbox_xywh) == 4, (
|
assert (
|
||||||
"bbox_xywh list must have 4 elements. Batching not support except for torch tensors."
|
len(bbox_xywh) == 4
|
||||||
)
|
), "bbox_xywh list must have 4 elements. Batching not support except for torch tensors."
|
||||||
normalized_bbox = bbox_xywh.copy()
|
normalized_bbox = bbox_xywh.copy()
|
||||||
normalized_bbox[0] /= img_w
|
normalized_bbox[0] /= img_w
|
||||||
normalized_bbox[1] /= img_h
|
normalized_bbox[1] /= img_h
|
||||||
normalized_bbox[2] /= img_w
|
normalized_bbox[2] /= img_w
|
||||||
normalized_bbox[3] /= img_h
|
normalized_bbox[3] /= img_h
|
||||||
else:
|
else:
|
||||||
assert isinstance(bbox_xywh, torch.Tensor), (
|
assert isinstance(
|
||||||
"Only torch tensors are supported for batching."
|
bbox_xywh, torch.Tensor
|
||||||
)
|
), "Only torch tensors are supported for batching."
|
||||||
normalized_bbox = bbox_xywh.clone()
|
normalized_bbox = bbox_xywh.clone()
|
||||||
assert normalized_bbox.size(-1) == 4, (
|
assert (
|
||||||
"bbox_xywh tensor must have last dimension of size 4."
|
normalized_bbox.size(-1) == 4
|
||||||
)
|
), "bbox_xywh tensor must have last dimension of size 4."
|
||||||
normalized_bbox[..., 0] /= img_w
|
normalized_bbox[..., 0] /= img_w
|
||||||
normalized_bbox[..., 1] /= img_h
|
normalized_bbox[..., 1] /= img_h
|
||||||
normalized_bbox[..., 2] /= img_w
|
normalized_bbox[..., 2] /= img_w
|
||||||
@@ -245,9 +245,9 @@ def visualize_formatted_frame_output(
|
|||||||
num_outputs = len(outputs_list)
|
num_outputs = len(outputs_list)
|
||||||
if titles is None:
|
if titles is None:
|
||||||
titles = [f"Set {i + 1}" for i in range(num_outputs)]
|
titles = [f"Set {i + 1}" for i in range(num_outputs)]
|
||||||
assert len(titles) == num_outputs, (
|
assert (
|
||||||
"length of `titles` should match that of `outputs_list` if not None."
|
len(titles) == num_outputs
|
||||||
)
|
), "length of `titles` should match that of `outputs_list` if not None."
|
||||||
|
|
||||||
_, axes = plt.subplots(1, num_outputs, figsize=figsize)
|
_, axes = plt.subplots(1, num_outputs, figsize=figsize)
|
||||||
if num_outputs == 1:
|
if num_outputs == 1:
|
||||||
@@ -703,9 +703,9 @@ def get_all_annotations_for_frame(
|
|||||||
|
|
||||||
# Get the frame
|
# Get the frame
|
||||||
video_df_current = video_df[video_df.id == video_id]
|
video_df_current = video_df[video_df.id == video_id]
|
||||||
assert len(video_df_current) == 1, (
|
assert (
|
||||||
f"Expected 1 video row, got {len(video_df_current)}"
|
len(video_df_current) == 1
|
||||||
)
|
), f"Expected 1 video row, got {len(video_df_current)}"
|
||||||
video_row = video_df_current.iloc[0]
|
video_row = video_df_current.iloc[0]
|
||||||
file_name = video_row.file_names[frame_idx]
|
file_name = video_row.file_names[frame_idx]
|
||||||
file_path = os.path.join(
|
file_path = os.path.join(
|
||||||
|
|||||||
@@ -243,9 +243,9 @@ def download_sav():
|
|||||||
def main():
|
def main():
|
||||||
assert len(sys.argv) > 1, "You have to provide the name of the dataset"
|
assert len(sys.argv) > 1, "You have to provide the name of the dataset"
|
||||||
dataset_name = sys.argv[1]
|
dataset_name = sys.argv[1]
|
||||||
assert dataset_name in annotation_files, (
|
assert (
|
||||||
f"The dataset can be one of {list(annotation_files.keys())}"
|
dataset_name in annotation_files
|
||||||
)
|
), f"The dataset can be one of {list(annotation_files.keys())}"
|
||||||
|
|
||||||
if dataset_name == "yt1b":
|
if dataset_name == "yt1b":
|
||||||
download_youtube()
|
download_youtube()
|
||||||
|
|||||||
@@ -68,9 +68,9 @@ def process_image(args):
|
|||||||
def main():
|
def main():
|
||||||
assert len(sys.argv) > 1, "You have to provide the name of the dataset"
|
assert len(sys.argv) > 1, "You have to provide the name of the dataset"
|
||||||
dataset_name = sys.argv[1]
|
dataset_name = sys.argv[1]
|
||||||
assert dataset_name in annotation_files, (
|
assert (
|
||||||
f"The dataset can be one of {list(annotation_files.keys())}"
|
dataset_name in annotation_files
|
||||||
)
|
), f"The dataset can be one of {list(annotation_files.keys())}"
|
||||||
all_outputs = []
|
all_outputs = []
|
||||||
for file in annotation_files[dataset_name]:
|
for file in annotation_files[dataset_name]:
|
||||||
with open(os.path.join(config["path_annotations"], file), "r") as f:
|
with open(os.path.join(config["path_annotations"], file), "r") as f:
|
||||||
|
|||||||
@@ -58,9 +58,9 @@ class YtVideoPrep:
|
|||||||
df = self.yt1b_start_end_time_df[
|
df = self.yt1b_start_end_time_df[
|
||||||
self.yt1b_start_end_time_df.saco_yt1b_id == self.saco_yt1b_id
|
self.yt1b_start_end_time_df.saco_yt1b_id == self.saco_yt1b_id
|
||||||
]
|
]
|
||||||
assert len(df) == 1, (
|
assert (
|
||||||
f"Expected exactly 1 row for saco_yt1b_id: {self.saco_yt1b_id}, found {len(df)}"
|
len(df) == 1
|
||||||
)
|
), f"Expected exactly 1 row for saco_yt1b_id: {self.saco_yt1b_id}, found {len(df)}"
|
||||||
id_and_frame_map_row = df.iloc[0]
|
id_and_frame_map_row = df.iloc[0]
|
||||||
|
|
||||||
yt_video_id = (
|
yt_video_id = (
|
||||||
@@ -82,9 +82,9 @@ class YtVideoPrep:
|
|||||||
def download_youtube_video(self):
|
def download_youtube_video(self):
|
||||||
video_url = f"https://youtube.com/watch?v={self.yt_video_id}"
|
video_url = f"https://youtube.com/watch?v={self.yt_video_id}"
|
||||||
|
|
||||||
assert os.path.exists(self.cookies_file), (
|
assert os.path.exists(
|
||||||
f"Cookies file '{self.cookies_file}' not found. Must have it to download videos."
|
self.cookies_file
|
||||||
)
|
), f"Cookies file '{self.cookies_file}' not found. Must have it to download videos."
|
||||||
|
|
||||||
outtmpl = self.raw_video_path
|
outtmpl = self.raw_video_path
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,304 @@
|
|||||||
|
"""
|
||||||
|
SAM3 Speed Test — supports both SAM3 and SAM3.1 (multiplex).
|
||||||
|
|
||||||
|
Generates synthetic video with moving circles, runs text-prompt detection
|
||||||
|
+ propagation, and measures FPS. Checkpoints are auto-downloaded from
|
||||||
|
HuggingFace if not provided.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
# SAM 3.1 (default, auto-downloads from HuggingFace):
|
||||||
|
python scripts/measure_speed.py
|
||||||
|
|
||||||
|
# SAM 3 (non-multiplex):
|
||||||
|
python scripts/measure_speed.py --version sam3
|
||||||
|
|
||||||
|
# Custom settings:
|
||||||
|
python scripts/measure_speed.py --num_objects 32 --n_frames 100 --no-compile
|
||||||
|
python scripts/measure_speed.py --version sam3.1 --compile --num_objects 5
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import getpass
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import time
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
|
||||||
|
def max_memory_allocated():
|
||||||
|
max_memory_allocated_bytes = torch.cuda.max_memory_allocated()
|
||||||
|
_, total_memory = torch.cuda.mem_get_info()
|
||||||
|
max_memory_allocated_percentage = int(
|
||||||
|
100 * (max_memory_allocated_bytes / total_memory)
|
||||||
|
)
|
||||||
|
max_memory_allocated_bytes = max_memory_allocated_bytes >> 20
|
||||||
|
print(
|
||||||
|
f"max_memory_allocated_bytes: {max_memory_allocated_bytes}MiB or {max_memory_allocated_percentage}%"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def synthesize_video_data(
|
||||||
|
num_objects: int,
|
||||||
|
out_dir: str,
|
||||||
|
radius: int,
|
||||||
|
speed: int,
|
||||||
|
width: int,
|
||||||
|
height: int,
|
||||||
|
n_frames: int,
|
||||||
|
):
|
||||||
|
circle_colors = [
|
||||||
|
tuple(np.random.randint(0, 256, size=3).tolist()) for _ in range(num_objects)
|
||||||
|
]
|
||||||
|
|
||||||
|
if os.path.exists(out_dir):
|
||||||
|
shutil.rmtree(out_dir)
|
||||||
|
os.makedirs(out_dir, exist_ok=True)
|
||||||
|
|
||||||
|
positions = []
|
||||||
|
velocities = []
|
||||||
|
for _ in range(num_objects):
|
||||||
|
px = float(np.random.randint(radius, width - radius))
|
||||||
|
py = float(np.random.randint(radius, height - radius))
|
||||||
|
vx = np.random.choice([-1, 1]) * speed
|
||||||
|
vy = np.random.choice([-1, 1]) * speed
|
||||||
|
positions.append([px, py])
|
||||||
|
velocities.append([vx, vy])
|
||||||
|
|
||||||
|
print(f"Generate {n_frames} frames with {num_objects} objects")
|
||||||
|
for i in range(n_frames):
|
||||||
|
img = Image.new("RGB", (width, height), (0, 0, 0))
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
for obj_idx in range(num_objects):
|
||||||
|
x, y = positions[obj_idx]
|
||||||
|
rx, ry = round(x), round(y)
|
||||||
|
draw.ellipse(
|
||||||
|
[(rx - radius, ry - radius), (rx + radius, ry + radius)],
|
||||||
|
fill=circle_colors[obj_idx],
|
||||||
|
)
|
||||||
|
vx, vy = velocities[obj_idx]
|
||||||
|
x += vx
|
||||||
|
y += vy
|
||||||
|
positions[obj_idx] = [
|
||||||
|
np.clip(x, radius, width - radius),
|
||||||
|
np.clip(y, radius, height - radius),
|
||||||
|
]
|
||||||
|
if x - radius < 0 or x + radius > width:
|
||||||
|
vx *= -1
|
||||||
|
if y - radius < 0 or y + radius > height:
|
||||||
|
vy *= -1
|
||||||
|
velocities[obj_idx] = [vx, vy]
|
||||||
|
|
||||||
|
img.save(os.path.join(out_dir, f"{i:03d}.jpg"))
|
||||||
|
|
||||||
|
|
||||||
|
def profiler_runner(fn, profile_save_dir=None, profile_end_frame=-1, *args, **kwargs):
|
||||||
|
if profile_save_dir is None:
|
||||||
|
profile_save_dir = os.path.expanduser("~/traces")
|
||||||
|
|
||||||
|
os.environ["ENABLE_PROFILING"] = "1"
|
||||||
|
os.environ["PROFILE_SAVE_DIR"] = profile_save_dir
|
||||||
|
if profile_end_frame >= 0:
|
||||||
|
os.environ["PROFILE_END_FRAME"] = str(profile_end_frame)
|
||||||
|
|
||||||
|
print(f"Profiling enabled. Traces will be saved to: {profile_save_dir}")
|
||||||
|
if profile_end_frame >= 0:
|
||||||
|
print(f"Profiling will stop at frame: {profile_end_frame}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = fn(*args, **kwargs)
|
||||||
|
finally:
|
||||||
|
os.environ.pop("ENABLE_PROFILING", None)
|
||||||
|
os.environ.pop("PROFILE_SAVE_DIR", None)
|
||||||
|
os.environ.pop("PROFILE_END_FRAME", None)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def main_loop(model_wrapper, session_id, text_prompt):
|
||||||
|
model_wrapper.handle_request({"type": "reset_session", "session_id": session_id})
|
||||||
|
model_wrapper.handle_request(
|
||||||
|
{
|
||||||
|
"type": "add_prompt",
|
||||||
|
"session_id": session_id,
|
||||||
|
"frame_index": 0,
|
||||||
|
"text": text_prompt,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
frame_count = 0
|
||||||
|
for _response in model_wrapper.handle_stream_request(
|
||||||
|
{"type": "propagate_in_video", "session_id": session_id}
|
||||||
|
):
|
||||||
|
frame_count += 1
|
||||||
|
torch.cuda.synchronize()
|
||||||
|
t1 = time.perf_counter()
|
||||||
|
|
||||||
|
if frame_count > 0:
|
||||||
|
return frame_count / (t1 - t0)
|
||||||
|
return -1
|
||||||
|
|
||||||
|
|
||||||
|
def run_test(
|
||||||
|
version: str,
|
||||||
|
profile: bool,
|
||||||
|
video_dir: str,
|
||||||
|
num_objects: int,
|
||||||
|
radius: int,
|
||||||
|
speed: int,
|
||||||
|
width: int,
|
||||||
|
height: int,
|
||||||
|
n_frames: int,
|
||||||
|
synthesize_data: bool = True,
|
||||||
|
profile_save_dir: str = None,
|
||||||
|
profile_end_frame: int = -1,
|
||||||
|
do_compile: bool = True,
|
||||||
|
checkpoint_path: str = None,
|
||||||
|
) -> float:
|
||||||
|
torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
|
||||||
|
|
||||||
|
if synthesize_data:
|
||||||
|
synthesize_video_data(
|
||||||
|
num_objects=num_objects,
|
||||||
|
out_dir=video_dir,
|
||||||
|
radius=radius,
|
||||||
|
speed=speed,
|
||||||
|
width=width,
|
||||||
|
height=height,
|
||||||
|
n_frames=n_frames,
|
||||||
|
)
|
||||||
|
|
||||||
|
from sam3 import build_sam3_predictor
|
||||||
|
|
||||||
|
print(f"Building {version} model...")
|
||||||
|
build_kwargs = dict(
|
||||||
|
version=version,
|
||||||
|
compile=do_compile,
|
||||||
|
async_loading_frames=False,
|
||||||
|
)
|
||||||
|
if checkpoint_path:
|
||||||
|
build_kwargs["checkpoint_path"] = checkpoint_path
|
||||||
|
if version == "sam3.1":
|
||||||
|
build_kwargs["warm_up"] = do_compile
|
||||||
|
build_kwargs["max_num_objects"] = num_objects
|
||||||
|
|
||||||
|
model_wrapper = build_sam3_predictor(**build_kwargs)
|
||||||
|
|
||||||
|
# Initialize session
|
||||||
|
response = model_wrapper.handle_request(
|
||||||
|
{"type": "start_session", "resource_path": video_dir}
|
||||||
|
)
|
||||||
|
session_id = response["session_id"]
|
||||||
|
|
||||||
|
print("\nWarm-up round.")
|
||||||
|
NUM_WARMUP_TRIES = 3
|
||||||
|
fps = 0
|
||||||
|
for _ in range(NUM_WARMUP_TRIES):
|
||||||
|
fps = max(
|
||||||
|
main_loop(
|
||||||
|
model_wrapper=model_wrapper, session_id=session_id, text_prompt="circle"
|
||||||
|
),
|
||||||
|
fps,
|
||||||
|
)
|
||||||
|
|
||||||
|
print("\nProfile round.")
|
||||||
|
if profile:
|
||||||
|
profiler_runner(
|
||||||
|
main_loop,
|
||||||
|
profile_save_dir=profile_save_dir or os.path.expanduser("~/traces"),
|
||||||
|
profile_end_frame=profile_end_frame,
|
||||||
|
model_wrapper=model_wrapper,
|
||||||
|
session_id=session_id,
|
||||||
|
text_prompt="circle",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
fps = max(
|
||||||
|
main_loop(
|
||||||
|
model_wrapper=model_wrapper, session_id=session_id, text_prompt="circle"
|
||||||
|
),
|
||||||
|
fps,
|
||||||
|
)
|
||||||
|
|
||||||
|
NUM_TRIES = 10
|
||||||
|
for i in range(NUM_TRIES):
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
torch.cuda.reset_peak_memory_stats()
|
||||||
|
print(f"\nTiming round {i + 1} ")
|
||||||
|
fps = max(
|
||||||
|
main_loop(
|
||||||
|
model_wrapper=model_wrapper, session_id=session_id, text_prompt="circle"
|
||||||
|
),
|
||||||
|
fps,
|
||||||
|
)
|
||||||
|
print(f"Frames per second (FPS): {fps:.2f}")
|
||||||
|
max_memory_allocated()
|
||||||
|
|
||||||
|
if synthesize_data:
|
||||||
|
print("\nDeleting temporary video directory.")
|
||||||
|
shutil.rmtree(video_dir)
|
||||||
|
|
||||||
|
return fps
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
username = getpass.getuser()
|
||||||
|
os.environ["TORCHINDUCTOR_CACHE_DIR"] = f"/tmp/torchinductor_cache_{username}"
|
||||||
|
os.environ["USE_PERFLIB"] = "1"
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="SAM3 Speed Test")
|
||||||
|
parser.add_argument(
|
||||||
|
"--version",
|
||||||
|
type=str,
|
||||||
|
default="sam3.1",
|
||||||
|
choices=["sam3", "sam3.1"],
|
||||||
|
help="Model version (default: sam3.1)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--checkpoint",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Path to checkpoint (auto-downloads from HuggingFace if not provided)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--video_dir", type=str, default="/tmp/segment-anything-3/synth_video"
|
||||||
|
)
|
||||||
|
parser.add_argument("--num_objects", type=int, default=5)
|
||||||
|
parser.add_argument("--n_frames", type=int, default=50)
|
||||||
|
parser.add_argument("--radius", type=int, default=50)
|
||||||
|
parser.add_argument("--speed", type=int, default=20)
|
||||||
|
parser.add_argument("--width", type=int, default=1024)
|
||||||
|
parser.add_argument("--height", type=int, default=1024)
|
||||||
|
parser.add_argument(
|
||||||
|
"--no-compile",
|
||||||
|
action="store_false",
|
||||||
|
dest="compile",
|
||||||
|
help="Disable torch.compile",
|
||||||
|
)
|
||||||
|
parser.add_argument("--no-torch-profiling", action="store_false", dest="profile")
|
||||||
|
parser.add_argument(
|
||||||
|
"--no-data-synthesis", action="store_false", dest="synthesize_data"
|
||||||
|
)
|
||||||
|
parser.add_argument("--profile-save-dir", type=str, default=None)
|
||||||
|
parser.add_argument("--profile-end-frame", type=int, default=-1)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
run_test(
|
||||||
|
version=args.version,
|
||||||
|
profile=args.profile,
|
||||||
|
num_objects=args.num_objects,
|
||||||
|
video_dir=args.video_dir,
|
||||||
|
radius=args.radius,
|
||||||
|
speed=args.speed,
|
||||||
|
width=args.width,
|
||||||
|
height=args.height,
|
||||||
|
n_frames=args.n_frames,
|
||||||
|
synthesize_data=args.synthesize_data,
|
||||||
|
profile_save_dir=args.profile_save_dir,
|
||||||
|
profile_end_frame=args.profile_end_frame,
|
||||||
|
do_compile=args.compile,
|
||||||
|
checkpoint_path=args.checkpoint,
|
||||||
|
)
|
||||||
@@ -0,0 +1,312 @@
|
|||||||
|
"""
|
||||||
|
SAM3 Qualitative Test — supports both SAM3 and SAM3.1.
|
||||||
|
|
||||||
|
Tests text prompt detection + propagation on a synthetic video.
|
||||||
|
Checkpoints are auto-downloaded from HuggingFace.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python scripts/qualitative_test.py # SAM 3.1 default
|
||||||
|
python scripts/qualitative_test.py --version sam3 # SAM 3
|
||||||
|
python scripts/qualitative_test.py --video /path/to/video.mp4
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import getpass
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
import cv2
|
||||||
|
import matplotlib
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from PIL import Image as PIL_Image, ImageDraw
|
||||||
|
|
||||||
|
matplotlib.use("Agg")
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
from PIL import Image as PIL_Image, ImageDraw
|
||||||
|
|
||||||
|
|
||||||
|
OUTPUT_DIR = "/tmp/sam3_qualitative_test"
|
||||||
|
|
||||||
|
MASK_COLORS = [
|
||||||
|
(255, 0, 0),
|
||||||
|
(0, 255, 0),
|
||||||
|
(0, 0, 255),
|
||||||
|
(255, 255, 0),
|
||||||
|
(255, 0, 255),
|
||||||
|
(0, 255, 255),
|
||||||
|
(255, 128, 0),
|
||||||
|
(128, 0, 255),
|
||||||
|
(0, 128, 255),
|
||||||
|
(255, 64, 128),
|
||||||
|
(128, 255, 0),
|
||||||
|
(64, 128, 255),
|
||||||
|
(255, 200, 0),
|
||||||
|
(0, 200, 128),
|
||||||
|
(200, 0, 128),
|
||||||
|
(128, 128, 255),
|
||||||
|
(255, 128, 128),
|
||||||
|
(128, 255, 128),
|
||||||
|
(128, 128, 0),
|
||||||
|
(0, 128, 128),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def extract_frames(video_path, output_dir):
|
||||||
|
if os.path.exists(output_dir) and len(os.listdir(output_dir)) > 0:
|
||||||
|
n = len([f for f in os.listdir(output_dir) if f.endswith(".jpg")])
|
||||||
|
print(f"Using existing {n} frames in {output_dir}")
|
||||||
|
return n
|
||||||
|
if os.path.exists(output_dir):
|
||||||
|
shutil.rmtree(output_dir)
|
||||||
|
os.makedirs(output_dir)
|
||||||
|
cap = cv2.VideoCapture(video_path)
|
||||||
|
idx = 0
|
||||||
|
while True:
|
||||||
|
ret, frame = cap.read()
|
||||||
|
if not ret:
|
||||||
|
break
|
||||||
|
cv2.imwrite(os.path.join(output_dir, f"{idx:05d}.jpg"), frame)
|
||||||
|
idx += 1
|
||||||
|
cap.release()
|
||||||
|
print(f"Extracted {idx} frames to {output_dir}")
|
||||||
|
return idx
|
||||||
|
|
||||||
|
|
||||||
|
def synthesize_video(out_dir, num_objects=5, n_frames=30, width=1024, height=1024):
|
||||||
|
if os.path.exists(out_dir):
|
||||||
|
shutil.rmtree(out_dir)
|
||||||
|
os.makedirs(out_dir)
|
||||||
|
colors = [
|
||||||
|
tuple(np.random.randint(0, 256, size=3).tolist()) for _ in range(num_objects)
|
||||||
|
]
|
||||||
|
positions = [
|
||||||
|
[
|
||||||
|
float(np.random.randint(80, width - 80)),
|
||||||
|
float(np.random.randint(80, height - 80)),
|
||||||
|
]
|
||||||
|
for _ in range(num_objects)
|
||||||
|
]
|
||||||
|
velocities = [
|
||||||
|
[np.random.choice([-1, 1]) * 15, np.random.choice([-1, 1]) * 15]
|
||||||
|
for _ in range(num_objects)
|
||||||
|
]
|
||||||
|
for i in range(n_frames):
|
||||||
|
img = PIL_Image.new("RGB", (width, height), (0, 0, 0))
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
for j in range(num_objects):
|
||||||
|
x, y = positions[j]
|
||||||
|
draw.ellipse([(x - 50, y - 50), (x + 50, y + 50)], fill=colors[j])
|
||||||
|
vx, vy = velocities[j]
|
||||||
|
positions[j] = [
|
||||||
|
np.clip(x + vx, 50, width - 50),
|
||||||
|
np.clip(y + vy, 50, height - 50),
|
||||||
|
]
|
||||||
|
if x < 50 or x > width - 50:
|
||||||
|
velocities[j][0] *= -1
|
||||||
|
if y < 50 or y > height - 50:
|
||||||
|
velocities[j][1] *= -1
|
||||||
|
img.save(os.path.join(out_dir, f"{i:05d}.jpg"))
|
||||||
|
print(f"Generated {n_frames} synthetic frames with {num_objects} circles")
|
||||||
|
return n_frames
|
||||||
|
|
||||||
|
|
||||||
|
def load_frame(frame_dir, frame_idx):
|
||||||
|
return cv2.cvtColor(
|
||||||
|
cv2.imread(os.path.join(frame_dir, f"{frame_idx:05d}.jpg")),
|
||||||
|
cv2.COLOR_BGR2RGB,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def render_overlay(frame_rgb, masks_by_obj, alpha=0.4):
|
||||||
|
overlay = frame_rgb.copy().astype(np.float32)
|
||||||
|
for obj_id, mask in sorted(masks_by_obj.items()):
|
||||||
|
color = MASK_COLORS[obj_id % len(MASK_COLORS)]
|
||||||
|
mask_bool = mask.astype(bool)
|
||||||
|
for c in range(3):
|
||||||
|
overlay[:, :, c] = np.where(
|
||||||
|
mask_bool,
|
||||||
|
overlay[:, :, c] * (1 - alpha) + color[c] * alpha,
|
||||||
|
overlay[:, :, c],
|
||||||
|
)
|
||||||
|
return overlay.astype(np.uint8)
|
||||||
|
|
||||||
|
|
||||||
|
def save_overlay(frame_rgb, masks_by_obj, output_path, title=None):
|
||||||
|
overlay = render_overlay(frame_rgb, masks_by_obj)
|
||||||
|
fig, ax = plt.subplots(1, 1, figsize=(12, 7), dpi=100)
|
||||||
|
ax.imshow(overlay)
|
||||||
|
for obj_id, mask in sorted(masks_by_obj.items()):
|
||||||
|
mask_bool = mask.astype(bool)
|
||||||
|
if mask_bool.any():
|
||||||
|
ys, xs = np.where(mask_bool)
|
||||||
|
cx, cy = int(xs.mean()), int(ys.mean())
|
||||||
|
color_rgb = MASK_COLORS[obj_id % len(MASK_COLORS)]
|
||||||
|
facecolor = (color_rgb[0] / 255, color_rgb[1] / 255, color_rgb[2] / 255)
|
||||||
|
ax.text(
|
||||||
|
cx,
|
||||||
|
cy,
|
||||||
|
str(obj_id),
|
||||||
|
color="white",
|
||||||
|
fontsize=10,
|
||||||
|
ha="center",
|
||||||
|
va="center",
|
||||||
|
fontweight="bold",
|
||||||
|
bbox=dict(boxstyle="round,pad=0.2", facecolor=facecolor, alpha=0.8),
|
||||||
|
)
|
||||||
|
if title:
|
||||||
|
ax.set_title(title, fontsize=12, fontweight="bold", pad=8)
|
||||||
|
ax.axis("off")
|
||||||
|
fig.tight_layout(pad=0)
|
||||||
|
fig.savefig(output_path, bbox_inches="tight", pad_inches=0)
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
|
||||||
|
def collect_propagation(model, session_id):
|
||||||
|
mask_dict = {}
|
||||||
|
for response in model.handle_stream_request(
|
||||||
|
{"type": "propagate_in_video", "session_id": session_id}
|
||||||
|
):
|
||||||
|
frame_idx = response.get("frame_index")
|
||||||
|
if frame_idx is None:
|
||||||
|
continue
|
||||||
|
outputs = response.get("outputs", {})
|
||||||
|
obj_ids = outputs.get("out_obj_ids", [])
|
||||||
|
binary_masks = outputs.get("out_binary_masks")
|
||||||
|
if binary_masks is None:
|
||||||
|
mask_dict[frame_idx] = {}
|
||||||
|
continue
|
||||||
|
if isinstance(obj_ids, torch.Tensor):
|
||||||
|
obj_ids = obj_ids.cpu().numpy()
|
||||||
|
if isinstance(binary_masks, torch.Tensor):
|
||||||
|
binary_masks = binary_masks.cpu().numpy()
|
||||||
|
masks = {}
|
||||||
|
for i, oid in enumerate(obj_ids):
|
||||||
|
m = binary_masks[i]
|
||||||
|
if m.ndim == 3:
|
||||||
|
m = m[0]
|
||||||
|
masks[int(oid)] = m
|
||||||
|
mask_dict[frame_idx] = masks
|
||||||
|
torch.cuda.synchronize()
|
||||||
|
return mask_dict
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description="SAM3 Qualitative Test")
|
||||||
|
parser.add_argument(
|
||||||
|
"--version", type=str, default="sam3.1", choices=["sam3", "sam3.1"]
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--video",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Path to video file. If not provided, generates synthetic video.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--checkpoint",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Path to checkpoint (auto-downloads from HuggingFace if not provided)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--text_prompt", type=str, default="circle", help="Text prompt for detection"
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--n_frames", type=int, default=30, help="Number of frames for synthetic video"
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
username = getpass.getuser()
|
||||||
|
os.environ["TORCHINDUCTOR_CACHE_DIR"] = f"/tmp/torchinductor_cache_{username}"
|
||||||
|
os.environ["USE_PERFLIB"] = "1"
|
||||||
|
torch.autocast(device_type="cuda", dtype=torch.bfloat16).__enter__()
|
||||||
|
|
||||||
|
# Prepare video frames
|
||||||
|
frame_dir = "/tmp/sam3_qualitative_frames"
|
||||||
|
if args.video:
|
||||||
|
n_frames = extract_frames(args.video, frame_dir)
|
||||||
|
else:
|
||||||
|
n_frames = synthesize_video(frame_dir, n_frames=args.n_frames)
|
||||||
|
|
||||||
|
img = load_frame(frame_dir, 0)
|
||||||
|
img_h, img_w = img.shape[:2]
|
||||||
|
print(f"Video: {img_w}x{img_h}, {n_frames} frames")
|
||||||
|
|
||||||
|
# Build model
|
||||||
|
from sam3 import build_sam3_predictor
|
||||||
|
|
||||||
|
print(f"\nBuilding {args.version} model...")
|
||||||
|
build_kwargs = dict(version=args.version, compile=False, async_loading_frames=False)
|
||||||
|
if args.checkpoint:
|
||||||
|
build_kwargs["checkpoint_path"] = args.checkpoint
|
||||||
|
model = build_sam3_predictor(**build_kwargs)
|
||||||
|
|
||||||
|
# Start session
|
||||||
|
response = model.handle_request(
|
||||||
|
{"type": "start_session", "resource_path": frame_dir}
|
||||||
|
)
|
||||||
|
session_id = response["session_id"]
|
||||||
|
print(f"Session: {session_id}")
|
||||||
|
|
||||||
|
# Test: text prompt -> propagate
|
||||||
|
out_dir = os.path.join(OUTPUT_DIR, f"{args.version}_text_{args.text_prompt}")
|
||||||
|
if os.path.exists(out_dir):
|
||||||
|
shutil.rmtree(out_dir)
|
||||||
|
os.makedirs(out_dir)
|
||||||
|
|
||||||
|
print(f"\nTest: text prompt '{args.text_prompt}' -> propagate")
|
||||||
|
model.handle_request(
|
||||||
|
{
|
||||||
|
"type": "add_prompt",
|
||||||
|
"session_id": session_id,
|
||||||
|
"frame_index": 0,
|
||||||
|
"text": args.text_prompt,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
mask_dict = collect_propagation(model, session_id)
|
||||||
|
print(f"Propagated through {len(mask_dict)} frames")
|
||||||
|
|
||||||
|
# Save overlays
|
||||||
|
saved = 0
|
||||||
|
for frame_idx in sorted(mask_dict.keys()):
|
||||||
|
if frame_idx % 5 != 0:
|
||||||
|
continue
|
||||||
|
masks = mask_dict[frame_idx]
|
||||||
|
if not masks:
|
||||||
|
continue
|
||||||
|
frame_rgb = load_frame(frame_dir, frame_idx)
|
||||||
|
save_overlay(
|
||||||
|
frame_rgb,
|
||||||
|
masks,
|
||||||
|
os.path.join(out_dir, f"frame_{frame_idx:05d}.png"),
|
||||||
|
title=f"{args.version} | frame {frame_idx} | {len(masks)} objects",
|
||||||
|
)
|
||||||
|
saved += 1
|
||||||
|
|
||||||
|
# Print results
|
||||||
|
frame0 = mask_dict.get(0, {})
|
||||||
|
print(f"\nDetected {len(frame0)} objects on frame 0:")
|
||||||
|
for obj_id, mask in sorted(frame0.items()):
|
||||||
|
mask_bool = mask.astype(bool)
|
||||||
|
n_pixels = int(mask_bool.sum())
|
||||||
|
if mask_bool.any():
|
||||||
|
ys, xs = np.where(mask_bool)
|
||||||
|
print(
|
||||||
|
f" obj {obj_id}: centroid ({int(xs.mean())}, {int(ys.mean())}), {n_pixels} pixels"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"\nSaved {saved} overlay images to {out_dir}")
|
||||||
|
print(
|
||||||
|
"QUALITATIVE TEST PASSED"
|
||||||
|
if len(frame0) > 0
|
||||||
|
else "WARNING: No objects detected!"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
if not args.video:
|
||||||
|
shutil.rmtree(frame_dir)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user