10 #ifdef LIBTORCH_ENABLED 17 template <
typename DataType>
19 vectorToTensor(std::vector<DataType> & vector, torch::Tensor & tensor,
const bool detach)
21 auto options = torch::TensorOptions();
22 if constexpr (std::is_same<DataType, double>::value)
23 options = torch::TensorOptions().dtype(at::kDouble);
24 else if constexpr (std::is_same<DataType, float>::value)
25 options = torch::TensorOptions().dtype(at::kFloat);
27 static_assert(Moose::always_false<DataType>,
28 "vectorToTensor is not implemented for the given data type!");
32 tensor = torch::from_blob(vector.data(), {long(vector.size()), 1}, options).clone();
42 template <
typename DataType>
48 tensor.data_ptr<DataType>();
50 catch (
const c10::Error & e)
53 "Cannot cast tensor values to", MooseUtils::prettyCppType<DataType>(),
"!\n", e.msg());
56 const auto & sizes = tensor.sizes();
58 long int max_size = 0;
59 for (
const auto & dim_size : sizes)
61 max_size = dim_size > max_size ? dim_size : max_size;
63 mooseAssert(max_size == tensor.numel(),
"The given tensor should be one-dimensional!");
64 vector = {tensor.data_ptr<DataType>(), tensor.data_ptr<DataType>() + tensor.numel()};
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
void tensorToVector(torch::Tensor &tensor, std::vector< DataType > &vector)
Utility function that converts a torch::Tensor to a standard vector.
void vectorToTensor(std::vector< DataType > &vector, torch::Tensor &tensor, const bool detach=false)
Utility function that converts a standard vector to a torch::Tensor.
template void tensorToVector< Real >(torch::Tensor &tensor, std::vector< Real > &vector)
template void vectorToTensor< Real >(std::vector< Real > &vector, torch::Tensor &tensor, const bool detach)