torch.Tensor.Tensor.new_empty
Tensor.new_empty(size: number[], options?: TensorOptions): Tensor<DynamicShape, D, Dev>Creates a new uninitialized tensor with same dtype and device as this tensor.
Allocates memory for a tensor with specified shape but does not initialize values. The returned tensor contains garbage/random values from uninitialized GPU/CPU memory. Useful when you plan to fill the tensor immediately (more efficient than allocate-then-fill). Inherits dtype and device from this tensor (but can override with options).
Common use cases:
- Pre-allocate buffers before filling with specific values
- Batch processing with pre-allocated storage
- Buffer reuse in loops (faster than repeated allocation)
- Internal temporary tensors that will be overwritten
- Template tensor to create similar ones with different data
- Uninitialized: Contains garbage values. Don't use contents without filling first.
- Dtype/device inherit: Copies dtype/device from this tensor by default.
- Can override: Use options to specify different dtype/device.
- Fast allocation: Faster than new_zeros/new_ones since no fill needed.
- GPU memory: Allocates GPU memory if this tensor is on WebGPU.
- Garbage values: Never use the values directly - they are uninitialized memory.
- Must fill: You must populate the tensor before using it.
Parameters
sizenumber[]- Shape of the new tensor (array of dimension sizes)
optionsTensorOptionsoptional- Optional overrides for dtype/device (defaults to this tensor's dtype/device)
Returns
Tensor<DynamicShape, D, Dev>– New tensor with uninitialized (garbage) values, same dtype/device as this tensorExamples
// Create buffer matching this tensor's dtype/device
const x = torch.tensor([1, 2, 3], { dtype: 'float32', device: 'cpu' });
const buffer = x.new_empty([10, 20]); // float32, cpu, uninitialized
// Batch buffer pre-allocation
const model_output = torch.zeros(1); // Template tensor on GPU
const batch_results = model_output.new_empty([batch_size, num_outputs]);
for (let i = 0; i < batch_size; i++) {
batch_results[i] = model(inputs[i]); // Fill buffer
}
// Override dtype but keep device
const float_tensor = torch.ones(3, { dtype: 'float32', device: 'webgpu' });
const int_buffer = float_tensor.new_empty([100], { dtype: 'int32' }); // int32, webgpu
// Efficient reusable buffer
const buffer = reference_tensor.new_empty([max_size]);
for (const batch of data) {
buffer.copy_(batch); // Reuse same buffer
result = process(buffer);
}See Also
- PyTorch tensor.new_empty()
- new_zeros - Same size but filled with zeros
- new_ones - Same size but filled with ones
- new_full - Same size but filled with specific value
- empty - Module-level function to create empty tensors