## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", eval = FALSE)

## ----install------------------------------------------------------------------
# # install.packages("pak")
# pak::pak("cudaverse/cudaverse@v0.4.1")
# 
# library(cudaverse)
# 
# check <- cuda_diagnostics()
# check$summary
# check$next_steps
# 
# # Stop here with a useful explanation if CUDA is not ready.
# cuda_select_device("cuda")

## ----dense-pca-knn------------------------------------------------------------
# set.seed(1)
# x <- matrix(rnorm(10000 * 100), nrow = 10000, ncol = 100)
# 
# pca <- cuda_pca(
#   x,
#   n_components = 20,
#   center = TRUE,
#   scale. = FALSE,
#   device = "cuda"
# )
# 
# neighbors <- cuda_knn(
#   pca$x,
#   k = 15,
#   metric = "euclidean",
#   device = "cuda"
# )
# 
# dim(pca$x)
# dim(neighbors$index)
# head(neighbors$index)
# head(neighbors$distance)

## ----dense-provenance---------------------------------------------------------
# cuda_provenance(pca)
# cuda_provenance(neighbors)
# cuda_memory_info("cuda")

## ----tensors------------------------------------------------------------------
# x_gpu <- cuda_tensor(x, device = "cuda", dtype = "float32")
# 
# centered_gpu <- x_gpu - tensor_mean(x_gpu, dim = 1)
# gram_gpu <- tensor_matmul(t(centered_gpu), centered_gpu)
# column_totals_gpu <- tensor_sum(x_gpu, dim = 1)
# 
# tensor_device(gram_gpu)
# gram <- to_cpu(gram_gpu)
# column_totals <- to_cpu(column_totals_gpu)

## ----sparse-pipeline----------------------------------------------------------
# counts <- Matrix::rsparsematrix(10000, 100, density = 0.03)
# 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)

## ----more-tasks---------------------------------------------------------------
# svd_fit <- cuda_svd(x, nu = 20, nv = 20, device = "cuda")
# 
# distances <- cuda_distance(
#   x[1:1000, ],
#   x[1001:2000, ],
#   batch_size = 256,
#   device = "cuda"
# )
# 
# clusters <- cuda_kmeans(
#   pca$x,
#   centers = 20,
#   seed = 1,
#   device = "cuda"
# )

