Sunday, October 5, 2025
HomeLanguagesHow to check if a tensor is contiguous or not in PyTorch

How to check if a tensor is contiguous or not in PyTorch

In this article, we are going to see how to check if a tensor is contiguous or not in PyTorch.

A contiguous tensor could be a tensor whose components are stored in a contiguous order without having any empty space between them. We can check if a tensor is contiguous or not by using the Tensor.is_contiguous() method.

Tensor.is_contiguous() method

This method helps us to identify whether a tensor is contiguous or not. This method returns True if a tensor is contiguous else it will return False. Use the below syntax to understand how to check if a tensor is contiguous or not in PyTorch.

Syntax – Tensor.is_contiguous()

Example 1:

In the following program, we are going to check whether a tensor is contiguous or not.

Python3




# import torch library
import torch
  
# create torch tensors
tens_1 = torch.tensor([1., 2., 3., 4., 5.])
  
# display tensors
print("\n First Tensor - ", tens_1)
  
# check this tensor is contiguous or not
output_1 = tens_1.is_contiguous()
  
# display output
print("\n This tensor is contiguous - ", output_1)


Output:

 

Example 2:

In the following program, we are going to see transpose of a tensor is contiguous or not.

Python3




# import torch library
import torch
  
# define a torch tensor
tens = torch.tensor([[10., 20., 30.],
                     [40., 50., 60.]])
  
# transpose of the above defined tensor
tens_transpose = tens.transpose(0, 1)
  
# display tensors
print("\n Original Tensor \n", tens)
print("\n Transpose of original Tensor \n",
      tens_transpose)
  
# check if a tensor and it's transpose are 
# contiguous or not
Output_1 = tens.is_contiguous()
print("\n Original Tensor is contiguous - ", Output_1)
  
Output_2 = tens_transpose.is_contiguous()
print("\n Transpose of original Tensor is contiguous - ", Output_2)


Output:

 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32337 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6706 POSTS0 COMMENTS
Nicole Veronica
11871 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11934 POSTS0 COMMENTS
Shaida Kate Naidoo
6823 POSTS0 COMMENTS
Ted Musemwa
7089 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6779 POSTS0 COMMENTS