要在并行计算中更新相同的内存(矩阵)吗?

问题描述 投票:0回答:1

我有一个很强的用例来并行化SGD算法的风格。在这种用例中,我需要使用增量梯度更新以及随机一批样本来更新矩阵P和Q。每个过程将更新两个矩阵的互斥索引。

我打算做的简单说明就是这样:

# create "big" matrix
A <- matrix(rnorm(10000), 100, 100)
system.time(
  # update each row vector independently using all my cores
  r <- mclapply(1:100, mc.cores = 6, function(i) {
    # updating ... 
    A[i,] <- A[i,] - 0.01
    # return something, i.e. here I'd return the RMSE of this batch instead   
    sqrt(sum(A[i,]^2))
  }) 
)

使用此方法是否有任何弊端?还有更多R惯用的替代方法吗?

例如,为干净起见(即没有副作用,不可变的计算),返回更新A[i,] - 0.01而不是RMSE会更复杂,并且编程会使内存使用达到峰值,甚至耗尽内存。

r concurrency parallel-processing multicore
1个回答
0
投票
N <- 10e3 A <- matrix(rnorm(N * N), N) library(bigstatsr) bigA <- as_FBM(A) library(doParallel) registerDoParallel(cl <- makeCluster(4)) system.time( r <- foreach(i = seq_len(N), .combine = 'c') %dopar% { # updating ... A[i,] <- A[i,] - 0.01 # return something, i.e. here I'd return the RMSE of this batch instead sqrt(sum(A[i,]^2)) } ) # 11 sec stopCluster(cl) registerDoParallel(cl <- makeCluster(4)) system.time( r2 <- big_apply(bigA, function(X, ind) { # updating ... tmp <- bigA[ind, ] <- bigA[ind, ] - 0.01 # return something, i.e. here I'd return the RMSE of this batch instead sqrt(rowSums(tmp^2)) }, a.combine = 'c') ) # 1 sex stopCluster(cl) all.equal(r, r2) # TRUE

同样,最好更新列而不是行。

© www.soinside.com 2019 - 2024. All rights reserved.