R: 内存管理澄清

5
假设我有一个矩阵bigm。我需要使用这个矩阵的随机子集,并将其提供给诸如svm之类的机器学习算法。矩阵的随机子集仅在运行时才知道。此外,还有其他参数从网格中选择。
因此,我的代码看起来像这样:
foo = function (bigm, inTrain, moreParamsList) {
  parsList = c(list(data=bigm[inTrain, ]), moreParamsList)
  do.call(svm, parsList)
}

我想知道的是,R是否会使用新内存来保存parsList中的bigm[inTrain,]对象(我的猜测是会的)。我可以使用哪些命令来自行测试这样的假设?此外,在R中有没有一种使用子矩阵的方法而不使用新内存?
另外,假设我正在使用mclapply(在Linux上)调用foo函数,其中bigm位于父进程中。这是否意味着我正在创建mc.cores个bigm副本,还是所有核心都只使用来自父进程的对象?
是否有跟踪在不同核心中创建对象的内存位置和消耗的函数和启发式算法?
谢谢!
3个回答

1

针对你第一个问题,你可以使用 tracemem

此函数会标记一个对象,当内部代码复制该对象时,会打印一条消息

这里是一个例子:

a <- 1:10
tracemem(a)
## [1] "<0x000000001669cf00"
b <- a        ## b and a share memory (no message)
d <- stats::rnorm(10)
invisible(lm(d ~ a+log(b)))
## tracemem[0x000000001669cf00 -> 0x000000001669e298]   ## object a is copied twice 
## tracemem[0x000000001669cf00 -> 0x0000000016698a38]   
untracemem(a)

感谢您的回答。只是想提醒一下,这仅在使用“--enable-memory-profiling”编译R时才可用。 - asb

1

我会把我在这个主题上的研究结果放在这里:

根据multicore手册中的说明,我认为使用mclapply不会使mc.cores复制bigm

In a nutshell fork spawns a copy (child) of the current process, that can work in parallel
to the master (parent) process. At the point of forking both processes share exactly the
same state including the workspace, global options, loaded packages etc. Forking is
relatively cheap in modern operating systems and no real copy of the used memory is
created, instead both processes share the same memory and only modified parts are copied.
This makes fork an ideal tool for parallel processing since there is no need to setup the
parallel working environment, data and code is shared automatically from the start.

1
你已经从手册中找到了 mclapply 不应该复制 bigm 的信息。但是每个线程需要制作自己的小型训练矩阵副本,因为它在线程之间变化。
如果你使用例如 snow 进行并行处理,则需要在每个集群节点上都有数据的副本。然而,在这种情况下,你可以以一种只传递较小的训练矩阵的方式重写问题。
研究内存消耗行为的搜索术语是 内存分析。不幸的是,据我所知,可用的工具还不是非常方便,例如参见:

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接