Scalar offset
Add a constant offset to every tensor element.
PyTorch · Function
Adds other, scaled by alpha, to input elementwise. Tensor operands support broadcasting and the operation returns a tensor.
torch.add computes elementwise addition as input plus alpha multiplied by other. The operands may be tensors or a scalar, and tensor operands can be broadcast to a common shape; the optional out tensor receives the result.
torch.add(input, other, *, alpha=1, out=None) → Tensor| Name | Type | Description |
|---|---|---|
input | Tensor | Input tensor. |
other | Tensor or Number | Tensor or number added to input. |
alpha | Number | Multiplier applied to other before addition; defaults to 1. |
out | Tensor, optional | Optional tensor that receives the output. |
Tensor
import torch
input = torch.tensor([1., 2., 3.])
result = torch.add(input, 5, alpha=2)
print(result) # tensor([11., 12., 13.])Adds twice the scalar 5 to every element of the input tensor.
Add a constant offset to every tensor element.
Combine tensors whose dimensions are broadcast-compatible.
Apply a weighted residual or correction term.
It returns the elementwise expression input + alpha × other. other may be a tensor or number, and tensor operands support broadcasting.
Follow-up: How would you add a tensor with a different shape? Use shapes that are broadcast-compatible, such as a vector and a column vector.
alpha scales other before addition, so alpha=3 computes input + 3 × other. Its default value is 1.
Follow-up: What does alpha=-1 do? It subtracts other from input because input + (-1) × other equals input - other.
The function accepts an optional out tensor for storing the result. Without it, torch.add returns a result tensor directly.
Follow-up: What should be checked when supplying out? Ensure the destination tensor is suitable for the resulting shape and dtype.
torch.Tensor.addtorch.addmvtorch.foreach.add