Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

PyTorch · Function

torch.abs

Computes the absolute value of every element in a tensor and returns the resulting tensor. An optional output tensor can receive the result.

How it works

torch.abs applies the absolute-value operation independently to every element of the input tensor and returns the resulting tensor. You can optionally provide an out tensor to receive the result.

Syntax

torch.abs(input: Tensor, *, out: Tensor | None = None) → Tensor

Parameters

NameTypeDescription
inputTensorInput tensor whose elements are transformed.
outTensor | NoneOptional output tensor that receives the result.

Returns

A Tensor containing the elementwise absolute values of input.

Key points

  • The operation is elementwise: each input value is replaced by its absolute value.
  • The function takes a Tensor and returns a Tensor; out is an optional keyword-only argument.
  • Mathematically, each output element equals the magnitude of the corresponding input element.
  • A tensor containing negative and positive integers produces nonnegative values at the same positions.

Common mistakes

  • The optional out argument writes the result into a supplied output tensor; ensure that tensor is suitable for the operation.

Example: Compute elementwise absolute values

import torch

x = torch.tensor([-1.0, 0.0, 2.5])
y = torch.abs(x)
print(y)  # tensor([1.0000, 0.0000, 2.5000])

Creates a tensor containing negative, zero, and positive values, then returns their elementwise absolute values.

When to use it

Convert signed features to magnitudes

Data preprocessing

Measure elementwise deviations without sign

Loss and metric preparation

Obtain element magnitudes

Complex-valued tensors

Interview questions

QWhat does torch.abs do?

torch.abs computes the absolute value of every element in a Tensor and returns a Tensor containing those results. For an element input_i, the result is |input_i|.

Follow-up: How would you apply the same operation to several tensors efficiently? Use torch.foreach.abs or the corresponding foreach operation, which applies torch.abs independently at each list position.

QWhat are torch.abs's parameters and return value?

The input parameter is a Tensor, and the function accepts an optional keyword-only out Tensor. The returned value is the resulting Tensor.

Follow-up: What is the in-place alternative? torch.abs_ is the in-place version of torch.abs and modifies the input rather than producing a separate result.

QHow does torch.abs transform a tensor?

For torch.tensor([-1, -2, 3]), torch.abs returns tensor([1, 2, 3]). The operation is pointwise, so tensor shape and element positions are preserved.

Follow-up: Is there an alias? Yes. torch.absolute is documented as an alias for torch.abs.

  • torch.absolute
  • torch.abs_
  • torch.foreach.abs

Source: torch.abs — PyTorch 2.13 documentation. Checked 2026-10-16.