#include
#include
#include
#include
#include
int main()
{
// Scalar
std::cout << "-------------- Scalar --------------\n";
const at::Tensor my_scalar = torch::tensor(68.0f).cuda();
std::cout << "Scalar: " << my_scalar << std::endl;
std::cout << "Scalar Dimension: " << my_scalar.ndimension() << std::endl;
std::cout << "Scalar Cuda: " << std::boolalpha << my_scalar.is_cuda() << std::endl;
std::cout << "Scalar as tensor shape: " << _shape_as_tensor(my_scalar).cuda() << std::endl;
std::cout << "Scalar element sizes: " << my_scalar.element_size() << std::endl;
std::cout << "Scalar sizes: " << my_scalar.sizes() << std::endl;
}
This is a short C++ code using the libtorch library to create a scalar tensor called my_scalar
with a value of 68.0f, which is stored in the GPU memory.
const at::Tensor my_scalar = torch::tensor(68.0f).cuda();
We then use several methods to extract information about this scalar tensor:
my_scalar.ndimension()
: This method returns the number of dimensions in the tensor, which for a scalar tensor is always zero. Here, it will output “Scalar Dimension: 0”.
std::cout << "Scalar Dimension: " << my_scalar.ndimension() << std::endl;
my_scalar.is_cuda()
: This method returns a true or false value indicating whether the tensor is stored in GPU memory or not. Since we created my_scalar in GPU memory using the cuda()
method, the output will be “Scalar Cuda: true”.
std::cout << "Scalar Cuda: " << std::boolalpha << my_scalar.is_cuda() << std::endl;
_shape_as_tensor(my_scalar).cuda()
: We use a helper function _shape_as_tensor() to create a tensor that represents the shape of my_scalar, which is an empty tensor with zero dimensions. We then move this tensor to the GPU memory using cuda()
. The output will be “Scalar as tensor shape: []”.
std::cout << "Scalar as tensor shape: " << _shape_as_tensor(my_scalar).cuda() << std::endl;
my_scalar.element_size()
: This method returns the size of each element in the tensor in bytes. Since my_scalar
is a scalar tensor with a single floating-point value, its element size is 4 bytes (for a 32-bit floating-point value). The output will be “Scalar element sizes: 4”.
std::cout << "Scalar element sizes: " << my_scalar.element_size() << std::endl;
my_scalar.sizes()
: This method returns a vector of integers representing the size of each dimension in the tensor. Since my_scalar has no dimensions, its size vector is empty. The output will be “Scalar sizes: []”.
std::cout << "Scalar sizes: " << my_scalar.sizes() << std::endl;
Finally, the code uses
std::cout
to print out the results of each method call. The output will be:
-------------- Scalar --------------
Scalar: 68
Scalar Dimension: 0
Scalar Cuda: true
Scalar as tensor shape: []
Scalar element sizes: 4
Scalar sizes: []
I hope you find this post useful.
Good luck!.