Construct new tensor on correct device based on input
ypxie
apaszke
Hi! I’m sorry to reply to an old post but I thought replying here would be better than starting a new topic. <SCODE>device = 1
X = torch.rand(10).cuda(device)  # or X = torch.rand(10)
<ECODE> How to make code below agnostic to whether X is on CPU/GPU and which device? <SCODE># Fill with numpy data
data = np.array([1, 2, 3])  # For example indices calculated by custom Python procedure
X.new().long().new(data)  # Works on CPU, error on GPU?
X.new().long().new(*data.shape).copy_(torch.from_numpy(data))  # Works but verbose
X.new(data.astype(float)).long()  # Inefficient, lossy?
# X.new(data)  # Error

# Or fill with zeros
X.new(10).long().zero_()  # Works, but inefficient?
X.new().long().new(10).zero_()  # Works, but verbose?<ECODE>
wouter
smth
wouter
What is the new alternative for this use case?
bgobbi
shlomia
This creates very ugly (and slow) code such as <SCODE>    if std.is_cuda:
        eps = torch.FloatTensor(std.size()).cuda().normal_()
    else:
        eps = torch.FloatTensor(std.size()).normal_()
<ECODE> Isn’t there a better way?
Noam_Salomonski
Noam_Salomonski