The torch.heaviside() method implements the Heaviside step function, a mathematical function that returns 0 for negative inputs, a specified value for zero inputs, and 1 for positive inputs.

This method takes two tensors as input:
- input_tensor: It is the tensor containing the values for which the step function is to be calculated.
- values_tensor: It is the tensor that provides the value to return when the elements of the input are exactly 0.
Here is the summary for this method:
- If input < 0, the output is 0.
- If input > 0, the output is 1.
- If input == 0, the output is values (i.e., the corresponding element in the second tensor).
Syntax
torch.heaviside(input, values, out=None)
Parameters
Argument | Description |
input (Tensor) | It is an input tensor for the evaluation. |
values (Tensor) | It is a tensor with multiple values or a scalar-tensor that is returned when the input is zero. |
out (Tensor, optional) | It is the output tensor to store the result (Default: None). |
Usage with scalar values
Let’s apply the Heaviside function to a tensor with a fixed value for zero inputs.
import torch input = torch.tensor([-2.1, 0.0, 1.5]) values = torch.tensor([0.5]) output = torch.heaviside(input, values) print(output) # Output: tensor([0.0000, 0.5000, 1.0000])
In this code, -2.1 becomes 0.0000, 0.0 becomes values tensor’s 0.5000, and 1.5 becomes 1.0000.
If you come across this RuntimeError: heaviside is not yet implemented for complex tensors, that means your input is a complex tensor.
Don’t use the complex tensor because the .heaviside() method does not support complex tensors as of PyTorch 2.7.
The primary applications of the Heaviside function include signal processing, physics modeling, and custom autograd logic.