torch.set_default_device
function set_default_device(device: DeviceType): voidSets the default device for tensor creation operations.
Configures which device ('webgpu' or 'cpu') will be used when creating tensors
that don't explicitly specify a device. This affects all subsequent tensor creation
unless individually overridden with the device option.
Common Use Cases:
- Force CPU mode for testing or debugging
- Ensure GPU mode is used when available
- Adapt to device availability at runtime
- Control memory/performance tradeoffs
Device Options:
- 'webgpu': GPU acceleration (requires WebGPU support)
- 'cpu': CPU fallback (always available)
Behavior:
- Sets global default affecting all tensor creation
- Individual operations can override with explicit
deviceparameter - Automatically reset to 'cpu' if WebGPU fails during init()
- Global setting: Affects all tensors without explicit device
- Can be changed: Toggle at any time during execution
- Validation: Validates device name, throws on invalid names
- Auto-fallback: torch.js will still use CPU if requested GPU unavailable
- Not persistent: Setting is lost on page refresh
- GPU requirement: Setting 'webgpu' doesn't guarantee GPU use if unavailable
- Override possible: Individual operations can still specify different device
Parameters
deviceDeviceType- The device type: 'webgpu' or 'cpu'
Returns
void
Examples
// Force CPU for reproducible debugging
torch.set_default_device('cpu');
const x = torch.randn([3, 4]); // Uses CPU
const y = torch.zeros([5, 6]); // Uses CPU
// Reset to GPU if available
torch.set_default_device('webgpu');
const z = torch.randn([100, 100]); // Uses WebGPU if available, CPU otherwise
// Adaptive to environment
if (torch.is_webgpu_available()) {
torch.set_default_device('webgpu');
console.log('Using GPU acceleration');
} else {
torch.set_default_device('cpu');
console.warn('GPU not available, using CPU');
}
// Create tensors - all use the set default device
const batch = torch.randn([32, 64]);
const model_output = model.forward(batch);
// Override default for specific operations
const weights = torch.randn([64, 32], { device: 'cpu' }); // Force CPU for this tensor
// Check what was set
console.log(torch.get_default_device()); // 'webgpu' or 'cpu'See Also
- PyTorch torch.set_default_device() (torch.js specific)
- get_default_device - Query current default device
- is_webgpu_available - Check if WebGPU is available
- is_cpu_only_mode - Check if running in CPU fallback