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

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

相关推荐
dunge202623 分钟前
2026年7月最新ChatGPT Plus / Pro 与 Codex:当 AI Agent 最新5.6版本来袭,必须理解事务、幂等与补偿
开发语言·人工智能·python
研究员子楚24 分钟前
GEO行业发展标准体系白皮书V2.0-第10卷 · 全球篇:跨国标准协同与全球品牌语义治理框架
数据库·人工智能·microsoft·架构·geo
这张生成的图像能检测吗1 小时前
(论文速读)CLUSTER-GCN:一种训练深度和大图卷积网络的有效算法
人工智能·深度学习·图神经网络·聚类算法
Omics Pro1 小时前
深度学习多组学互作:组内+组间
数据库·人工智能·深度学习·mysql·搜索引擎·自然语言处理
txg6662 小时前
机器人领域简报(2026年7月9日—16日)
人工智能·深度学习·机器人
学习编程之路2 小时前
Cursor × 蓝耘 MaaS 代码注释工具
人工智能
小小测试开发2 小时前
Promptfoo 源码级解析:LLM 评估框架的核心设计与 CI/CD 集成实践
人工智能·ci/cd
凌虚2 小时前
AI 时代,程序员会消失吗?
人工智能·后端·程序员
阿里云大数据AI技术2 小时前
Hologres 4.2新特性 Liquid Table:让 Shard 数不再是建表时的一锤定音
人工智能