【问题标题】:How to parallelize running linear regressions on a GPU with pytorch如何使用 pytorch 在 GPU 上并行运行线性回归
【发布时间】:2021-02-26 17:01:44
【问题描述】:

我正在写我的大学毕业论文,我需要计算过去 60 年中每年大约 7000 家公司的所有可能配对之间的均方误差,即我需要进行大量回归。我可用的服务器有多个非常强大的 GPU,所以我在 pytorch 中实现了我的线性回归代码。但是,我在如何优化我的代码以充分利用 GPU 方面并不是很有经验,尤其是如何在 GPU 上并行运行代码。这是遍历公司数据的 for 循环,我将非常感谢任何有关如何对其进行编码以便将作业拆分为最佳大小的建议或提示。

--注意:我知道我在重复计算对,因为 (x,y)=(y,x),我仍然需要弄清楚如何实现这一点。

for index_x,x in enumerate(unique_cusip_list):
    for index_y,y in enumerate(unique_cusip_list):
        
        #FIXME figure out how to not duplicate values 
            
        #FIXME figure out how to run it on the gpu
        
        #setting up the model parameters and inputs
        #------------------------------------------------------------#
        
        
        #adding the corresponding cusip pairs to our list 
        ids_list=[x,y]
        for val in ids_list:
            nested_list_outputs[total_iteration_counter].append(val)
            
        #preparing data
        x_values=nested_list_returns[index_x]
        y_values=nested_list_returns[index_y]
        
        #storing the number of ret variables given
        nested_list_outputs[total_iteration_counter].append(len(x_values))
        nested_list_outputs[total_iteration_counter].append(len(y_values))
        
        
        #if paired data doesnt match in length reduce larger dataset to fit the other
        if len(x_values)<len(y_values):
            y_values=y_values[:len(x_values)]
        if len(x_values)>len(y_values):
            x_values=x_values[:len(y_values)]
        
        #convserion to tensor variables 
        x_values_np=np.array(x_values,dtype=np.float32)
        x_values_np=x_values_np.reshape(-1,1)
        x_values_tensor=Variable(torch.from_numpy(x_values_np))
        
        
        y_values_np=np.array(y_values,dtype=np.float32)
        y_values_np=y_values_np.reshape(-1,1)
        y_values_tensor=Variable(torch.from_numpy(y_values_np))
        
        #move tensors to device
        x_values_tensor=x_values_tensor.to(device)
        y_values_tensor=y_values_tensor.to(device)
        
        if args.print_info:
            print('\n')
            print('Tensor shapes:')
            print(x_values_tensor.size())
            print(y_values_tensor.size())
            
            
            
        #defining the model 
        class LinearRegression(nn.Module):
            def __init__(self,input_size,output_size):
            # super function inherits from nn.Module so that we can access everything from nn.Module
                super(LinearRegression,self).__init__()
            # Linear function
                self.linear = nn.Linear(input_dim,output_dim)

            def forward(self,x):
                return self.linear(x)
        
        
        
        #defining model input and outputs:
        input_dim = 1
        output_dim = 1
        model = LinearRegression(input_dim, output_dim)
        
        #defining loss 
        mse=nn.MSELoss()
        
        #defining optimzation
        learning_rate = 0.01
        optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
        
        loss_list=[]
        
        num_epochs=100
        
        #send model to gpu
        if dev=='cuda:0':
            model.cuda()
        
        #training loop
        #------------------------------------------------------------#      

        for i in range(num_epochs):
            # perform optimization with zero gradient
            optimizer.zero_grad()

            results = model(x_values_tensor)
            loss = mse(results, y_values_tensor)

            # calculate derivative by stepping backward
            loss.backward()

            # Updating parameters
            optimizer.step()

            # store loss
            loss_list.append(loss.data)

            # print loss
            if args.print_info:
                if(i % 10 == 0):
                    print('epoch {}, loss {}'.format(i, loss.data))
            
        
        
        
        #save loss value    
        nested_list_outputs[total_iteration_counter].append(loss.data.item())
        
        
        #incriment loop counter
        total_iteration_counter+=1


end=time.time()
if args.print_outputs:
    for val in nested_list_outputs: 
        print(val)

【问题讨论】:

    标签: python parallel-processing pytorch gpu linear-regression


    【解决方案1】:

    使用 Pytorch,您可以使用 cuda() 模块发送任何计算任务。

    首先您需要使用以下命令将设备设置为 GPU:

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model.to(device)
    
    

    同样你可以使用:

    model.to(torch.device('cuda:0'))
    

    通过这种方式,您可以向 GPU 发送指令。

    【讨论】:

    • 感谢您的回复!我实际上已经这样做了,如果 cuda 可用,我会将所有张量发送到 gpu,并将我的线性模型也发送到 gpu,但问题是,由于每个回归计算的时间都很短,我不认为 gpu 计算正在优化中。
    猜你喜欢
    • 2019-01-06
    • 2022-01-21
    • 2016-04-09
    • 2019-01-11
    • 2017-09-19
    • 2021-10-19
    • 2020-11-14
    • 2021-06-17
    • 2022-10-06
    相关资源
    最近更新 更多