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

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

相关推荐
yugi9878385 分钟前
PNCC(Power-Normalized Cepstral Coefficients)— MATLAB 实现
开发语言·人工智能·matlab
AI棒棒牛7 分钟前
第 03 讲《监督学习:数据、标签、Loss与训练循环》
人工智能·学习·yolo·目标检测·yolo26
甲维斯7 分钟前
GLM5.2超过Opus4.8Think,全球第二了!
前端·人工智能·ai编程
你是个什么橙9 分钟前
Python入门学习2:Python 基础语法全解析——从代码结构到输入输出
开发语言·python·学习
小白学大数据12 分钟前
Python + 大模型行业资讯自动化摘要流水线完整工程实现方案
开发语言·python·自动化
宝贝儿好12 分钟前
【LLM】第二章:HuggingFace入门学习
人工智能·深度学习·神经网络·学习·算法·自然语言处理
早点睡啊13 分钟前
详解Loop Engineering,AI 编程从提示词走向循环系统
人工智能
我是小bā吖14 分钟前
Claude Code 模型接入阿里云 AI 网关并统计不同使用者的模型用量
网络·人工智能·阿里云
天风之翼14 分钟前
AI 全栈开发实战(9):用户设置与 API Key 管理——账号安全与用量统计
人工智能
小撒的私房菜19 分钟前
Multi-Agent 里谁来指挥?我用一个调度员,让多个 Agent 开始协作
人工智能·后端·agent