gpt4 book ai didi

matlab - 如何正确存储与 parfor 一起使用的变量?

转载 作者:行者123 更新时间:2023-12-01 13:11:03 26 4
gpt4 key购买 nike

我的计算基于二叉树,它采用变量 block (称为程序集)的两个先前实例并生成另一个。一个新的程序集是基于上层分支的两个程序集生成的,因此必须存储所有变量。

为此,我使用具有以下语法的元胞数组:Assembly_ij = Tree{ithBranch}{jthAssembly},其中 Assembly18x3 double 矩阵。这种做法是allowed然而,它并没有改进代码的执行。我认为这是由于我将变量传递给 worker 的方式不当。我收到以下警告:

The entire array or structure 'Tree' is a broadcast variable. This might result in unnecessary communication overhead.

大部分工作都在这部分代码中完成,它应该传达出我正在犯的错误。

initialBranch = initialize();
Tree{1} = initialBranch;
for i = 2 : Nbranches
branch = cell(1, elmsInBranch(i));
parfor j = 1 : elmsInBranch(i)
branch{j} = assembleBlocks(Tree{i-1}{2*j-1}, Tree{i-1}{2*j});
end
Tree{i} = branch;
end

Matlab 一定要把整个Tree 结构传递给每个worker,这是一大堆无用的复制。我不知道如何重写它以使其正常工作,但是,也许有一些聪明的方法可以为每个 worker 提取所需的变量

最佳答案

问题是您将整个 Tree{i-1} 变量传递到 parfor 循环的每个(并行)迭代中。这是因为 MATLAB 解释器不够“聪明”,无法计算出您需要 Tree{i-1} 的哪些部分,因为您是通过一些基于 的计算动态索引到它的>j.

在外循环中分配一个临时变量,可以在内循环中直接用 j 索引,应该解决这个问题:

initialBranch = initialize();
Tree{1} = initialBranch;
for i = 2 : Nbranches
N = elmsInBranch(i);
branch = cell(1, N);
% Pre-partition the data to send individual packets to each node
iTrees = arrayfun( @(j) Tree{i-1}([2*j-1,2*j]), 1:N, 'uni', 0 );
% Parallel loop...
parfor j = 1 : N
jTrees = iTrees{j}; % direct indexing using 'j', no calculation
branch{j} = assembleBlocks(jTrees{1}, jTrees{2});
end
Tree{i} = branch;
end

请注意,我添加的 cellfun 对您的数据进行分区,以便每个并行节点一次可以直接索引一个元素,该元素包含 Tree 所需的两个项目环形。这可能会导致内存重复,但比将整个数组广播到每个节点的重复要少!

关于matlab - 如何正确存储与 parfor 一起使用的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59898916/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com