The torch.mul() method performs element-wise multiplication between two tensors or a tensor and a scalar value. This method is equivalent to the * operator in PyTorch.

Syntax
torch.mul(input, other, out=None)
Parameters
Argument | Description |
input (Tensor) | It represents an input tensor. |
other (Tensor or Number) |
It is the second tensor or scalar to multiply with the input. |
out (Tensor, optional) | An output tensor to store the result. |
Element-wise multiplication of two tensors
Let’s define two 2D tensors of the same size and multiply their elements, and the output tensor will also be 2D.
import torch # Define tensors t1 = torch.tensor([[1, 2], [3, 4]]) t2 = torch.tensor([[5, 6], [7, 8]]) # Element-wise multiplication multiplied_tensor = torch.mul(t1, t2) print(multiplied_tensor) # Output: # tensor([[ 5, 12], # [21, 32]])
In this code, you can see that the multiplication happened between the first element of the first tensor and the first element of the second tensor. 5×1 = 5. So, the output tensor’s first element is 5.
Now, multiplication happened between the second element of the first tensor and the second element of the second tensor, which is 2×6 = 12. So, the second element of the output tensor is 12.
Same for the third element of the first tensor and the third element of the second tensor, which is 3×7 = 21.
Same for the fourth element of the first tensor and the fourth element of the second tensor, so 4×8 = 32, which is the fourth element of the output tensor. That’s how element-wise multiplication is done.
Scalar multiplication

Let’s multiply a tensor with a scalar (a single value).
import torch tensor = torch.tensor([[1, 2], [3, 4]]) scalar = 9 # Scalar multiplication scalar_multiplied_tensor = torch.mul(tensor, scalar) print(scalar_multiplied_tensor) # Output: # tensor([[ 9, 18], # [27, 36]])
In the above code, every element in the tensor is multiplied by the scalar 9.
Broadcasting with Different Shapes
If the input tensors have compatible shapes, it can handle it via broadcasting.
import torch tensor1 = torch.tensor([[1, 5], [3, 6]]) tensor2 = torch.tensor([2, 3]) # Broadcasting multiplication broadcast_multiplication = torch.mul(tensor1, tensor2) print(broadcast_multiplication) # Output: # tensor([[ 2, 15], # [ 6, 18]])
In this code, the tensor2 is broadcast to shape (2, 2) by replicating [2, 3] across rows. And then it will perform element-wise multiplication.
In-place Operation with “out”
You can store the result of the multiplication in a pre-allocated tensor.
To create a pre-allocated tensor, you can use torch.zeros() method.
import torch # Define tensors a = torch.tensor([[1, 2], [3, 4]]) b = torch.tensor([[5, 6], [7, 8]]) out = torch.zeros(2, 2) # In-place multiplication torch.mul(a, b, out=out) print(out) # Output: # tensor([[ 5., 12.], # [21., 32.]])That’s all!