[ PROMPT_NODE_22768 ]
Multimodal Segment Anything 故障排查
[ SKILL_DOCUMENTATION ]
# Segment Anything 故障排查指南
## 安装问题
### CUDA 不可用
**错误**:`RuntimeError: CUDA not available`
**解决方案**:
python
# 检查 CUDA 可用性
import torch
print(torch.cuda.is_available())
print(torch.version.cuda)
# 安装带 CUDA 的 PyTorch
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121
# 如果 CUDA 工作但 SAM 未使用它
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cuda") # 显式移动到 GPU
### 导入错误
**错误**:`ModuleNotFoundError: No module named 'segment_anything'`
**解决方案**:
bash
# 从 GitHub 安装
pip install git+https://github.com/facebookresearch/segment-anything.git
# 或克隆并安装
git clone https://github.com/facebookresearch/segment-anything.git
cd segment-anything
pip install -e .
# 验证安装
python -c "from segment_anything import sam_model_registry; print('OK')"
### 缺少依赖
**错误**:`ModuleNotFoundError: No module named 'cv2'` 或类似错误
**解决方案**:
bash
# 安装所有可选依赖
pip install opencv-python pycocotools matplotlib onnxruntime onnx
# Windows 下的 pycocotools
pip install pycocotools-windows
## 模型加载问题
### 找不到检查点
**错误**:`FileNotFoundError: checkpoint file not found`
**解决方案**:
bash
# 下载正确的检查点
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
# 验证文件完整性
md5sum sam_vit_h_4b8939.pth
# 预期: a7bf3b02f3ebf1267aba913ff637d9a2
# 使用绝对路径
sam = sam_model_registry["vit_h"](checkpoint="/full/path/to/sam_vit_h_4b8939.pth")
### 模型类型不匹配
**错误**:`KeyError: 'unexpected key in state_dict'`
**解决方案**:
python
# 确保模型类型与检查点匹配
# vit_h 检查点 → vit_h 模型
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
# vit_l 检查点 → vit_l 模型
sam = sam_model_registry["vit_l"](checkpoint="sam_vit_l_0b3195.pth")
# vit_b 检查点 → vit_b 模型
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
### 加载时内存不足
**错误**:模型加载期间 `CUDA out of memory`
**解决方案**:
python
# 使用更小的模型
sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
# 先加载到 CPU,然后再移动
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
sam.to("cpu")
torch.cuda.empty_cache()
sam.to("cuda"