我在 R 中进行了一些并行模拟,我注意到使用“L'Ecuyer-CMRG”rng 时种子没有改变。我正在阅读“Parallel R”一书,每次调用 mclapply() 时,选项 mc.set.seed = TRUE 应该给每个工人一个新种子。
这是我的代码:
library(parallel)
RNGkind("L'Ecuyer-CMRG")
mclapply(1:2, function(n) rnorm(n), mc.set.seed = TRUE)
[[1]]
[1] -0.7125037
[[2]]
[1] -0.9013552 0.3445190
mclapply(1:2, function(n) rnorm(n), mc.set.seed = TRUE)
[[1]]
[1] -0.7125037
[[2]]
[1] -0.9013552 0.3445190
Run Code Online (Sandbox Code Playgroud)
编辑:同样的事情发生在我的台式机和我的笔记本电脑上(都是 Ubuntu 12.04 LTS)。
我正在尝试使用 concurrent.futures 模块将一个需要很长时间的进程拆分为多个进程。附上下面的代码
主功能:
with concurrent.futures.ProcessPoolExecutor() as executor:
for idx, score in zip([idx for idx in range(dataframe.shape[0])],executor.map(get_max_fuzzy_score,[dataframe[idx:idx+1] for idx in range(dataframe.shape[0])])):
print('processing '+str(idx+1)+' of '+str(dataframe.shape[0]+1))
dataframe['max_row_score'].iloc[idx] = score
Run Code Online (Sandbox Code Playgroud)
get_max_fuzzy_score 函数:
def get_max_fuzzy_score(picklepath_or_list, df):
import numpy as np
extracted_text_columns = list(df.filter(regex='extracted_text').columns)
data_list = [df[data].iloc[0] for data in extracted_text_columns if not df[data].isnull().values.any()]
try:
size = len(picklepath_or_list)
section_snippet_list = picklepath_or_list
except:
section_snippet_list = pickle.load(open(picklepath_or_list,'rb'))
scores = []
for section_snippet in section_snippet_list:
for data in data_list:
scores.append(fuzz.partial_ratio(data,section_snippet))
score = max(scores)
return score
Run Code Online (Sandbox Code Playgroud)
该函数采用几列的值,并从先前构建的列表中返回最大模糊分数。
这是我得到的错误: …
parallel-processing distributed-computing python-3.x concurrent.futures python-multiprocessing
我正在使用dask.distributed(令人尴尬的并行任务)并行化一些代码。
.
from dask.distributed import Client, LocalCluster
cluster = LocalCluster(n_workers=2, threads_per_worker=1,memory_limit =8e9)
client = Client(cluster)
Run Code Online (Sandbox Code Playgroud)
.
distributed.worker - WARNING - Memory use is high but worker has no data to store to disk.
Perhaps some other process is leaking memory? Process memory: 6.21 GB -- Worker memory limit: 8.00 GB
Run Code Online (Sandbox Code Playgroud)
暗示工作人员使用的部分 RAM 不在freed不同文件之间(我猜是剩余的过滤中间体......)
有没有办法在开始处理下一个图像之前释放工人的内存?我必须garbage collector在运行任务之间运行一个循环吗?
我有一个很大的句子列表(约 7 百万个),我想从中提取名词。
我使用joblib库来并行化提取过程,如下所示:
import spacy
from tqdm import tqdm
from joblib import Parallel, delayed
nlp = spacy.load('en_core_web_sm')
class nouns:
def get_nouns(self, text):
doc = nlp(u"{}".format(text))
return [token.text for token in doc if token.tag_ in ['NN', 'NNP', 'NNS', 'NNPS']]
def parallelize(self, sentences):
results = Parallel(n_jobs=1)(delayed(self.get_nouns)(sent) for sent in tqdm(sentences))
return results
if __name__ == '__main__':
sentences = ['we went to the school yesterday',
'The weather is really cold',
'Can we catch the dog?',
'How old are you John?', …Run Code Online (Sandbox Code Playgroud) 我的任务是将依赖节点列表转换为 AWS Step Functions。AWS Step Function 定义允许并行分支甚至分支嵌套到多级深度。不幸的是,它不支持分支中任务之间的依赖关系,因此强制您在两个结果可用于步骤函数中的后续任务之前完成并行步骤。
在我的图表中,Step Functions 可以轻松支持如图 1 所示的简单并行分支。
当涉及到图 2,尤其是图 3 时,它就成了一个问题。
作为一种简单的方法,我们可以引入额外的节点来为其依赖节点收集结果,如图 2b 和 3b 所示,但这现在引入了以前不存在的依赖关系:
这是一个问题,因为在手动审批任务的情况下,这些任务的时间可能是几小时到几天。这将导致后面的步骤被它们不依赖的任务不必要地延迟。
有关如何解决此问题的任何建议?也许我可以采取不同的方法?也许我可以应用一些花哨的图论算法?我什至不知道用什么词来解释图论中的这个问题。
如果需要,这里有一个在 draw.io 上使用这些图表的网址。
我已经使用 FastAI(PyTorch 后端)在 GPU 上训练了一个 CNN 模型。我现在尝试在同一台机器上使用该模型进行推理,但使用 CPU 而不是 GPU。除此之外,我还尝试使用多处理模块来利用多个 CPU 内核。现在问题来了,
在单 CPU 上运行代码(无多处理)只需 40 秒即可处理近 50 张图像
使用 Torch 多处理在多个 CPU 上运行代码需要 6 多分钟才能处理相同的 50 个图像
from torch.multiprocessing import Pool, set_start_method
os.environ['CUDA_VISIBLE_DEVICES']=""
from fastai.vision import *
from fastai.text import *
defaults.device = torch.device('cpu')
def process_image_batch(batch):
learn_cnn = load_learner(scripts_folder, 'cnn_model.pkl')
learn_cnn.model.training = False
learn_cnn.model = learn_cnn.model.eval()
# for image in batch:
# prediction = ... # predicting the image here
# return prediction
if __name__ == '__main__':
#
# …Run Code Online (Sandbox Code Playgroud) 我运行蒙特卡罗模拟并行使用joblib。然而,我注意到虽然我的种子是固定的,但我的结果一直在变化。但是,当我连续运行该过程时,它如我所料保持不变。
下面我实现了一个小例子,模拟具有较高方差的正态分布的均值。
加载库并定义函数
import numpy as np
from joblib import Parallel, delayed
def _estimate_mean():
np.random.seed(0)
x = np.random.normal(0, 2, size=100)
return np.mean(x)
Run Code Online (Sandbox Code Playgroud)
我串联实现的第一个示例- 结果都与预期相同。
tst = [_estimate_mean() for i in range(8)]
In [28]: tst
Out[28]:
[0.11961603106897,
0.11961603106897,
0.11961603106897,
0.11961603106897,
0.11961603106897,
0.11961603106897,
0.11961603106897,
0.11961603106897]
Run Code Online (Sandbox Code Playgroud)
我在 Parallel 中实现的第二个例子:(注意有时手段是一样的,其他时候不一样)
tst = Parallel(n_jobs=-1, backend="threading")(delayed(_estimate_mean)() for i in range(8))
In [26]: tst
Out[26]:
[0.11961603106897,
0.11961603106897,
0.11961603106897,
0.11961603106897,
0.11961603106897,
0.1640259414956747,
-0.11846452111932627,
-0.3935934130918206]
Run Code Online (Sandbox Code Playgroud)
我希望并行运行与固定种子相同。我发现如果我实施RandomState修复种子似乎可以解决问题:
def _estimate_mean():
local_state …Run Code Online (Sandbox Code Playgroud) std::accumulate并std::reduce做几乎相同的事情。
的总结std::reduce说明了一切:
similar to `std::accumulate`, except out of order
Run Code Online (Sandbox Code Playgroud)
在许多情况下,这些函数应该产生相同的最终结果并展示相同的整体功能。很明显,如果您有一些非常重的负载计算等,您可以尝试std::reduce进行parrelization。IE。从鸟类的角度来看,这里的传统智慧是什么 - 除非明确优化,否则您是否应该始终坚持直率的 std::accumulate ?还是应该默认使用std::reduce?
如果std::reduce(选择默认/未选择执行策略)总是至少与std::accumulate(保存一些指令)一样快,那么我认为只有在订单严格时才应使用累积。
这是查找 LCM 和 HCF 之和等于该数字的第一对数字(1 除外)的代码。
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
class PerfectPartition {
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to return LCM of two numbers
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
long[] getPartition(long n) {
var ref = new Object() {
long x;
long y;
long[] ret = null;
};
Thread mainThread = Thread.currentThread();
ThreadGroup t …Run Code Online (Sandbox Code Playgroud) java parallel-processing performance multithreading java-threads
我过去使用过 Joblib 和 Airflow 并且没有遇到过这个问题。我正在尝试通过 Airflow 运行一个使用 Joblib 运行并行计算的作业。当 Airflow 作业启动时,我看到以下警告
UserWarning: Loky-backed parallel loops cannot be called in multiprocessing, setting n_jobs=1
Run Code Online (Sandbox Code Playgroud)
将警告追溯到源头我看到 LokyBackend 类的 joblib 包中触发了以下函数(MultiprocessingBackend 类中也有类似的逻辑)
def effective_n_jobs(self, n_jobs):
"""Determine the number of jobs which are going to run in parallel"""
if n_jobs == 0:
raise ValueError('n_jobs == 0 in Parallel has no meaning')
elif mp is None or n_jobs is None:
# multiprocessing is not available or disabled, fallback
# to sequential mode
return 1
elif mp.current_process().daemon: …Run Code Online (Sandbox Code Playgroud) python ×5
joblib ×2
python-3.x ×2
accumulate ×1
airflow ×1
c++ ×1
c++17 ×1
dask ×1
fast-ai ×1
java ×1
java-threads ×1
numpy ×1
performance ×1
prng ×1
pytorch ×1
r ×1
random-seed ×1
spacy ×1