torch.Tensor.Tensor.new_tensor
Tensor.new_tensor(data: number | number[] | number[][], options?: TensorOptions): Tensor<DynamicShape, D, Dev>Creates a new tensor from data, inheriting dtype and device from this tensor.
Constructs a tensor from nested arrays or scalars with the same dtype and device as this tensor. Useful when creating related tensors that must match device/dtype constraints. Automatically infers shape from data structure. Can override dtype/device if needed.
Common use cases:
- Create related tensors with matching dtype/device
- Construct small constant tensors on same device as model
- Convert data while preserving device affinity
- Template-based tensor creation
- Shape inferred: Data structure determines output shape automatically.
- Dtype/device inherit: Copies dtype/device from this tensor by default.
- Type promotion: Input numbers are promoted to this tensor's dtype.
- Device affinity: Data is allocated on this tensor's device.
Parameters
datanumber | number[] | number[][]- Scalar, 1D array, or nested array of numbers (shape inferred automatically)
optionsTensorOptionsoptional- Optional overrides for dtype/device (defaults to this tensor's dtype/device)
Returns
Tensor<DynamicShape, D, Dev>– New tensor with provided dataExamples
// Create related tensor on same device
const x = torch.randn(100, 100, { device: 'webgpu' });
const y = x.new_tensor([[1, 2, 3], [4, 5, 6]]); // Also on WebGPU
// Scalar data
const ref = torch.zeros(1, { device: 'webgpu' });
const scalar = ref.new_tensor(3.14); // Single value, on WebGPU
// Match dtype but override device
const gpu_ref = torch.randn(10, { dtype: 'float32', device: 'webgpu' });
const cpu_const = gpu_ref.new_tensor([1, 2, 3], { device: 'cpu' });
// Create initializer tensors matching model device
const weights = torch.randn(100, 50, { device: 'webgpu' });
const init_values = weights.new_tensor([0.1, 0.2, 0.3]); // Also on WebGPU
// 2D constant matching batch size
const batch_output = torch.randn(32, 10, { device: 'webgpu' });
const class_weights = batch_output.new_tensor([1.0, 2.0, 3.0, 0.5, 1.5, 2.5, 0.8, 1.2, 1.8, 2.2]);See Also
- PyTorch tensor.new_tensor()
- new_zeros - Create zero tensor with explicit shape
- new_ones - Create ones tensor with explicit shape
- new_empty - Uninitialized tensor with explicit shape
- tensor - Module-level function to create tensors from data