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

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

相关推荐
米小虾6 分钟前
Agent Skill 设计模式完全指南
人工智能·agent
饼干哥哥34 分钟前
保姆级教程:用Image2 + Seedance2.0 做长视频,以品牌广告为例
人工智能
米小虾1 小时前
Agent Skill 规范与 Skill-Creator 核心思想
人工智能·agent
ZhengEnCi1 小时前
09e-斯坦福CS336作业四:大规模语言模型训练数据收集与处理
人工智能
oil欧哟1 小时前
Codex 最佳实践(超级长文):先搞懂 AI,再用好 AI
前端·人工智能·后端
甲维斯2 小时前
日本发布比肩Fable5的模型?Fugu Ultra初探!
人工智能·ai编程
雪隐2 小时前
个人电脑玩AI-04让5060 Ti给你打工——本地FLUX.2 Klein 的 AI 图片生成
人工智能·后端
腾讯云开发者2 小时前
腾讯云TVP走进香港数码港,解码AI出海新范式
人工智能
用户47949283569152 小时前
又当又立: Anthropic 这篇安全白皮书,为什么让人恶心
人工智能
Darling噜啦啦2 小时前
AI Loop 自迭代循环实战:让 AI 自动写文案直到完美——从 Prompt 工程到 Loop 工程
人工智能