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

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

相关推荐
盟接之桥1 天前
AI助手:你的7×24小时智能管家——让异常预警无处不在
大数据·网络·数据库·人工智能·制造·ai编程
llqbzllll1 天前
Agent Skills 为什么不能只是“长提示词”:SKILL.md、按需加载和权限边界
人工智能
苦瓜打怪兽1 天前
leetcode 热题100(11. 盛最多水的容器)
python·算法·leetcode
砚底藏山河1 天前
量化实战:回测数据底座快照与版本管理进阶
java·大数据·python·金融·maven
“AI国潮设计-小江”1 天前
《Python+SDXL实战:用ControlNet批量生成“英歌舞麻将糕”IP,附自动化脚本与商用思路》
开发语言·人工智能·python·prompt·aigc
具身AGI1 天前
从Demo到货架,全栈自研 物理AI 的验收标准
人工智能
熊猫钓鱼>_>1 天前
越顺,越空:当 AI 把学习 “优化“ 到消失
人工智能·学习·ai·llm·agent·ai编程·metaai
2601_956743681 天前
上海GEO优化公司名单(2026年10月更新):GEO是什么业务、上海主流服务商盘点与选型避坑指南
大数据·人工智能·技术分享·geo·上海
倔强的石头1061 天前
Qwen系列解析_阿里巴巴大模型技术路线
人工智能·大模型
liuchangng1 天前
类Jev项目Kev从入门到实战(6):Jev / Kev / Laya 对比
人工智能·jev·kev