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**

**input (Tensor)**: It is the input tensor.

**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**

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.