What and why use inputs (image tensors).cpu().data[j]?

Why we need to firstly convert inputs tensors to cpu, and then get tensor values by calling data()?
What is the data attribute used for and what will it return? If I call this visualize_model on GPU, do I need to convert to cpu tensors, or I can directly imshow(inputs.data[j])?

Can anyone help explain please? Thanks in advance!!

def visualize_model(model, num_images=6):
    was_training = model.training
    model.eval()
    images_so_far = 0
    fig = plt.figure()

    with torch.no_grad():
        for i, (inputs, labels) in enumerate(dataloaders['val']):
            inputs = inputs.to(device)
            labels = labels.to(device)

            outputs = model(inputs)
            _, preds = torch.max(outputs, 1)

            for j in range(inputs.size()[0]):
                images_so_far += 1
                ax = plt.subplot(num_images//2, 2, images_so_far)
                ax.axis('off')
                ax.set_title('predicted: {}'.format(class_names[preds[j]]))
                imshow(inputs.cpu().data[j])

                if images_so_far == num_images:
                    model.train(mode=was_training)
                    return
        model.train(mode=was_training)
  1. pyplot doesn’t support the functions on GPU.
    This is why you should copy the tensor by .cpu().
  2. As I know, .data is deprecated. You don’t need to use that. But pyplot doesn’t support the plot function with torch.Tensor so it looks good to convert the tensor into numpy array by .numpy().
  3. You can directly use imshow(input.cpu().numpy())