Initialize constant tensors
Building masks or indicator arrays with a known constant.
PyTorch · Function
Creates a tensor with a specified shape and fills every element with one scalar value. Its dtype is inferred from the fill value unless dtype is provided explicitly.
torch.full constructs a tensor with the requested shape and places the same scalar in every element. Unless explicitly specified, the result’s dtype is inferred from the fill value, while layout, device, and gradient tracking can be controlled with keyword arguments.
torch.full(*size*, *fill_value*, ***, *out=None*, *dtype=None*, *layout=torch.strided*, *device=None*, *requires_grad=False*) → Tensor| Name | Type | Description |
|---|---|---|
size | int... | Shape of the output tensor, provided as integers in a list, tuple, or torch.Size. |
fill_value | Scalar | Scalar written into every output element. |
out | Tensor, optional | Optional destination tensor. |
dtype | torch.dtype, optional | Optional output dtype; if None, the global default is used when applicable. |
layout | torch.layout, optional | Optional output layout; defaults to torch.strided. |
device | torch.device, optional | Optional output device; if None, the current default device is used. |
requires_grad | bool, optional | Whether autograd records operations on the returned tensor; defaults to False. |
A Tensor of the requested size, filled with fill_value.
import torch
x = torch.full((2, 3), 7, dtype=torch.int64)
print(x)
# tensor([[7, 7, 7],
# [7, 7, 7]])Creates and prints a 2-by-3 integer tensor whose every element is 7.
Building masks or indicator arrays with a known constant.
Creating test inputs or baseline values with a chosen shape.
Allocating a tensor directly on a selected device and with a selected dtype.
torch.full creates a tensor with the shape described by size and fills every element with fill_value. The size may be an integer sequence, tuple, or torch.Size.
Follow-up: How would you guarantee the result is integer-valued? Pass an explicit integer dtype, such as dtype=torch.int64, instead of relying on inference.
If dtype is None, PyTorch infers the tensor dtype from fill_value. An explicit dtype overrides that inference and is preferable when a stable type is part of an interface.
Follow-up: What determines dtype when the fill value is floating-point and dtype is omitted? The configured global default dtype is used.
The function accepts keyword options for out, dtype, layout, device, and requires_grad. layout defaults to torch.strided, requires_grad defaults to False, and device defaults according to the current default tensor settings.
Follow-up: How can placement be made explicit? Supply a torch.device through the device keyword, such as device='cuda'.
torch.emptytorch.onestorch.zerostorch.full_like