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

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

相关推荐
zhanghaha13146 小时前
Python语言基础:4_数据类型转换
java·前端·python
码农学院7 小时前
跨平台AI搜索优化的统一策略与引擎差异适配方法
人工智能
赫文派7 小时前
K3 与 Kimi Code 实战:模型到终端 Agent
人工智能·ai编程
larance7 小时前
机器学习特征预处理之标准化/归一化
开发语言·python·机器学习
z12345677797 小时前
2026年企业AI办公工具深度评测:钉钉悟空平替横向选型指南
人工智能·钉钉
tokenova7 小时前
Python 多模型统一调用封装类,一套代码兼容 GPT/Claude/Grok
python
网易云信7 小时前
网易智企入选《2026人工智能发展白皮书》,帝王蟹引领“智能增效”场景
人工智能·agent
老兵发新帖7 小时前
Transformer最新小样本学习能力分析
人工智能
阿虎儿7 小时前
Dify Failed to invoke tool: Aborted: Maximum execution steps exceeded: 501 > 500
人工智能
后端小肥肠7 小时前
用它做的第一条视频自然流就是投流的 3 倍,我做了个抖音全栈运营 Skill
人工智能·aigc·agent