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

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

相关推荐
Clarence Liu39 分钟前
用大白话讲解人工智能(4) Softmax回归:AI如何给选项“打分排序“
人工智能·数据挖掘·回归
教男朋友学大模型1 小时前
Agent效果该怎么评估?
大数据·人工智能·经验分享·面试·求职招聘
hit56实验室1 小时前
AI4Science开源汇总
人工智能
CeshirenTester1 小时前
9B 上端侧:多模态实时对话,难点其实在“流”
开发语言·人工智能·python·prompt·测试用例
Starry_hello world1 小时前
Python (2)
python
relis1 小时前
Tiny-GPU 仿真与静态分析完整指南:Pyslang + Cocotb 实战
人工智能
njsgcs1 小时前
agentscope怎么在对话的时候调用记忆的
人工智能
ID_180079054731 小时前
Python爬取京东商品库存数据与价格监控
jvm·python·oracle
泯泷1 小时前
提示工程的悖论:为什么与 AI 对话比你想象的更难
人工智能·后端·openai
逻极2 小时前
BMAD之落地实施:像CTO一样指挥AI编码 (Phase 4_ Implementation)——必学!BMAD 方法论架构从入门到精通
人工智能·ai·系统架构·ai编程·ai辅助编程·bmad·ai驱动敏捷开发