v9.1.1
Menu

Tensor Shape and Attributes

easyFREEBasic OpsPyTorch BasicsPytorch

Problem Statement

Given a PyTorch tensor, extract and return its key attributes.

Background

Understanding tensor attributes is crucial for debugging and ensuring tensors are compatible for operations. Every tensor has a shape, data type, and device.

Your Task

Write a function get_tensor_info(tensor) that returns a dictionary containing the tensor's shape (as a list), dtype (as a string), and device (as a string).

Output Format

Return a dictionary with keys: "shape", "dtype", "device".

Example

Input
torch.rand(2, 3)
Output
{"shape": [2, 3], "dtype": "torch.float32", "device": "cpu"}
Reasoning
  • Input: a 2×32 \times 3 tensor of random numbers drawn uniformly from [0,1)[0, 1): 2 rows, 3 columns, 2⋅3=62 \cdot 3 = 6 elements. The values themselves never matter here, only the metadata describing the tensor.
  • shape: the size of each dimension in order, so [2, 3]. There is one entry per dimension, so a 1×2×31 \times 2 \times 3 tensor would give [1, 2, 3]. The product of the entries is the element count, here 6.
  • dtype: the number type every element is stored as. Random uniform values default to 32-bit floating point (4 bytes each, 24 bytes in total), and the output reports that type by its full library name as a string. A tensor built from 32-bit integers would report the integer type instead.
  • device: where the data lives in memory. Nothing moved it to a GPU, so it is cpu.
  • Notice that every value in the result is plain data (a list of integers and two strings) rather than a PyTorch object, which is why the dictionary prints cleanly as JSON.

Constraints

  • Input will always be a valid PyTorch tensor
  • Tensor can be of any shape and data type
  • Return dtype and device as strings

Learn this in

More from Pytorch

solution.py

Test results

Sign in to run your code against the test cases.