python - 并行运行 Flair 嵌入

标签 python multithreading parallel-processing nlp flair

我有一个列表,其中包含数百万个需要嵌入的句子。我正在使用 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/

相关文章:

r - 并行 R 中每个子进程的唯一名称

python - 在 python NLTK 中平滑

python - 在数据框列的列表列表中查找列表的出现

python - Scrapy 扩展 : spider_closed is not called

wait()可以代替sleep()或delay()吗?

java - 修复了线程池线程阻塞,当提交了足够多的任务时

python - 检查哪些ObjectID是在ray中完成的

python - 获取已排序的 numpy 矩阵或 pandas 数据帧的最后一个非 nan 索引

C++工作队列与阻塞

c++ - 如何让 MPI_Send 让处理器按顺序发送而不是随机发送?