torch.is_cpu_only_mode
function is_cpu_only_mode(): booleanChecks if the current environment is operating in CPU-only mode.
Returns true if WebGPU initialization was attempted but failed,
indicating that torch.js is running entirely on CPU without GPU acceleration.
Returns false if WebGPU is available and initialized successfully.
When This is True:
- Browser doesn't support WebGPU (Safari <18, old Chrome, IE, Firefox without flag)
- WebGPU initialization failed for some reason (driver issue, hardware issue)
- torch.init() completed and detected no GPU support
Performance Implications:
- CPU operations are generally 10-100x slower than GPU
- Should use smaller batches, models, and datasets
- Some operations may not be implemented on CPU
Use Cases:
- Adapt batch sizes to available hardware
- Skip GPU-specific optimizations
- Provide helpful error messages to users
- Fallback to alternative algorithms
- Binary check: Simpler than is_webgpu_available() for common case
- After init: Call after torch.init() for accurate result
- Performance critical: Often used to optimize batch size or model complexity
- True only if failed: True only if WebGPU was attempted and failed
- Null handling: Before torch.init(), result is effectively false
- Performance: CPU operations are very slow - plan accordingly
- Limited fallbacks: Not all operations have CPU implementations
Returns
boolean– true if in CPU-only mode (WebGPU unavailable), false otherwiseExamples
// Initialize and check CPU-only mode
await torch.init();
if (torch.is_cpu_only_mode()) {
console.warn('⚠️ Running in CPU-only mode - expect slower performance');
// Reduce workload for CPU
const batch_size = 8;
const model_size = 'small'; // Use smaller model
} else {
console.log('✓ GPU acceleration enabled');
// Can use larger workloads
const batch_size = 128;
const model_size = 'large';
}
// Conditional algorithm selection
if (torch.is_cpu_only_mode()) {
// Use faster but less accurate algorithm
const result = fastApproximation(input);
} else {
// Use more accurate GPU algorithm
const result = accurateComputation(input);
}
// Performance warning for users
if (torch.is_cpu_only_mode()) {
alert('WebGPU not supported in your browser. ' +
'Please upgrade to Chrome 113+ or Safari 18+ for GPU acceleration.');
}
// Batch size tuning
const maxBatchSize = torch.is_cpu_only_mode() ? 16 : 256;
for (let i = 0; i < dataset.length; i += maxBatchSize) {
const batch = dataset.slice(i, i + maxBatchSize);
trainStep(batch);
}
// Combined with device checks
if (!torch.is_cpu_only_mode() && torch.get_default_device() === 'webgpu') {
console.log('GPU acceleration fully active');
}See Also
- [PyTorch N/A (torch.js specific)](https://pytorch.org/docs/stable/generated/N/A .html)
- is_webgpu_available - More detailed GPU availability status
- get_default_device - Get current default device
- torch.init - Initialize and detect GPU support