Do make sure the dataloader in def train() and the one in main are indeed the same. The behaviour of the code,  batch_idx, (inputs, targets) in enumerate(trainloader): will not change inside a function provided there is no modification to the trainloader. Alternatively, you can use next(iter(data_loader)) to obtain a batch of the dataloader without manual iteration using a for loop.