## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", eval = FALSE)

## ----select-------------------------------------------------------------------
# library(cudaverse)
# cuda_select_device("cuda")

## ----tensor-pipeline----------------------------------------------------------
# set.seed(1)
# x <- matrix(rnorm(10000 * 100), nrow = 10000)
# x_gpu <- cuda_tensor(x, device = "cuda", dtype = "float32")
# 
# means_gpu <- tensor_mean(x_gpu, dim = 1)
# centered_gpu <- x_gpu - means_gpu
# selected_gpu <- centered_gpu[, 1:50, drop = FALSE]
# gram_gpu <- tensor_matmul(t(selected_gpu), selected_gpu)
# 
# tensor_device(gram_gpu)
# cuda_provenance(gram_gpu)

## ----tensor-download----------------------------------------------------------
# gram <- to_cpu(gram_gpu)

## ----pca-knn------------------------------------------------------------------
# pca <- cuda_pca(
#   x_gpu,
#   n_components = 20,
#   device = "cuda"
# )
# 
# neighbors <- cuda_knn(
#   pca$x,
#   k = 15,
#   batch_size = 256,
#   device = "cuda"
# )
# 
# cuda_provenance(pca)
# cuda_provenance(neighbors)
# head(neighbors$index)

## ----sparse-resident----------------------------------------------------------
# counts <- Matrix::rsparsematrix(50000, 128, density = 0.01)
# counts@x <- abs(counts@x)
# 
# counts_gpu <- cuda_sparse(counts, device = "cuda")
# normalized_gpu <- sparse_normalize(
#   counts_gpu,
#   margin = "rows",
#   scale_factor = 10000,
#   log1p = TRUE
# )
# sparse_pca <- cuda_pca(normalized_gpu, n_components = 20, device = "cuda")
# sparse_neighbors <- cuda_knn(
#   sparse_pca$x,
#   k = 15,
#   device = "cuda"
# )
# 
# sparse_info(normalized_gpu)
# cuda_provenance(sparse_neighbors)

## ----inspect-stages-----------------------------------------------------------
# prov <- cuda_provenance(neighbors)
# prov$stages

## ----memory-------------------------------------------------------------------
# cuda_memory_info("cuda")

## ----assert-native------------------------------------------------------------
# stages <- cuda_provenance(neighbors)$stages
# vapply(stages, `[[`, character(1), "device")
# vapply(stages, `[[`, character(1), "backend")

