How to convert a pytorch tensor into a byte string?

in libtorch we can do :

    std::stringstream stream;
    torch::save(tensor, stream);
    return stream.str();

and get a byte-str and then can serialize it using protobuf for example. How can I do its equivalent in Pytorch?
would using io.BytesIO suffice?

import io 
 buffer = io.BytesIO(), buffer)
bytes =
# use bytes ...

Any help is greatly apprecaited

Maybe you can use .to() function.

Hope this information can help you.

Thanks a lot. but .to is not applicable here. it works in libtorch only if the underlying data is a string (usually used with IValue if I’m not mistaken) other than that, types and devices are other usecases of .to which again are not applicable here. since here we want to turn the whole tensor into a byte representation an not individual elements in it. .to(torch.float, or the likes, only change the underlting data representation and not the tensor itself.
The way to go was to use io.BytesIO() and get the bytes needed.