PyTorch .mul()

method9081102191's avatar
Published Oct 28, 2025
Contribute to Docs

The .mul() function multiplies each element in the input tensor with another tensor or a scalar and returns a tensor of the same shape as the input (or broadcasted shape when inputs have different shapes).

  • Learn to build machine learning models with Python.
    • Includes 10 Courses
    • With Certificate
    • Beginner Friendly.
      23 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

torch.mul(input, other, *, out=None) → Tensor

Parameters:

  • input (Tensor): Input tensor.
  • other (Tensor or Integer): The second input can be another tensor or a scalar value.
  • out (Tensor, optional): Optional tensor to store the output.

Return value:

Returns a new tensor containing the result of the operation, or modifies the out tensor if provided.

Example 1: Applying .mul() with a 1D tensor and a scalar

In this example, .mul() multiplies a 1D tensor and a scalar:

import torch
# Create a tensor
x = torch.tensor([1, 2, 3])
# Multiply by scalar
result = torch.mul(x, 2)
print(result)

The output of this code is:

tensor([2, 4, 6])

Example 2: Using .mul() with two 1D tensors

In this example, .mul() multiplies each element in a 1D tensor with another 1D tensor:

import torch
# Create a tensor
x = torch.tensor([1.0, 2.0, 3.0])
# Create a second tensor
y = torch.tensor([4.0, 5.0, 6.0])
# Multiply by tensor
result = torch.mul(x, y)
print(result)

The output of this code is:

tensor([ 4., 10., 18.])

Example 3: Using .mul() with a 2D tensor and a 1D tensor

In this example, .mul() multiplies a 2D tensor with a 1D tensor using broadcasting:

import torch
# Create a 2x3 tensor
x = torch.tensor([[1.0, 2.5, 3.0],[4.0, 5.0, 6.5]])
# Create a second tensor
y = torch.tensor([7.0, 8.0, 9.1])
# Multiply by tensor
result = torch.mul(x, y)
print(result)

The output of this code is:

tensor([[ 7.0000, 20.0000, 27.3000],
[28.0000, 40.0000, 59.1500]])

All contributors

Contribute to Docs

Learn PyTorch on Codecademy

  • Learn to build machine learning models with Python.
    • Includes 10 Courses
    • With Certificate
    • Beginner Friendly.
      23 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours