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

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

相关推荐
zmsofts14 小时前
Maven核心能力深度解析:从项目管理到扩展机制
java·python·maven
AI视觉网奇15 小时前
3d部件拆分PartCrafter
人工智能·大模型
Ether IC Verifier15 小时前
CPU/GPU/NPU/DPU功能详解与AI应用分析
网络·人工智能·网络协议·tcp/ip·计算机网络·dpu
2601_9494999415 小时前
芯瑞科技800G VR8 OSFP光模块,解决智算中心高速互连四大难题
人工智能·科技
qq_4523962315 小时前
第十四篇:《JMeter插件扩展:自定义函数与第三方插件》
开发语言·python·jmeter
清风lsq15 小时前
大模型-vllm 投机解码实现
人工智能·vllm·大模型推理
2601_9583529015 小时前
拆解 EN-46:一块 15mA 的 DSP 芯片如何实现 50dB 降噪
人工智能·语音识别·信号处理·嵌入式开发·音频降噪·双麦波束成形·硬件拆解
Mangguo520815 小时前
GPU利用率提升软件横向对比评测:NVIDIA Run:ai、VMware Bitfusion、博云ACE与阿里云PAI灵骏
人工智能·阿里云·云计算
摄影图15 小时前
蓝色光效科技背景图片素材 多场景设计
人工智能·科技·aigc·贴图·插画
m0_7020365315 小时前
mysql如何导出特定条件的查询数据_使用mysqldump加where参数
jvm·数据库·python