How to compare tensors in libtorch

How might one compare two tensors in Libtorch (C++) to check if they are equal?

I want to see if they are equal for an unit test, and understand in python one might:


However torch::all returns a Tensor.

I simply want to achieve:

if( !torch::all(producedTensor.eq(expectedTensor)) ){
    // fails test, do something
    // hooray, do something else

You can just do:

bool success = producedTensor.equal(expectedTensor);

This works, and is what I am looking for, however people should be aware that if the tensors are different dtypes then it simply throws an c10::Error exception with no message, warning, or justification.

for example the below will SIGABRT:

 11  21  31
 12  22  32
 13  23  33
 10  20  30
 13  23  33
 14  24  34
[ CPUDoubleType{6,3} ]
 11  21  31
 12  22  32
 13  23  33
 10  20  30
 13  23  33
 14  24  34
[ CPULongType{6,3} ]
libc++abi.dylib: terminating with uncaught exception of type c10::Error

generated by simply running:

	std::cout << "produced:\n" << produced << "\nexpected\n" << expected << std::endl;
	bool same = produced.equal(expected);

This appears to be an OSX thing.

On Linux/gcc, we get very reasonable error and backtrace:

terminate called after throwing an instance of 'c10::Error'
  what():  Expected object of scalar type double but got scalar type long int for argument 'other'
Exception raised from cpu_equal at ../aten/src/ATen/native/ReduceOps.cpp:1230 (most recent call first):
frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) + 0x55 (0x7fc78e452055 in /usr/local/lib/python3.9/dist-packages/torch/lib/
frame #1: <unknown function> + 0x66de24 (0x7fc78eae4e24 in /usr/local/lib/python3.9/dist-packages/torch/lib/

Maybe on OSX you need to do your own exception catching and what printing (or have a compilation flag that adds that for you or something, I would not know).

Best regards