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

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

相关推荐
ZHW_AI课题组几秒前
调用阿里云API实现运营商实名认证
python·阿里云·云计算·api
Baihai_IDP2 分钟前
「DeepSeek-V3 技术解析」:无辅助损失函数的负载均衡
人工智能·llm·deepseek
闲人编程3 分钟前
图像插值算法(最近邻/双线性/立方卷积)
python·opencv·图像识别
硅谷秋水8 分钟前
大语言模型智体的综述:方法论、应用和挑战(下)
人工智能·深度学习·机器学习·语言模型·自然语言处理
TGITCIC12 分钟前
BERT与Transformer到底选哪个-下部
人工智能·gpt·大模型·aigc·bert·transformer
Lx35213 分钟前
AutoML逆袭:普通开发者如何玩转大模型调参
人工智能
IT古董15 分钟前
【漫话机器学习系列】185.神经网络参数的标准初始化(Normalized Initialization of Neural Network Parameter
人工智能
嘻嘻哈哈开森17 分钟前
Java开发工程师转AI工程师
人工智能·后端
rocksun18 分钟前
Agentic AI和平台工程:如何结合
人工智能·devops
孔令飞28 分钟前
关于 LLMOPS 的一些粗浅思考
人工智能·云原生·go