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

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

相关推荐
浅墨cgz1 分钟前
查找并删除源目录中与目标目录重复的文件
python
AI程序员7 分钟前
Code Agent 的上下文压缩:不是 zip,而是工作记忆管理
人工智能
AI程序员8 分钟前
OpenAI Frontier 到底是什么:企业 Agent 不只是需要一个更强的模型
人工智能
爱喝白开水a10 分钟前
春节后普通程序员如何“丝滑”跨行AI:不啃算法,也能拿走AI
java·人工智能·算法·spring·ai·前端框架·大模型
云姜.14 分钟前
YAML简单使用
python
两万五千个小时19 分钟前
解析 OpenClaw AgentSkills:AI Agent 如何通过「技能包」实现专业化
人工智能·程序员·代码规范
喵手19 分钟前
Python爬虫实战:手把手教你Python 自动化构建志愿服务岗位结构化数据库!
爬虫·python·自动化·数据采集·爬虫实战·零基础python爬虫教学·志愿服务岗位结构数据库打造
热点速递22 分钟前
美团2025年“翻车”实录:从盈利王者到赤字领跑!
人工智能·业界资讯
chushiyunen25 分钟前
python numpy包的使用
开发语言·python·numpy
小邓睡不饱耶25 分钟前
Python多线程爬虫实战:爬取论坛帖子及评论
开发语言·爬虫·python