Build constant-one inputs or parameters
Model initialization
PyTorch · Function
Creates a tensor filled with 1, using the supplied dimensions as its shape. Optional keywords control its output tensor, dtype, layout, device, and autograd behavior.
torch.ones creates a new tensor whose dimensions come from the supplied size arguments or a single shape collection. It fills every element with 1 and lets you choose the data type, layout, device, and whether autograd records operations involving the result.
torch.ones(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor| Name | Type | Description |
|---|---|---|
size | int... | Dimensions of the output; provide multiple integers or one collection such as a list or tuple. |
out | Tensor, optional | Optional output tensor to receive the result. |
dtype | torch.dtype, optional | Data type of the returned tensor; None uses the global default dtype. |
layout | torch.layout, optional | Layout of the returned tensor; defaults to torch.strided. |
device | torch.device, optional | Device on which the returned tensor is allocated; None uses the current default-tensor device. |
requires_grad | bool, optional | Whether autograd records operations on the returned tensor; defaults to False. |
Tensor
import torch
x = torch.ones((2, 3), dtype=torch.float64, device="cpu")
print(x)
# tensor([[1., 1., 1.],
# [1., 1., 1.]], dtype=torch.float64)Creates a 2-by-3 CPU tensor filled with ones using 64-bit floating-point values.
Model initialization
Mask construction
Device-aware setup
Typed computation
torch.ones returns a tensor filled with the scalar value 1. Its shape is defined by size, which can be passed as multiple integer arguments or as a list or tuple.
Follow-up: How would you create a 2×3 tensor without relying on the default floating-point type? Pass a shape and an explicit dtype, such as torch.ones((2, 3), dtype=torch.int32).
The function accepts dtype, layout, device, and requires_grad as keyword options. dtype controls the returned data type, layout controls tensor layout, device controls placement, and requires_grad controls autograd recording.
Follow-up: How can placement be made deterministic? Supply an explicit torch.device, such as device="cuda" or device="cpu", rather than relying on the default.
requires_grad defaults to False, so autograd does not record operations on the returned tensor unless requested. Set requires_grad=True when the tensor should participate in recorded gradient computation.
Follow-up: What other allocation-related option can reuse storage? The optional out argument supplies an output tensor for the operation.
torch.emptytorch.fulltorch.ones_liketorch.randtorch.zeros