PyTorch C++ API中Conv2d析构函数崩溃问题求助
问题
我编写了如下代码,代码运行后结果正确,但在Conv2d的析构函数阶段发生崩溃,请问有没有人遇到过类似情况?
代码
torch::Tensor kernel = torch::full({ 1, 32, 1, 2 }, 0, torch::kInt32); // Define the bias torch::Tensor bias = torch::tensor({ 0 }, torch::kInt32); // Define the input image torch::Tensor image = torch::full({ 32, 6, 7 }, 0, torch::kInt32); /// Define the convolution operation //depth_conv = Conv2d(in_channels = 10, out_channels = 10, kernel_size = 3, groups = 10) torch::nn::Conv2d depth_conv = torch::nn::Conv2d( torch::nn::Conv2dOptions(32, 1, {1,2}).groups(1).bias(false) ); // Set the filter for the convolution operation depth_conv->weight = kernel; // Set the bias for the convolution operation depth_conv->bias = bias; std::cout << "Original Data Tensor:\n" << image << std::endl; std::cout << "Original Wght Tensor:\n" << depth_conv->weight << std::endl; // Apply the convolution operation torch::Tensor output = depth_conv->forward(image); std::cout << "Output:\n" << output.dtype() << std::endl; // Print the output shape and values std::cout << "Output Shape: " << output.sizes() << std::endl; std::cout << "Output:\n" << output.dtype() << std::endl;
问题原因及解决方案
- 核心崩溃原因:初始化Conv2d时设置了
.bias(false),这会让层不分配bias参数的内存空间,但后续强行给depth_conv->bias赋值,导致析构时程序尝试释放未被正确分配的bias资源,直接触发崩溃。 - 输入维度错误:Conv2d要求输入是4维张量(batch_size, in_channels, height, width),当前的image是3维{32,6,7},需要调整为{1,32,6,7}(batch设为1),否则forward时会有维度不匹配的隐患。
- 数据类型问题:PyTorch的Conv2d默认权重是浮点类型,用kInt32虽然能运行,但可能引发计算精度或内部逻辑的潜在问题,建议统一使用float32类型。
修正后的代码
torch::Tensor kernel = torch::full({ 1, 32, 1, 2 }, 0.f, torch::kFloat32); // 如果需要bias,初始化时不要加.bias(false) torch::Tensor bias = torch::tensor({ 0.f }, torch::kFloat32); // 调整输入为4维:batch=1, channels=32, height=6, width=7 torch::Tensor image = torch::full({ 1, 32, 6, 7 }, 0.f, torch::kFloat32); // 初始化Conv2d时开启bias(如果需要的话) torch::nn::Conv2d depth_conv = torch::nn::Conv2d( torch::nn::Conv2dOptions(32, 1, {1,2}).groups(1).bias(true) ); depth_conv->weight = kernel; depth_conv->bias = bias; std::cout << "Original Data Tensor:\n" << image << std::endl; std::cout << "Original Wght Tensor:\n" << depth_conv->weight << std::endl; torch::Tensor output = depth_conv->forward(image); std::cout << "Output:\n" << output.dtype() << std::endl; std::cout << "Output Shape: " << output.sizes() << std::endl; std::cout << "Output:\n" << output << std::endl;
如果不需要bias,直接删除depth_conv->bias = bias这一行即可,同时保持.bias(false)的设置。
内容的提问来源于stack exchange,提问作者user1941008
相关产品推荐
相关产品推荐

