torch.empty_like
function empty_like<S extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(input: Tensor<S, D, Dev>, options: TensorOptions = {}): Tensor<S, D, Dev>Create an uninitialized tensor with the same shape as another tensor.
Returns a new tensor with identical shape to the input but with uninitialized values.
In WebGPU, values are zeroed for safety, so it behaves like zeros_like().
Useful for pre-allocating output buffers or intermediate tensors to be immediately overwritten.
By default, matches input's dtype, device, and gradient requirements. Override any of these with the options parameter.
- Uninitialized values: Undefined on CPU; zeros on WebGPU for safety
- Shape matching: Automatically infers shape from input
- Fast allocation: No initialization overhead (except WebGPU safety zeroing)
- Output buffer: Common use for pre-allocated outputs
Undefined values (CPU): Do not rely on values; they are garbage! Must be overwritten before use on CPU backend.
Parameters
inputTensor<S, D, Dev>- Tensor to match shape from
optionsTensorOptionsoptional- Optional overrides: -
dtype: Data type (default: same as input) -requires_grad: Gradient tracking (default: same as input) -device: Compute device (default: same as input)
Returns
Tensor<S, D, Dev>– An uninitialized tensor with shape = input.shapeExamples
// Fast allocation matching input shape
const x = torch.randn(3, 4, 5);
const buffer = torch.empty_like(x); // [3, 4, 5] uninitialized (CPU) / zeros (WebGPU)
// Pre-allocate output for computation
const out = torch.empty_like(x);
torch.relu(x).copyTo_(out); // Overwrite with result
// Accumulator to be filled in loop
const accumulator = torch.empty_like(batch[0]);
for (const sample of batch) {
accumulator.add_(sample); // Will overwrite
}See Also
- PyTorch torch.empty_like()
- empty - Create uninitialized tensor with explicit shape
- zeros_like - Zero-filled tensor with same shape
- ones_like - One-filled tensor with same shape
- full_like - Constant-filled tensor with same shape