PyTorch torch.clone() Method

PyTorch torch.clone() method is “used to create a copy of an input tensor, retaining its data and requiring a gradient if the original tensor required a gradient.”

Syntax

torch.clone(input, *, memory_format=torch.preserve_format)

Parameters

  1. input (Tensor): It is the input tensor.
  2. memory_format (torch.memory_format, optional): It is the desired memory format of the returned tensor.

Example 1: Basic Cloning

import torch

# Create a tensor
original_tensor = torch.Tensor([1, 2, 3, 4, 5])

# Clone the tensor
cloned_tensor = torch.clone(original_tensor)

print(cloned_tensor)

Output

tensor([1., 2., 3., 4., 5.])

Example 2: Cloning with Autograd

If you’re working with tensors that require gradients for autograd, torch.clone() is a helpful method to copy such tensors.

import torch

# Create a tensor that requires gradients
original_tensor = torch.Tensor([1, 2, 3, 4, 5]).requires_grad_()

# Clone the tensor
cloned_tensor = torch.clone(original_tensor)

# The cloned tensor also requires gradients
print(cloned_tensor.requires_grad)

Output

True

Example 3: Cloning and Modification

import torch

# Create a tensor
original_tensor = torch.Tensor([1, 2, 3, 4, 5])

# Clone the tensor
cloned_tensor = torch.clone(original_tensor)

# Modify the cloned tensor
cloned_tensor[0] = 10

# The original tensor remains unchanged
print("Original tensor:", original_tensor)
print("Cloned tensor:", cloned_tensor)

Output

Original tensor: tensor([1., 2., 3., 4., 5.])

Cloned tensor: tensor([10., 2., 3., 4., 5.])

That’s it!

Related posts

torch.squeeze()

torch.sum()

torch.full()

Leave a Comment