使用LibTorch在C++中加载PyTorch模型时触发std::bad_alloc错误
LibTorch加载追踪PyTorch模型触发std::bad_alloc错误
问题现象:运行加载模型的C++程序时崩溃,报错如下:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
最小复现代码
C++代码
#include <iostream> #include <memory> #include <torch/script.h> int main() { // 加载追踪后的模型 torch::jit::script::Module module; // 加载保存的模型 - 替换为你的.pt文件路径 module = torch::jit::load("net.pt"); return 0; }
CMakeLists.txt
cmake_minimum_required(VERSION 3.18) project(torch_example) include(FetchContent) set(LIBTORCH_CPU_URL "https://download.pytorch.org/libtorch/cpu/libtorch-shared-with-deps-2.5.1%2Bcpu.zip") FetchContent_Declare( Torch URL ${LIBTORCH_CPU_URL } DOWNLOAD_EXTRACT_TIMESTAMP TRUE ) FetchContent_MakeAvailable(Torch) add_executable(torch_example main.cpp) target_link_libraries(torch_example PRIVATE "${TORCH_LIBRARIES}") target_include_directories(torch_example PRIVATE "${torch_SOURCE_DIR}/include") set_target_properties(torch_example PROPERTIES CXX_STANDARD 23)
排查方向与解决办法
- 版本不匹配:确保导出模型的PyTorch Python版本与LibTorch C++版本完全一致(比如都是2.5.1),版本差异会导致模型结构解析失败,进而触发内存分配错误。
- 模型文件损坏:重新用
torch.jit.trace或torch.jit.script导出模型,先验证导出后的模型能在Python中正常加载运行,再拿到C++环境测试。 - 内存资源不足:如果模型体积过大,运行程序的机器内存不足以容纳模型,会触发
std::bad_alloc。可以检查模型文件大小,或换内存更充足的环境测试。 - 编译配置问题:确认LibTorch是正确的CPU版本,CMake配置中LibTorch路径无拼写错误,链接的库正确。另外可尝试降低C标准版本(比如从C23改为C17),部分LibTorch版本对高版本C标准兼容性存在问题。
内容的提问来源于stack exchange,提问作者works
相关产品推荐
相关产品推荐

