torch.get_default_device
function get_default_device(): DeviceTypeReturns the current default device for tensor operations.
The default device is used implicitly when creating tensors without specifying a device parameter. torch.js automatically falls back to CPU if WebGPU is unavailable, so this will return either 'webgpu' (GPU acceleration available) or 'cpu' (CPU fallback).
Typical Values:
- 'webgpu': Modern browser with WebGPU support (Chrome 113+, Firefox experimental, Safari 18+)
- 'cpu': Browser without WebGPU, or GPU initialization failed
Usage Pattern:
const device = torch.get_default_device();
const x = torch.randn([3, 4]); // Uses default device (no explicit device parameter)
const y = torch.randn([3, 4], { device: 'webgpu' }); // Explicit device overrides default- Query-only: Does not change any settings
- Auto-fallback: Automatically 'cpu' if WebGPU unavailable
- Override possible: Can specify device in individual operations
- Set with set_default_device(): To change the default
Returns
DeviceType– The current default device: 'webgpu' or 'cpu'Examples
// Check what device is being used by default
const device = torch.get_default_device();
console.log(`Using ${device} device`);
// Conditional logic based on available device
if (torch.get_default_device() === 'cpu') {
console.warn('GPU not available, using slower CPU mode');
// Use smaller batch sizes for memory efficiency
const batch_size = 8;
} else {
// GPU available, can use larger batches
const batch_size = 128;
}
// All these use the default device
const a = torch.zeros([2, 3]);
const b = torch.ones([4, 5]);
const c = a + b; // Addition happens on default deviceSee Also
- PyTorch torch.get_default_device() (torch.js specific enhancement)
- set_default_device - Change the default device
- is_webgpu_available - Check if WebGPU is available
- is_cpu_only_mode - Check if running in CPU-only fallback