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

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

相关推荐
猫猫与橙子3 分钟前
记录使用AI工具来完成中文形近字识别
人工智能
Eric.Lee202120 分钟前
机器人:sim2real 技术必要性
人工智能·深度学习·机器人·机器人仿真·mujoco·sim2real
江上鹤.14821 分钟前
Day 49 预训练模型
人工智能·深度学习·机器学习
zuozewei22 分钟前
7D-AI系列:Transformer 与深度学习核心概念
人工智能·深度学习·transformer
技术路上的探险家35 分钟前
vLLM常用启动参数的详细解释
python·大模型·qwen·vllm
WHJ22641 分钟前
记录解决jupyter打开闪退
ide·python·jupyter
老歌老听老掉牙41 分钟前
1V1砂轮轮廓的几何建模与可视化分析
python·sympy·砂轮
乐迪信息1 小时前
乐迪信息:异物入侵识别算法上线,AI摄像机保障智慧煤矿生产稳定
大数据·运维·人工智能·物联网·安全
浔川python社1 小时前
浔川社团关于福利发放方案再次调整的征求意见稿公告
python
CareyWYR1 小时前
每周AI论文速递(251222-251226)
人工智能