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

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

相关推荐
_小雨林4 分钟前
(UPDATING)LLM微调之实战,SFTTrainer官方案例、LoRA/QloRA微调案例、Unsloth、分布式训练、LLaMA Factory
人工智能·深度学习
道可云4 分钟前
道可云人工智能&OPC每日资讯|全国首份人工智能开源生态共识在广州发布
人工智能·开源
PyHaVolask8 分钟前
Python 爬虫进阶:直接请求 JSON 接口与开发者工具使用
爬虫·python·请求头·反爬·json接口·chrome开发者工具
larance10 分钟前
安装dify的几个问题
python
2301_7735536213 分钟前
CSS如何对用户访问过的链接进行降级颜色处理_使用-visited伪类改变颜色
jvm·数据库·python
Cosolar19 分钟前
Agent Skills 深度解析:AI 编码代理的工程化生产级工作流引擎
人工智能·面试·开源
2301_8152795220 分钟前
Golang怎么理解Go的sync.Pool底层_Golang如何理解Pool的本地缓存和GC清理机制【详解】
jvm·数据库·python
2301_7641505620 分钟前
MySQL迁移过程如何避免数据不一致_利用强一致性备份方案
jvm·数据库·python
m0_7164300724 分钟前
Redis如何处理预热失效引起的开局雪崩
jvm·数据库·python
m0_3776182326 分钟前
c++文件锁使用方法 c++如何实现多进程文件同步
jvm·数据库·python