The torch.equal() method checks if two tensors are exactly equal in terms of shape and element values (even if their dtypes differ like int64 or float32). It returns True if the tensors are identical, and False otherwise.

In the latest version of PyTorch, dtype differences are now allowed as long as values match exactly (e.g., 1 == 1.0). Broadcasting is not allowed; shapes must match exactly.
Syntax
torch.equal(input, other)
Parameters
Argument | Description |
input (Tensor) | It is the first tensor to compare. |
other (Tensor) | It is the second tensor to compare. |
Identical tensors
Let’s define two identical tensors and check if it is equal.import torch # Two identical tensors tensor1 = torch.tensor([11, 2, 31]) tensor2 = torch.tensor([11, 2, 31]) print(torch.equal(tensor1, tensor2)) # Output: True
In the above code, both tensors have the same shape ([3]), data type (torch.int64), device (CPU), and values.
Different values

If the input tensors have the same size but different values, the .equal() method returns False.
import torch first_tensor = torch.tensor([1, 2, 3]) second_tensor = torch.tensor([1, 2, 4]) print(torch.equal(first_tensor, second_tensor)) # Output: False
In the above code, only the last elements of both tensors are different. The first_tensor has element 3, and the second_tensor has element 4. So, they are not the same and returned False.
Different Data Types
If the first tensor has an integer type and the second tensor has a float type, it will return True as long as the values are the same in both input tensors.
import torch int_tensor = torch.tensor([1, 2, 3], dtype=torch.int64) float_tensor = torch.tensor([1, 2, 3], dtype=torch.float32) print(torch.equal(int_tensor, float_tensor)) # Output: True
Empty tensors
If you compare two empty tensors, it will return True.
import torch empty_tensor_one = torch.tensor([], dtype=torch.float32) empty_tensor_two = torch.tensor([], dtype=torch.float32) print(torch.equal(empty_tensor_one, empty_tensor_two)) # Output: True
Multi-dimensional tensors
Multi-dimensional tensors are compared element-wise, and all properties (shape and device) must match.
import torch tensor1 = torch.tensor([[1, 2], [3, 4]]) tensor2 = torch.tensor([[1, 2], [3, 4]]) print(torch.equal(tensor1, tensor2)) # Output: TrueThat’s all!