一次使用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画面不廉价:质感的三层来源详解
人工智能
秦先生在广东11 分钟前
Agentic Awesome Skills 解析:构建本地优先的 Agent 技能控制平面
人工智能
径硕科技JINGdigital16 分钟前
企业搭建 AI 模型网关,该选择哪些支持多模型接入与统一治理的平台?
人工智能
甲维斯18 分钟前
国产Flash大乱斗【1】:DS和MiniMax挺起胸膛!
人工智能
阿里云大数据AI技术22 分钟前
StarRocks × Paimon C++:加速湖上数据分析
大数据·人工智能
秦先生在广东27 分钟前
多智能体统一架构:拆解 wshobson/agents 的跨工具插件适配机制
人工智能
秦先生在广东33 分钟前
Graphify:基于本地确定性 AST 解析的代码知识图谱探索
人工智能
学Linux的语莫1 小时前
python中类的常见写法
开发语言·python·状态模式
阿里云大数据AI技术1 小时前
【云栖实录】一切数据,皆可计算:MaxCompute 升级为AI Native全模态计算服务
大数据·人工智能·agent
面壁的熊猫1 小时前
agent-team 与 Multica 差异分析,以及 2026 年多 Agent 编码编排最新相关工作
人工智能·开源项目·ai agent