R/check-device.R

Defines functions get_default_device validate_device

Documented in validate_device

#' Validate device and get default device
#'
#' Check if requested device is available. And auto-detect available GPU device
#' or fallback to CPU.
#'
#' @param device Character. Requested device.
#' @return Character string of validated device.
#' @keywords internal
validate_device = function(device) {
    device = tolower(device)

    if (device == "cuda" && !torch::cuda_is_available()) {
        cli::cli_warn("CUDA not available. Falling back to CPU.")
        return("cpu")
    }

    if (device == "mps" && !torch::backends_mps_is_available()) {
        cli::cli_warn("MPS not available. Falling back to CPU.")
        return("cpu")
    }

    if (!device %in% c("cpu", "cuda", "mps")) {
        cli::cli_abort("Invalid device: {device}. Must be 'cpu', 'cuda', or 'mps'.")
    }

    device
}

get_default_device = function() {
    if (torch::cuda_is_available()) {
        return("cuda")
    } else if (torch::backends_mps_is_available()) {
        return("mps")
    } else {
        return("cpu")
    }
}

Try the kindling package in your browser

Any scripts or data that you put into this service are public.

kindling documentation built on March 3, 2026, 9:07 a.m.