Check if the expected object is of backend CUDA or CPU?

  
  I am trying to run a code on both CPU and CUDA.
  The problem arise when I create objects, as I need to know what's expected.
  


I need to determine if the computer is expecting a CUDA or CPU tensor, before it is created.

Code:

def initilize(self, input):
     self.x = torch.nn.Parameter(torch.zeros((1,M))

def run(self,x,state):
  B = torch.cat((self.x,h)


This outputs:

Error: 'Expected object of backend CUDA but got backend CPU for argument #1'


Code idea:

def initilize(self, input):
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  if (expecting_cuda == True):
     self.x = torch.nn.Parameter(torch.zeros((1,M)).to(device))
  else
     self.x = torch.nn.Parameter(torch.zeros((1,M))

def run(self,h):
  B = torch.cat((self.x,h)



Question:
How to figure out what the computer expects?
Limitations:
I am running on a pre-defined "check" procedure, so I can not send an argument into the function 'initilize' with information about CUDA or CPU.


You can just use self.x = torch.nn.Parameter(torch.zeros((1,M)).to(device)), no need for if (expecting_cuda == True): because to(device) will also work for cpu.
