Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sam2.1 #4

Closed
wants to merge 61 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
61 commits
Select commit Hold shift + click to select a range
658aaba
Use `weights_only` for loading
kit1980 Jul 29, 2024
b72a8a9
First draft
NielsRogge Aug 3, 2024
17b7450
Use classmethod
NielsRogge Aug 3, 2024
3af4e82
Add model_id_to_filenames
NielsRogge Aug 3, 2024
0c28c63
Do not load config from the hub
NielsRogge Aug 3, 2024
6aeee34
Make huggingface_hub soft dependency
NielsRogge Aug 5, 2024
cb48213
Update links
NielsRogge Aug 5, 2024
e93be7f
Update README
NielsRogge Aug 5, 2024
841cc1f
Update docstring
NielsRogge Aug 5, 2024
acd3939
Add workflow
haithamkhedr Aug 5, 2024
3b0fd9e
Update workflow
haithamkhedr Aug 5, 2024
5e3d6ca
Merge pull request #1 from haithamkhedr/CI
haithamkhedr Aug 5, 2024
0230c5f
Merge pull request #152 from haithamkhedr/main
haithamkhedr Aug 5, 2024
c3393d8
Include original code snippet
NielsRogge Aug 5, 2024
e9503c9
Move HF to separate section
NielsRogge Aug 5, 2024
fbf7e3a
Add link
NielsRogge Aug 5, 2024
e815f70
Address comment
NielsRogge Aug 6, 2024
a36edf1
Clean up
NielsRogge Aug 6, 2024
6f7e700
Make it optional to build CUDA extension for SAM 2; also fallback to …
ronghanghu Aug 6, 2024
27a167c
Update README
NielsRogge Aug 6, 2024
0bac418
Update INSTALL.md (#156)
jhj0517 Aug 6, 2024
8f15c62
Format using ufmt
NielsRogge Aug 6, 2024
511199d
Updated INSTALL.md with CUDA_HOME-related troubleshooting (#140)
AmmoniumX Aug 6, 2024
322aa3e
Revert code snippet
NielsRogge Aug 6, 2024
43c385c
Update docstrings
NielsRogge Aug 6, 2024
6ec8560
Update hieradet.py
arun477 Aug 7, 2024
9b58611
Address comment
NielsRogge Aug 7, 2024
6ba4c65
Merge pull request #128 from NielsRogge/add_hf
haithamkhedr Aug 7, 2024
086daf0
Merge branch 'main' into patch-1
arun477 Aug 7, 2024
6ecb5ff
Add interface for box prompt in SAM 2 video predictor (#174)
ronghanghu Aug 7, 2024
6186d15
also catch errors during installation in case `CUDAExtension` cannot …
ronghanghu Aug 7, 2024
102ddb8
Merge branch 'main' into patch-1
arun477 Aug 8, 2024
d421e0b
add Colab support to the notebooks; pack config files in `sam2_config…
ronghanghu Aug 8, 2024
46945a2
Update hieradet.py
arun477 Aug 9, 2024
8f607e2
Merge branch 'main' into patch-1
arun477 Aug 9, 2024
778e112
Merge pull request #167 from arun477/patch-1
chayryali Aug 9, 2024
1034ee2
better support for non-CUDA devices (CPU, MPS) (#192)
ronghanghu Aug 12, 2024
dce7b54
improving warning message and adding further tips for installation (#…
ronghanghu Aug 12, 2024
1191677
Fix HF image predictor
haithamkhedr Aug 12, 2024
fd5125b
accept kwargs in auto_mask_generator
haithamkhedr Aug 13, 2024
0db838b
Merge pull request #205 from facebookresearch/haitham/fix_hf_image_pr…
haithamkhedr Aug 13, 2024
7e1596c
open `README.md` with unicode (to support Hugging Face emoji); fix va…
ronghanghu Aug 14, 2024
0f6515a
Merge branch 'main' into patch-1
kit1980 Aug 26, 2024
aa9b872
SAM2.1
haithamkhedr Sep 28, 2024
3a7889d
Merge pull request #335 from facebookresearch/sam2.1
chayryali Sep 29, 2024
429a2c7
minor update README.md
ronghanghu Sep 29, 2024
05d9e57
[docs] add a release note and new installation instructions for SAM 2…
ronghanghu Sep 30, 2024
98fcb16
Update links after renaming the repo from `segment-anything-2` to `sa…
ronghanghu Oct 1, 2024
52198ea
Merge pull request #2 from kit1980/patch-1
haithamkhedr Oct 1, 2024
8bf0920
Add MANIFEST.in (#353)
haithamkhedr Oct 3, 2024
e225218
[demo] add GPU to resources (#355)
ronghanghu Oct 3, 2024
29267c8
[doc] Check and raise an error if the user is running Python from the…
ronghanghu Oct 5, 2024
ff9704f
[sam2][demo][1/x] Fix file upload
raedle Oct 8, 2024
c98aa6b
Merge pull request #364 from facebookresearch/pr364
raedle Oct 8, 2024
c2ec8e1
remove unused paths (#384)
haithamkhedr Oct 14, 2024
393ae33
SAM 2 Update 12/11/2024 -- full model compilation for a major VOS spe…
ronghanghu Dec 11, 2024
722d1d1
patch for the case of `offload_state_to_cpu=True` in the new `SAM2Vid…
ronghanghu Dec 12, 2024
2b90b9f
remove `.pin_memory()` in `obj_pos` of `SAM2Base` to resolve and erro…
ronghanghu Dec 16, 2024
7bd604e
In memory operations + adjustments
adam-encord Dec 16, 2024
90c4473
Merge branch 'main' into aj/sam2.1
adam-encord Dec 16, 2024
37767a3
Formatting
adam-encord Dec 16, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
17 changes: 17 additions & 0 deletions .github/workflows/check_fmt.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: SAM2/fmt
on:
pull_request:
branches:
- main
jobs:
ufmt_check:
runs-on: ubuntu-latest
steps:
- name: Check formatting
uses: omnilib/ufmt@action-v1
with:
path: sam2 tools
version: "2.0.0b2"
python-version: "3.10"
black-version: "24.2.0"
usort-version: "1.0.2"
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ build/*
_C.*
outputs/*
checkpoints/*.pt
demo/backend/checkpoints/*.pt
1 change: 1 addition & 0 deletions .watchmanconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
116 changes: 108 additions & 8 deletions INSTALL.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,40 @@

### Requirements

- Linux with Python ≥ 3.10, PyTorch ≥ 2.3.1 and [torchvision](https://github.com/pytorch/vision/) that matches the PyTorch installation. Install them together at https://pytorch.org to ensure this.
- Linux with Python ≥ 3.10, PyTorch ≥ 2.5.1 and [torchvision](https://github.com/pytorch/vision/) that matches the PyTorch installation. Install them together at https://pytorch.org to ensure this.
* Note older versions of Python or PyTorch may also work. However, the versions above are strongly recommended to provide all features such as `torch.compile`.
- [CUDA toolkits](https://developer.nvidia.com/cuda-toolkit-archive) that match the CUDA version for your PyTorch installation. This should typically be CUDA 12.1 if you follow the default installation command.
- If you are installing on Windows, it's strongly recommended to use [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/en-us/windows/wsl/install) with Ubuntu.

Then, install SAM 2 from the root of this repository via
```bash
pip install -e ".[demo]"
pip install -e ".[notebooks]"
```

Note that you may skip building the SAM 2 CUDA extension during installation via environment variable `SAM2_BUILD_CUDA=0`, as follows:
```bash
# skip the SAM 2 CUDA extension
SAM2_BUILD_CUDA=0 pip install -e ".[notebooks]"
```
This would also skip the post-processing step at runtime (removing small holes and sprinkles in the output masks, which requires the CUDA extension), but shouldn't affect the results in most cases.

### Building the SAM 2 CUDA extension

By default, we allow the installation to proceed even if the SAM 2 CUDA extension fails to build. (In this case, the build errors are hidden unless using `-v` for verbose output in `pip install`.)

If you see a message like `Skipping the post-processing step due to the error above` at runtime or `Failed to build the SAM 2 CUDA extension due to the error above` during installation, it indicates that the SAM 2 CUDA extension failed to build in your environment. In this case, **you can still use SAM 2 for both image and video applications**. The post-processing step (removing small holes and sprinkles in the output masks) will be skipped, but this shouldn't affect the results in most cases.

If you would like to enable this post-processing step, you can reinstall SAM 2 on a GPU machine with environment variable `SAM2_BUILD_ALLOW_ERRORS=0` to force building the CUDA extension (and raise errors if it fails to build), as follows
```bash
pip uninstall -y SAM-2 && \
rm -f ./sam2/*.so && \
SAM2_BUILD_ALLOW_ERRORS=0 pip install -v -e ".[notebooks]"
```

Note that PyTorch needs to be installed first before building the SAM 2 CUDA extension. It's also necessary to install [CUDA toolkits](https://developer.nvidia.com/cuda-toolkit-archive) that match the CUDA version for your PyTorch installation. (This should typically be CUDA 12.1 if you follow the default installation command.) After installing the CUDA toolkits, you can check its version via `nvcc --version`.

Please check the section below on common installation issues if the CUDA extension fails to build during installation or load at runtime.

### Common Installation Issues

Click each issue for its solutions:
Expand All @@ -21,24 +46,48 @@ I got `ImportError: cannot import name '_C' from 'sam2'`
</summary>
<br/>

This is usually because you haven't run the `pip install -e ".[demo]"` step above or the installation failed. Please install SAM 2 first, and see the other issues if your installation fails.
This is usually because you haven't run the `pip install -e ".[notebooks]"` step above or the installation failed. Please install SAM 2 first, and see the other issues if your installation fails.

In some systems, you may need to run `python setup.py build_ext --inplace` in the SAM 2 repo root as suggested in https://github.com/facebookresearch/sam2/issues/77.
</details>

<details>
<summary>
I got `MissingConfigException: Cannot find primary config 'sam2_hiera_l.yaml'`
I got `MissingConfigException: Cannot find primary config 'configs/sam2.1/sam2.1_hiera_l.yaml'`
</summary>
<br/>

This is usually because you haven't run the `pip install -e .` step above, so `sam2_configs` isn't in your Python's `sys.path`. Please run this installation step. In case it still fails after the installation step, you may try manually adding the root of this repo to `PYTHONPATH` via
This is usually because you haven't run the `pip install -e .` step above, so `sam2` isn't in your Python's `sys.path`. Please run this installation step. In case it still fails after the installation step, you may try manually adding the root of this repo to `PYTHONPATH` via
```bash
export SAM2_REPO_ROOT=/path/to/segment-anything # path to this repo
export SAM2_REPO_ROOT=/path/to/sam2 # path to this repo
export PYTHONPATH="${SAM2_REPO_ROOT}:${PYTHONPATH}"
```
to manually add `sam2_configs` into your Python's `sys.path`.

</details>

<details>
<summary>
I got `RuntimeError: Error(s) in loading state_dict for SAM2Base` when loading the new SAM 2.1 checkpoints
</summary>
<br/>

This is likely because you have installed a previous version of this repo, which doesn't have the new modules to support the SAM 2.1 checkpoints yet. Please try the following steps:

1. pull the latest code from the `main` branch of this repo
2. run `pip uninstall -y SAM-2` to uninstall any previous installations
3. then install the latest repo again using `pip install -e ".[notebooks]"`

In case the steps above still don't resolve the error, please try running in your Python environment the following
```python
from sam2.modeling import sam2_base

print(sam2_base.__file__)
```
and check whether the content in the printed local path of `sam2/modeling/sam2_base.py` matches the latest one in https://github.com/facebookresearch/sam2/blob/main/sam2/modeling/sam2_base.py (e.g. whether your local file has `no_obj_embed_spatial`) to indentify if you're still using a previous installation.

</details>

<details>
<summary>
My installation failed with `CUDA_HOME environment variable is not set`
Expand All @@ -56,6 +105,12 @@ Also, you should make sure
python -c 'import torch; from torch.utils.cpp_extension import CUDA_HOME; print(torch.cuda.is_available(), CUDA_HOME)'
```
print `(True, a directory with cuda)` to verify that the CUDA toolkits are correctly set up.

If you are still having problems after verifying that the CUDA toolkit is installed and the `CUDA_HOME` environment variable is set properly, you may have to add the `--no-build-isolation` flag to the pip command:
```
pip install --no-build-isolation -e .
```

</details>

<details>
Expand All @@ -66,9 +121,24 @@ I got `undefined symbol: _ZN3c1015SmallVectorBaseIjE8grow_podEPKvmm` (or similar

This usually happens because you have multiple versions of dependencies (PyTorch or CUDA) in your environment. During installation, the SAM 2 library is compiled against one version library while at run time it links against another version. This might be due to that you have different versions of PyTorch or CUDA installed separately via `pip` or `conda`. You may delete one of the duplicates to only keep a single PyTorch and CUDA version.

In particular, if you have a lower PyTorch version than 2.3.1, it's recommended to upgrade to PyTorch 2.3.1 or higher first. Otherwise, the installation script will try to upgrade to the latest PyTorch using `pip`, which could sometimes lead to duplicated PyTorch installation if you have previously installed another PyTorch version using `conda`.
In particular, if you have a lower PyTorch version than 2.5.1, it's recommended to upgrade to PyTorch 2.5.1 or higher first. Otherwise, the installation script will try to upgrade to the latest PyTorch using `pip`, which could sometimes lead to duplicated PyTorch installation if you have previously installed another PyTorch version using `conda`.

We have been building SAM 2 against PyTorch 2.5.1 internally. However, a few user comments (e.g. https://github.com/facebookresearch/sam2/issues/22, https://github.com/facebookresearch/sam2/issues/14) suggested that downgrading to PyTorch 2.1.0 might resolve this problem. In case the error persists, you may try changing the restriction from `torch>=2.5.1` to `torch==2.1.0` in both [`pyproject.toml`](pyproject.toml) and [`setup.py`](setup.py) to allow PyTorch 2.1.0.
</details>

<details>
<summary>
I got `CUDA error: no kernel image is available for execution on the device`
</summary>
<br/>

A possible cause could be that the CUDA kernel is somehow not compiled towards your GPU's CUDA [capability](https://developer.nvidia.com/cuda-gpus). This could happen if the installation is done in an environment different from the runtime (e.g. in a slurm system).

We have been building SAM 2 against PyTorch 2.3.1 internally. However, a few user comments (e.g. https://github.com/facebookresearch/segment-anything-2/issues/22, https://github.com/facebookresearch/segment-anything-2/issues/14) suggested that downgrading to PyTorch 2.1.0 might resolve this problem. In case the error persists, you may try changing the restriction from `torch>=2.3.1` to `torch>=2.1.0` in both [`pyproject.toml`](pyproject.toml) and [`setup.py`](setup.py) to allow PyTorch 2.1.0.
You can try pulling the latest code from the SAM 2 repo and running the following
```
export TORCH_CUDA_ARCH_LIST=9.0 8.0 8.6 8.9 7.0 7.2 7.5 6.0`
```
to manually specify the CUDA capability in the compilation target that matches your GPU.
</details>

<details>
Expand All @@ -87,3 +157,33 @@ OLD_GPU, USE_FLASH_ATTN, MATH_KERNEL_ON = True, True, True
```
to relax the attention kernel setting and use other kernels than Flash Attention.
</details>

<details>
<summary>
I got `Error compiling objects for extension`
</summary>
<br/>

You may see error log of:
> unsupported Microsoft Visual Studio version! Only the versions between 2017 and 2022 (inclusive) are supported! The nvcc flag '-allow-unsupported-compiler' can be used to override this version check; however, using an unsupported host compiler may cause compilation failure or incorrect run time execution. Use at your own risk.

This is probably because your versions of CUDA and Visual Studio are incompatible. (see also https://stackoverflow.com/questions/78515942/cuda-compatibility-with-visual-studio-2022-version-17-10 for a discussion in stackoverflow).<br>
You may be able to fix this by adding the `-allow-unsupported-compiler` argument to `nvcc` after L48 in the [setup.py](https://github.com/facebookresearch/sam2/blob/main/setup.py). <br>
After adding the argument, `get_extension()` will look like this:
```python
def get_extensions():
srcs = ["sam2/csrc/connected_components.cu"]
compile_args = {
"cxx": [],
"nvcc": [
"-DCUDA_HAS_FP16=1",
"-D__CUDA_NO_HALF_OPERATORS__",
"-D__CUDA_NO_HALF_CONVERSIONS__",
"-D__CUDA_NO_HALF2_OPERATORS__",
"-allow-unsupported-compiler" # Add this argument
],
}
ext_modules = [CUDAExtension("sam2._C", srcs, extra_compile_args=compile_args)]
return ext_modules
```
</details>
7 changes: 7 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# 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.

recursive-include sam2 *.yaml #include all config files
Loading
Loading