Libtorch loss.backward(); C10 Error

Hello, my environment is win10 vs2019. After I built the network structure using libtorch, forward got the output result and loss function. But when I lost.backward, there was a Microsoft C++ exception: c10::Error, located at memory location 0x000000F11C4FE260. How to solve this problem.

net->train();
	size_t index = 0;
	float Loss = 0.0;
	for (auto& batch : loader) {
		torch::Tensor input = batch.data.to(device);
		torch::Tensor targets = batch.target.to(device);
		torch::Tensor output, loss;
		optimizer.zero_grad();
/*		std::cout << targets;*/
		std::tie(output, loss) = net->forward(input, targets);
		std::cout << output;
		std::cout << loss;
// 		input.print();
// 		targets.print();
// 		output.print();
// 		loss.print();
		loss.backward();
		optimizer.step();
		Loss += loss.item<float>();

The error message is as follows

0x00007FFA17833B29 处(位于 Project.exe 中)有未经处理的异常: Microsoft C++ 异常: c10::Error,位于内存位置 0x00000040FE0FE410 处。

The print log is as follows

loading cfg & creating modules ...
train start ...
torch::nn::Sequential(
  (0): torch::nn::Conv2d(3, 96, kernel_size=[11, 11], stride=[4, 4])
  (1): torch::nn::Functional()
) torch::nn::Sequential(
  (0): MaxPoolLayer2D
) torch::nn::Sequential(
  (0): torch::nn::Conv2d(96, 256, kernel_size=[5, 5], stride=[1, 1], padding=[2, 2])
  (1): torch::nn::Functional()
) torch::nn::Sequential(
  (0): MaxPoolLayer2D
) torch::nn::Sequential(
  (0): torch::nn::Conv2d(256, 384, kernel_size=[3, 3], stride=[1, 1], padding=[1, 1])
  (1): torch::nn::Functional()
) torch::nn::Sequential(
  (0): torch::nn::Conv2d(384, 384, kernel_size=[3, 3], stride=[1, 1], padding=[1, 1])
  (1): torch::nn::Functional()
) torch::nn::Sequential(
  (0): torch::nn::Conv2d(384, 256, kernel_size=[3, 3], stride=[1, 1], padding=[1, 1])
  (1): torch::nn::Functional()
) torch::nn::Sequential(
  (0): MaxPoolLayer2D
) torch::nn::Sequential(
  (0): Flatten
  (1): torch::nn::Linear(in_features=9216, out_features=4096, bias=true)
  (2): torch::nn::Functional()
) torch::nn::Sequential(
  (0): torch::nn::Dropout2d(p=0, inplace=false)
) torch::nn::Sequential(
  (0): torch::nn::Linear(in_features=4096, out_features=4096, bias=true)
  (1): torch::nn::Functional()
) torch::nn::Sequential(
  (0): torch::nn::Dropout2d(p=0, inplace=false)
) torch::nn::Sequential(
  (0): torch::nn::Linear(in_features=4096, out_features=2, bias=true)
  (1): EmptyLayer
) torch::nn::Sequential(
  (0): torch::nn::Softmax(dim=1)
) torch::nn::Sequential(
  (0): Loss_Function
) 0.4967  0.5033
[ CUDAFloatType{1,2} ]0.250011
[ CUDAFloatType{} ]

You could try wrapping your code with try catch block to see the exact message

try
{
... your code
}
catch (const c10::Error& e)
{
	std::cout << e.msg() << std::endl;
}
1 Like

thank you very much!