How to release GPU memory on R after fit?

Is there a way to release the GPU memory used by a model after it is already fit on the R package?

On the python package, from what understood you can do that by calling the ‘.__ del__()’ function of the fitted model. How could I do that on the R package?

You should be able to call the built-in method rm to free up memory: rm(booster)

Hi hcho3, thanks a lot for the reply.

I have tried:

  1. rm(bst_gpu) and then gc() .
  2. using the model’s output bst_gpu.call(’_del_’) function
  3. running the model on a separate process and stopping the thread. This releases the memory but crashes xgboost when I try to run it again.

1 and 2 do not seems to clear the gpu memory as reported in nvtop. 3 crashes xgboost. Let me show you an example code from the package:

library('xgboost')

# Simulate N x p random matrix with some binomial response dependent on pp columns
set.seed(111)
N <- 1000000
p <- 50
pp <- 25
X <- matrix(runif(N * p), ncol = p)
betas <- 2 * runif(pp) - 1
sel <- sort(sample(p, pp))
m <- X[, sel] %*% betas - 1 + rnorm(N)
y <- rbinom(N, 1, plogis(m))

tr <- sample.int(N, N * 0.75)
dtrain <- xgb.DMatrix(X[tr, ], label = y[tr])
dtest <- xgb.DMatrix(X[-tr, ], label = y[-tr])
wl <- list(train = dtrain, test = dtest)

param <- list(objective = 'reg:logistic', eval_metric = 'auc', subsample = 0.5, nthread = 4,
              max_bin = 64, tree_method = 'gpu_hist')
pt <- proc.time()
bst_gpu <- xgb.train(param, dtrain, watchlist = wl, nrounds = 50)
proc.time() - pt

rm(bst_gpu) # Does not clear gpu memory...

Have you also tried deleting the DMatrix object as well?

Yes. No good either…

I managed to solve it using item 3: create a separate process and stop the thread. After you stop the son thread or threads, the GPU memory is cleared. The secret is that the parent R session cannot have accessed the GPU thru xgboost, otherwise the crash bellow occurs.

Error in checkForRemoteErrors(val) : 
  2 nodes produced errors; first error: [23:17:55] /home/share/xgboost/src/c_api/../data/../common/common.h:44: /home/share/xgboost/src/tree/../common/device_helpers.cuh: 182: cudaErrorInitializationError: initialization error
Stack trace:
  [bt] (0) /home/R/x86_64-pc-linux-gnu-library/4.0/xgboost/libs/xgboost.so(+0x3f5828) [0x7f05434ad828]
  [bt] (1) /home/R/x86_64-pc-linux-gnu-library/4.0/xgboost/libs/xgboost.so(dh::ThrowOnCudaError(cudaError, char const*, int)+0x297) [0x7f05434b2ad7]
  [bt] (2) /home/R/x86_64-pc-linux-gnu-library/4.0/xgboost/libs/xgboost.so(dh::CheckComputeCapability()+0x113) [0x7f05436cdfb3]
  [bt] (3) /home/R/x86_64-pc-linux-gnu-library/4.0/xgboost/libs/xgboost.so(xgboost::tree::GPUHistMaker::Configure(std::vector<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx1