Pytorch why is .float() needed here for RuntimeError: expected scalar type Float but found Double

Simple question, i wanted to experiment with the simplest possible network, but i kept running into RuntimeError: expected scalar type Float but found Double unless i casted data into .float() (see below code with comment)

What i dont understand is, why is this casting needed? data is already a torch.float64 type. Whys the explicit re-casting in the output = model(data.float()) line needed?


from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from sklearn.datasets import make_classification
from import TensorDataset, DataLoader

# =============================================================================
# Simplest Example
# =============================================================================
X, y = make_classification()
X, y = torch.tensor(X), torch.tensor(y)
print("X Shape :{}".format(X.shape))
print("y Shape :{}".format(y.shape))

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(X.shape[1], 128)
        self.fc2 = nn.Linear(128, 10)
        self.fc3 = nn.Linear(10, 2)

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x
device = torch.device("cuda") 
lr = 1
batch_size = 32
gamma = 0.7
epochs = 14
args = {'log_interval': 10, 'dry_run':False}

kwargs = {'batch_size': batch_size}
kwargs.update({'num_workers': 1,
               'pin_memory': True,
               'shuffle': True},

model = Net().to(device)
optimizer = optim.Adam(model.parameters(), lr=lr)
scheduler = StepLR(optimizer, step_size=1, gamma=gamma)

my_dataset = TensorDataset(X,y) # create dataset
train_loader = DataLoader(my_dataset,**kwargs) #generate dataloader

cross_entropy_loss = torch.nn.CrossEntropyLoss()

for epoch in range(1, epochs + 1):
    ## Train step ##
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target =,
        output = model(data.float()) #HERE: why is .float() needed here?
        loss = cross_entropy_loss(output, target)
        if batch_idx % args['log_interval'] == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))
            if args['dry_run']:



This happens because the data in your dataset are double.
Which I guess happens because you load them from numpy which store floating point numbers in double by default most of the time.
Another alternative to save memory is to do X, y = torch.tensor(X).float(), torch.tensor(y)

1 Like