Create a scalar tensor in LibTorch, Part 1

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.

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”.
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”.
_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: []”.
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”.
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: []”.
Finally, the code uses std::cout to print out the results of each method call. The output will be:

I hope you find this post useful.

Good luck!.

Photo by Suzi Kim on Unsplash

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top