snake-ai-pytorch icon indicating copy to clipboard operation
snake-ai-pytorch copied to clipboard

cpu to gpu

Open onepointfuck opened this issue 3 years ago • 11 comments

It has been implemented with cpu, I want to implement this project with gpu, how should I do it, please advise

onepointfuck avatar Feb 05 '22 11:02 onepointfuck

+1

AchalS-iglu avatar May 16 '22 13:05 AchalS-iglu

You might like to take a look at this... https://towardsdatascience.com/pytorch-switching-to-the-gpu-a7c0b21e8a99

arch-user-france1 avatar Jul 08 '22 12:07 arch-user-france1

All you have to do is in the agent.py place the following code right after the model init:

model.to('cuda:0')

ethicalhacker7192 avatar Dec 13 '23 01:12 ethicalhacker7192

Alright I figured out the solution.

Changes to agent.py

Add the below right after line "self.model..." self.model.to('cuda:0')

Modify def get_action, in the else (add .to('cuda:0') state0 = torch.tensor(state, dtype=torch.float).to('cuda:0')

Changes to model.py...

"import numpy as np"

add the below just after line "self.model = model" self.model = model.to('cuda:0')

def train_setup needs to have these changes.

def train_step(self, states, actions, rewards, next_states, dones):
    states = torch.tensor(np.array(states), dtype=torch.float).to('cuda:0')
    actions = torch.tensor(np.array(actions), dtype=torch.long).to('cuda:0')
    rewards = torch.tensor(np.array(rewards), dtype=torch.float).to('cuda:0')
    next_states = torch.tensor(np.array(next_states), dtype=torch.float).to('cuda:0')

    if len(states.shape) == 1:
        states = torch.unsqueeze(states, 0)
        actions = torch.unsqueeze(actions, 0)
        rewards = torch.unsqueeze(rewards, 0)
        next_states = torch.unsqueeze(next_states, 0)
        dones = (dones,)

dookiethedog avatar Jan 01 '24 01:01 dookiethedog

Yay!

ethicalhacker7192 avatar Jan 06 '24 17:01 ethicalhacker7192

Or you can do for agent.py:

Action = self.model(state0.to('cuda:0'))

ethicalhacker7192 avatar Jan 06 '24 17:01 ethicalhacker7192

Hi guys, thx for the help i did it and it works, BUT on my PC with AMD 7950X3D and Nvidia 4090 cpu device performance is actually faster than cuda, why is that? In both cases are devices utilized 100%, thx

PayteR avatar Jul 10 '24 15:07 PayteR

Sometimes GPUs are meant for graphics strictly, which may hinder them in terms of multiprocessing and calculating each action the neurons will take, it is a fairly uncommon issue.

ethicalhacker7192 avatar Jul 11 '24 05:07 ethicalhacker7192

Yea, but that's THE best PC GPU right now although CPU is top too. Any other cases to process AI is like 100-1000x faster with GPU, for example LLM inferences. Im still think that there is some issue in the code.

PayteR avatar Jul 11 '24 07:07 PayteR