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

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

相关推荐
@HNUSTer15 分钟前
基于 Visual Studio Code 配置 Python 开发环境详细教程
ide·vscode·python·csdn开发云
星爷AG I41 分钟前
14-2 个体、任务与环境(AGI基础理论)
人工智能·agi
tuotali202642 分钟前
天然气压缩机技术2026,高可靠性长周期运行与智能运维融合路径
运维·python
飞Link44 分钟前
深度解析 LSTM 神经网络架构与实战指南
人工智能·深度学习·神经网络·lstm
前端不太难1 小时前
AI 时代,鸿蒙 App 还需要传统导航结构吗?
人工智能·状态模式·harmonyos
格林威1 小时前
工业相机图像高速存储(C#版):内存映射文件方法,附Basler相机C#实战代码!
开发语言·人工智能·数码相机·c#·机器视觉·工业相机·堡盟相机
geneculture1 小时前
AGI Maths融智学AGI数学模型
人工智能·融智学的重要应用·哲学与科学统一性·信息融智学·融智时代(杂志)·agi maths.
Ama_tor1 小时前
Flask零基础进阶(中)
后端·python·flask
OpenMMLab1 小时前
Agent范式转移:组织、协作与商业的重构
人工智能·大模型·多模态大模型·智能体·openclaw