gpt4 book ai didi

python - 并行运行 Flair 嵌入

转载 作者:行者123 更新时间:2023-12-05 05:35:14 34 4
gpt4 key购买 nike

我有一个列表,其中包含数百万个需要嵌入的句子。我正在使用 Flair以此目的。这个问题似乎应该是并行的。但是,当我尝试优化时,我的性能要么没有提高,要么只是停滞不前。

我将我的句子定义为一个简单的字符串列表:

texts = [
"this is a test",
"to see how well",
"this system works",
"here are alot of words",
"many of them",
"they keep comming",
"many more sentences",
"so many",
"some might even say",
"there are 10 of them",
]

我使用 Flair 创建嵌入:

from flair.embeddings import SentenceTransformerDocumentEmbeddings
from flair.data import Sentence

sentence_embedding = SentenceTransformerDocumentEmbeddings("bert-base-nli-mean-tokens")

def sentence_to_vector(sentence):
sentence_tokens = Sentence(sentence)
sentence_embedding.embed(sentence_tokens)
return sentence_tokens.get_embedding().tolist()

我都试过 Joblib Concurrent Futures并行解决问题:

import time
from joblib import Parallel, delayed
import concurrent.futures

def parallelize(iterable, func):
return Parallel(n_jobs=4, prefer="threads")(delayed(func)(i) for i in iterable)

print("start embedding sequentially")
tic = time.perf_counter()
embeddings = [sentence_to_vector(text) for text in texts]
toc = time.perf_counter()
print(toc - tic)

print("start embedding parallel, w. joblib")
tic = time.perf_counter()
embeddings = parallelize(texts, sentence_to_vector)
toc = time.perf_counter()
print(toc - tic)

print("start embedding parallel w. concurrent.futures")
tic = time.perf_counter()
with concurrent.futures.ProcessPoolExecutor() as executor:
embeddings = [executor.submit(sentence_to_vector, text) for text in texts]
toc = time.perf_counter()
print(toc - tic)

Joblib 函数正在运行,但它比按顺序执行要慢。 concurrent.futures 函数启动了一堆线程,但无限期挂起。

任何正确方向的解决方案或提示将不胜感激。

最佳答案

使用经过训练的模型进行类比 - 似乎经过训练的模型一次只能识别一个项目。

通过复制文件,并运行所有——并行处理应该没有问题例如Prog1.py、prog2.py ... 是相同代码的副本——运行时它们会得到不同的数据来处理。要手动并行运行,请打开多个命令窗口并在每个窗口中运行不同的文件。

要以编程方式运行,主程序可以创建子进程并向每个子进程发送不同的数据。或者批处理文件可以启动程序。例如运行 10 个脚本副本,并将 1/10 的句子发送给每个副本。

然后合并结果。

密切关注 CPU 和内存,以避免机器使用 100 个 CPU。 (随着计算出计算机可以处理多少个并行程序,慢慢增加程序和数据的数量)

关于python - 并行运行 Flair 嵌入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73546129/

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