Search code examples
c++libtorch

How to change type of torch::Torch from Float to Long in LibTorch (C++)


I am coding in C++ using LibTorch (PyTorch C++ API). Here, I am passing predicted_value and target_value which are both torch::Tensor of size {1, 1}.

torch::Tensor loss = torch::nll_loss(predicted_value, target_value);

When I try to evaluate the above, I get the following error:

 0.4997 [ Variable[CPUFloatType]{1,1} ]   # printout of predicted_value
-0.5392 [ Variable[CPUFloatType]{1,1} ]   # printout of target_value
terminate called after throwing an instance of 'c10::Error'
  what():  Expected object of scalar type Long but got scalar type Float for argument #2 'target' in call to _thnn_nll_loss_forward (checked_dense_tensor_unwrap at ../../aten/src/ATen/Utils.h:84)

I tried searching for how to cast float type tensors to long type tensors but was only able to find documentations for Python. Would very much appreciate suggestions to fix this!


Solution

  • tensor.to(torch::kLong) gives you the Long type.

    Here is the overloaded definition of Tensor's to function:

    inline Tensor Tensor::to(ScalarType dtype, bool non_blocking, bool copy) const {
        static auto table = globalATenDispatch().getOpTable("aten::to(Tensor self, ScalarType dtype, bool non_blocking=False, bool copy=False) -> Tensor");
        return table->getOp<Tensor (const Tensor &, ScalarType, bool, bool)>(tensorTypeIdToBackend(type_id()), is_variable())(*this, dtype, non_blocking, copy);
    }