一次使用threading.Thread来实现Pytorch多个模型并发运行的失败案例

文章目录

背景

我有多个pytorch GPU模型,他们有不同的参数(也就是说不是共享的),但是相同的数据输入,想要并发运行。

不并发运行,当然就是循环喽。

复制代码
        for i in range(self.args.m):
            self.models[i](batch)

我想要并发,因为m有点大。像上面循环的话m=30以上速度就有点受不了了。我看过了,我的GPU还有很多空间,起码放上去10个模型没有问题。

我的做法(但证明不起效果)

我想到了多线程,如下:

复制代码
class MyThread_forward(threading.Thread):  #自定义线程类
    def __init__(self, model,batch):
        threading.Thread.__init__(self)
        self.model = model              
        self.batch=batch
    def run(self):                    
        self.result=self.model(self.batch) 
    def get_result(self): 
        return self.result

def multi_thread_forward():
    threads=[]
    for  i in range(self.args.m):#创建多个线程
        threads.append(MyThread_forward(self.models[i],batch))
    for thread in threads:#各个线程开始并发运行。
        thread.start()
    for thread in threads:#等待各个线程运行完毕再执行下面代码。
        thread.join()    
    results= []
    for thread in threads:
    	results.append(thread.get_result())  #每个线程返回结果(result)加入列表中
    return results
    
multi_thread_forward()#多线程运行。

结果就是不起效果好像,还是运行得很慢,咋回事捏。

相关推荐
Bruce_Liuxiaowei10 分钟前
使用Python脚本在Mac上彻底清除Chrome浏览历史:开发实战与隐私保护指南
chrome·python·macos
vocal16 分钟前
谷歌第七版Prompt Engineering—第一部分
人工智能
MonkeyKing_sunyuhua17 分钟前
5.6 Microsoft Semantic Kernel:专注于将LLM集成到现有应用中的框架
人工智能·microsoft·agent
ruyingcai66666622 分钟前
用python进行OCR识别
开发语言·python·ocr
arbboter25 分钟前
【AI插件开发】Notepad++ AI插件开发1.0发布和使用说明
人工智能·大模型·notepad++·ai助手·ai插件·aicoder·notepad++插件开发
Niuguangshuo25 分钟前
Python设计模式:MVC模式
python·设计模式·mvc
TOMGRIL29 分钟前
文件的读取操作
python
liuweidong080232 分钟前
【Pandas】pandas DataFrame radd
开发语言·python·pandas
IT_Octopus37 分钟前
AI工程pytorch小白TorchServe部署模型服务
人工智能·pytorch·python
果冻人工智能42 分钟前
AI军备竞赛:我们是不是正在造一个无法控制的神?
人工智能