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

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

相关推荐
Henry-SAP12 小时前
AI与机器人信息新闻
人工智能·云原生·sap·erp
天远数科12 小时前
零信任架构实战:基于天远二手车VIN估值构建自动化汽车数据网关
人工智能·架构·自动化·汽车
AI码农小姐姐12 小时前
小说导入AI漫剧赚钱教程:知漫剧批量生成与选型
人工智能
hh95012 小时前
Agent Plan x DeepSeek Harness — Token 预算管理与成本追踪体系技术
人工智能·学习·adg·火山引擎·adg成都社区
梦想的旅途212 小时前
Python实现企业微信文本消息发送
开发语言·python·企业微信
水獭比特12 小时前
工具都批准了,为什么还不能执行?给 Agent 补上第二道校验
javascript·人工智能·node.js
%4712 小时前
DAY41
pytorch·python
小小帅呀12 小时前
学习 VLA 第 2 天:深度学习基础
人工智能·深度学习·学习
科技小E12 小时前
国标GB28181视频平台EasyGBS监控为什么会“瞎”:视频质量诊断EasyVQD如何揪出黑屏卡顿偏色
大数据·人工智能·音视频
敲代码还房贷12 小时前
VMware17 + Ubuntu22.04 共享 完整步骤
linux·python·ubuntu