一次使用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()#多线程运行。

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

相关推荐
Oxo Security5 分钟前
【AI安全】拆解 OWASP LLM Top 10 攻击架构图
人工智能·安全
Math_teacher_fan7 分钟前
第二篇:核心几何工具类详解
人工智能·算法
yingxiao8888 分钟前
11月海外AI应用市场:“AI轻工具”贡献最大新增;“通用型AI助手”用户留存强劲
人工智能·ai·ai应用
饭饭大王66612 分钟前
卷积神经网络的设计与优化
人工智能·神经网络·cnn
有才不一定有德27 分钟前
解密黑盒:如何追踪 AI 角色的“观点”变化?
人工智能·多智能体系统
晞微27 分钟前
ResNet18 迁移学习实战:CIFAR-10 图像分类与 CPU 优化
人工智能·分类·迁移学习
dhdjjsjs34 分钟前
Day34 PythonStudy
python
java_logo36 分钟前
Onlyoffice Documentserver Docker 容器化部署指南
运维·人工智能·docker·容器·onlyoffice·milvus·documentserver
数据猿38 分钟前
【金猿人物展】涛思数据创始人、CEO陶建辉:实现AI时代时序数据库向“数据平台”的转型
大数据·数据库·人工智能·时序数据库·涛思数据
TMT星球39 分钟前
京东健康联合京东金榜发布2025年度三大品类金榜
人工智能