Search code examples
python-3.xpytorchnormal-distribution

RuntimeError: _th_normal not supported on CPUType for Long


I am trying to generate a number from the normal distribution using:

from torch.distributions import Normal
noise = Normal(th.tensor([0]), th.tensor(3.20))
noise = noise.sample()

But I am getting this error: RuntimeError: _th_normal not supported on CPUType for Long


Solution

  • Your first tensor th.tensor([0]) is of torch.Long type due to automatic type inference from passed value while float or FloatTensor is required by function.

    You can solve it by passing 0.0 explicitly like this:

    import torch
    
    noise = torch.distributions.Normal(torch.tensor([0.0]), torch.tensor(3.20))
    noise = noise.sample()
    

    Better yet, drop torch.tensor altogether, in this case Python types will be automatically casted to float if possible, so this is valid as well:

    import torch
    
    noise = torch.distributions.Normal(0, 3.20)
    noise = noise.sample()
    

    And please, do not alias torch as th, it is not official, use fully qualified name as this only confuses everyone.