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

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

相关推荐
高洁0110 小时前
大模型落地行业第一线
人工智能·数据挖掘·transformer·virtualenv·知识图谱
weixin_3975740910 小时前
AI Agent三层架构设计原理
人工智能·dubbo
机 _ 长10 小时前
YOLO12-Mamba:融合MambaVision思想的目标检测创新实践
人工智能·目标检测·计算机视觉
阿里云大数据AI技术10 小时前
阿里云 ES AI 多模态搜索(百炼)
人工智能
活跃的煤矿打工人10 小时前
【星海出品】大模型微调-Part-One
人工智能·语言模型·gpu算力
coldstarry10 小时前
sheng的学习笔记-AI-xgboost
人工智能·机器学习·boosting
2601_9599862411 小时前
M4Markets:把工具可用性做到位——逻辑梳理与提示整理
大数据·人工智能
程序员小崔日记11 小时前
十年后回头看,2026 年或许是程序员行业的转折点
人工智能·ai编程·claudecode
ZzT11 小时前
给 Claude Code 装个 profiler:每个工具调用慢在哪,瀑布流时间线里一眼看见
人工智能·github·claude