Get string of tensor in libtorch

I have tried to find a way to get the string reprensentation of a tensor for logging with spdlog.

torch::Tensor tensor;

// works
std::cout << tensor << "\n";

// spdlog prints error: "basic_ios::clear: iostream error"
spdlog::info("tensor: {}", tensor);

I’m thinking to work around the error by getting the string of tensor first and pass it to spdlog but failed to find any API which does that. I really appreciate any help. Thanks in advance!

I think the best way is to transform the std::ostringstream version of your tensor into a string, you can do it this way:

std::ostringstream stream;
stream << tensor;
std::string tensor_string = stream.str();
2 Likes

Thanks. I was actually hoping for something native. But if is does not exist, I guess your suggestion is the best I get :slight_smile:

spdlog provides an option for this.
You can define a function that takes tensor and ostream and writes to it.
See example in https://github.com/gabime/spdlog#user-defined-types

Thanks for the awesome logging library. Based on my understanding, I wrote the following free function

template <typename OStream>
OStream& operator<<(OStream& os, const torch::Tensor& t) {
  return os << t;
}

which resulted in a pile of compile errors when combined with

spdlog::info("tensor: {}", tensor);

I am not sure where I am doing wrong here…