Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 215 additions & 0 deletions INSTALL_zh.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
## 安装与环境配置

### 系统要求

- Linux 系统,Python ≥ 3.10,PyTorch ≥ 2.5.1 以及与 PyTorch 版本匹配的 [torchvision](https://github.com/pytorch/vision/)。请前往 https://pytorch.org 一起安装,以确保版本一致。
* 注意:较旧版本的 Python 或 PyTorch 也可能可以运行,但强烈建议使用上述版本以获得 `torch.compile` 等完整功能支持。
- 与 PyTorch 安装所使用的 CUDA 版本匹配的 [CUDA 工具包](https://developer.nvidia.com/cuda-toolkit-archive)。如果您使用默认安装命令,通常为 CUDA 12.1。
- 如果您在 Windows 上安装,强烈建议使用带有 Ubuntu 的 [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/zh-cn/windows/wsl/install)。

然后,在本仓库根目录下通过以下命令安装 SAM 2:

```bash
pip install -e ".[notebooks]"
```

如需跳过构建 SAM 2 的 CUDA 扩展,可通过环境变量 `SAM2_BUILD_CUDA=0` 来跳过:

```bash
# 跳过 SAM 2 CUDA 扩展的构建
SAM2_BUILD_CUDA=0 pip install -e ".[notebooks]"
```

跳过构建后,运行时也会跳过后处理步骤(即去除输出掩码中的小空洞和噪点,该功能需要 CUDA 扩展),但在大多数情况下不会影响结果。

### 构建 SAM 2 CUDA 扩展

默认情况下,即使 SAM 2 的 CUDA 扩展构建失败,安装也会继续进行(此时构建错误会被隐藏,除非在 `pip install` 中使用 `-v` 开启详细输出)。

如果运行时出现 `Skipping the post-processing step due to the error above`,或安装时出现 `Failed to build the SAM 2 CUDA extension due to the error above` 的提示,说明 SAM 2 的 CUDA 扩展在您的环境中构建失败。此时,**您仍然可以将 SAM 2 用于图像和视频应用**。后处理步骤(去除输出掩码中的小空洞和噪点)将被跳过,但在大多数情况下不会影响结果。

如果您希望启用此后处理步骤,可以在 GPU 机器上通过设置环境变量 `SAM2_BUILD_ALLOW_ERRORS=0` 来重新安装 SAM 2,强制构建 CUDA 扩展(如果构建失败则抛出错误):

```bash
pip uninstall -y SAM-2 && \
rm -f ./sam2/*.so && \
SAM2_BUILD_ALLOW_ERRORS=0 pip install -v -e ".[notebooks]"
```

注意:在构建 SAM 2 CUDA 扩展之前,需要先安装 PyTorch。同时,还需要安装与 PyTorch 安装所使用的 CUDA 版本匹配的 [CUDA 工具包](https://developer.nvidia.com/cuda-toolkit-archive)(如果使用默认安装命令,通常为 CUDA 12.1)。安装完成后,可以通过 `nvcc --version` 查看其版本。

如果安装过程中或运行时 CUDA 扩展构建失败,请查看下方的常见安装问题章节。

### 常见安装问题

点击各问题查看解决方案:

<details>
<summary>
出现 <code>ImportError: cannot import name '_C' from 'sam2'</code>
</summary>
<br/>

这通常是因为您没有执行上面的 `pip install -e ".[notebooks]"` 步骤,或者安装失败。请先安装 SAM 2,并参考其他问题排查安装失败的原因。

在某些系统上,您可能需要按照 https://github.com/facebookresearch/sam2/issues/77 的建议,在 SAM 2 仓库根目录下运行 `python setup.py build_ext --inplace`。

</details>

<details>
<summary>
出现 <code>MissingConfigException: Cannot find primary config 'configs/sam2.1/sam2.1_hiera_l.yaml'</code>
</summary>
<br/>

这通常是因为您没有执行上面的 `pip install -e .` 步骤,导致 `sam2` 不在 Python 的 `sys.path` 中。请执行该安装步骤。如果安装后仍然失败,可以通过以下方式手动将本仓库根目录添加到 `PYTHONPATH`:

```bash
export SAM2_REPO_ROOT=/path/to/sam2 # 本仓库的路径
export PYTHONPATH="${SAM2_REPO_ROOT}:${PYTHONPATH}"
```

这样可以将 `sam2_configs` 手动加入 Python 的 `sys.path`。

</details>

<details>
<summary>
加载新的 SAM 2.1 检查点时出现 <code>RuntimeError: Error(s) in loading state_dict for SAM2Base</code>
</summary>
<br/>

这可能是因为您安装的是旧版本仓库,其中缺少支持 SAM 2.1 检查点所需的新模块。请尝试以下步骤:

1. 从本仓库的 `main` 分支拉取最新代码
2. 运行 `pip uninstall -y SAM-2` 卸载之前的安装
3. 使用 `pip install -e ".[notebooks]"` 重新安装最新版本

如果上述步骤仍无法解决问题,请在您的 Python 环境中运行以下代码:

```python
from sam2.modeling import sam2_base

print(sam2_base.__file__)
```

并检查打印出的 `sam2/modeling/sam2_base.py` 本地路径中的内容是否与 https://github.com/facebookresearch/sam2/blob/main/sam2/modeling/sam2_base.py 中的最新版本一致(例如,您的本地文件是否包含 `no_obj_embed_spatial`),以确认您是否仍在使用旧版本的安装。

</details>

<details>
<summary>
安装失败,提示 <code>CUDA_HOME environment variable is not set</code>
</summary>
<br/>

这通常是因为安装步骤找不到 CUDA 工具包(包含 NVCC 编译器)来构建 SAM 2 中的自定义 CUDA 内核。请安装 [CUDA 工具包](https://developer.nvidia.com/cuda-toolkit-archive) 或与您的 PyTorch 安装所使用的 CUDA 版本匹配的版本。如果安装 CUDA 工具包后错误仍然存在,可以通过以下方式显式指定 `CUDA_HOME`:

```
export CUDA_HOME=/usr/local/cuda # 改为您的 CUDA 工具包路径
```

然后重新运行安装命令。

此外,您应该确保以下命令:

```
python -c 'import torch; from torch.utils.cpp_extension import CUDA_HOME; print(torch.cuda.is_available(), CUDA_HOME)'
```

打印出 `(True, 包含 cuda 的目录)` 以验证 CUDA 工具包配置正确。

如果验证 CUDA 工具包已安装且 `CUDA_HOME` 环境变量已正确设置后仍有问题,可能需要在 pip 命令中添加 `--no-build-isolation` 标志:

```
pip install --no-build-isolation -e .
```

</details>

<details>
<summary>
出现 <code>undefined symbol: _ZN3c1015SmallVectorBaseIjE8grow_podEPKvmm</code>(或类似错误)
</summary>
<br/>

这通常是因为您的环境中存在多个版本的依赖项(PyTorch 或 CUDA)。安装时,SAM 2 库编译时链接了某个版本的库,但运行时链接了另一个版本。这可能是因为您通过 `pip` 或 `conda` 分别安装了不同版本的 PyTorch 或 CUDA。您可以删除其中一个重复项,只保留单一版本的 PyTorch 和 CUDA。

特别是,如果您的 PyTorch 版本低于 2.5.1,建议先升级到 PyTorch 2.5.1 或更高版本。否则,安装脚本会尝试使用 `pip` 升级到最新版本的 PyTorch,如果您之前使用 `conda` 安装了其他版本的 PyTorch,有时会导致 PyTorch 重复安装。

我们内部一直使用 PyTorch 2.5.1 构建 SAM 2。但部分用户的评论(例如 https://github.com/facebookresearch/sam2/issues/22 和 https://github.com/facebookresearch/sam2/issues/14)表明,降级到 PyTorch 2.1.0 可能可以解决此问题。如果错误仍然存在,您可以尝试将 [`pyproject.toml`](pyproject.toml) 和 [`setup.py`](setup.py) 中的 `torch>=2.5.1` 改为 `torch==2.1.0`,以允许使用 PyTorch 2.1.0。

</details>

<details>
<summary>
出现 <code>CUDA error: no kernel image is available for execution on the device</code>
</summary>
<br/>

可能的原因是 CUDA 内核没有针对您的 GPU 的 CUDA [计算能力](https://developer.nvidia.com/cuda-gpus)进行编译。这种情况可能发生在安装环境与运行时环境不同的情况下(例如在 slurm 系统中)。

您可以尝试拉取最新的 SAM 2 代码并运行以下命令:

```
export TORCH_CUDA_ARCH_LIST=9.0 8.0 8.6 8.9 7.0 7.2 7.5 6.0
```

手动指定与您的 GPU 匹配的 CUDA 计算能力作为编译目标。

</details>

<details>
<summary>
出现 <code>RuntimeError: No available kernel. Aborting execution.</code>(或类似错误)
</summary>
<br/>

这可能是因为您的机器没有 GPU 或 PyTorch 版本不兼容 Flash Attention(另请参阅 PyTorch 论坛中的讨论:https://discuss.pytorch.org/t/using-f-scaled-dot-product-attention-gives-the-error-runtimeerror-no-available-kernel-aborting-execution/180900)。您可以尝试将 [`sam2/modeling/sam/transformer.py`](sam2/modeling/sam/transformer.py) 中的以下代码行:

```python
OLD_GPU, USE_FLASH_ATTN, MATH_KERNEL_ON = get_sdpa_settings()
```

替换为:

```python
OLD_GPU, USE_FLASH_ATTN, MATH_KERNEL_ON = True, True, True
```

以放宽注意力内核设置,使用 Flash Attention 以外的其他内核。

</details>

<details>
<summary>
出现 <code>Error compiling objects for extension</code>
</summary>
<br/>

您可能会看到如下错误日志:

> 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.

这可能是因为您的 CUDA 和 Visual Studio 版本不兼容(另请参阅 stackoverflow 中的讨论:https://stackoverflow.com/questions/78515942/cuda-compatibility-with-visual-studio-2022-version-17-10)。<br>
您可以尝试在 [setup.py](https://github.com/facebookresearch/sam2/blob/main/setup.py) 第 48 行之后添加 `-allow-unsupported-compiler` 参数来修复此问题。<br>
添加参数后,`get_extension()` 将如下所示:

```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" # 添加此参数
],
}
ext_modules = [CUDAExtension("sam2._C", srcs, extra_compile_args=compile_args)]
return ext_modules
```

</details>
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Note:
2. The step above requires compiling a custom CUDA kernel with the `nvcc` compiler. If it isn't already available on your machine, please install the [CUDA toolkits](https://developer.nvidia.com/cuda-toolkit-archive) with a version that matches your PyTorch CUDA version.
3. If you see a message like `Failed to build the SAM 2 CUDA extension` during installation, you can ignore it and still use SAM 2 (some post-processing functionality may be limited, but it doesn't affect the results in most cases).

Please see [`INSTALL.md`](./INSTALL.md) for FAQs on potential issues and solutions.
Please see [`INSTALL.md`](./INSTALL.md) for FAQs on potential issues and solutions. A Chinese version of the installation guide is also available: [`INSTALL_zh.md`](./INSTALL_zh.md).

## Getting Started

Expand Down