使用torch.load()触发Segmentation fault (core dumped)问题求助
解决Torch GPU版加载模型触发Segmentation Fault问题
核心原因
GPU版本Torch调用torch.load()时,默认会自动将模型权重映射到当前GPU设备,若模型是在CPU环境或不同CUDA配置的Torch下保存的,易出现设备不兼容导致的段错误。
修复方案
强制加载到CPU再迁移GPU
修改加载代码,通过map_location参数指定先加载到CPU,避免自动映射冲突:model_xl = torch.load("./data/models_saved/xl_model.pth", map_location=torch.device('cpu')) # 按需迁移至GPU model_xl = model_xl.to('cuda')重新安装匹配版本的GPU版Torch
确保Torch与CUDA版本完全适配,执行以下命令重装:pip uninstall torch -y pip install torch==1.2.0+cu92 -f https://download.pytorch.org/whl/torch_stable.html重新保存模型为状态字典格式
若模型文件存在格式兼容问题,先用CPU版Torch加载后,以状态字典形式重新保存,再用GPU版加载:# CPU环境下执行 model_cpu = torch.load("./data/models_saved/xl_model.pth") torch.save(model_cpu.state_dict(), "./data/models_saved/xl_model_state_dict.pth") # GPU环境下执行(需导入你的模型类) from your_model_def import XLModel # 替换为实际模型类路径 model_xl = XLModel() model_xl.load_state_dict(torch.load("./data/models_saved/xl_model_state_dict.pth")) model_xl = model_xl.to('cuda')检查GPU内存占用
执行nvidia-smi查看GPU内存使用情况,关闭其他占用GPU资源的进程后再尝试加载模型。
内容的提问来源于stack exchange,提问作者cooper
相关产品推荐
相关产品推荐

