Hi Patrick
Yes, it indeed works when I rewrite the code with if protection in the following way. Thanks!
My question is why the issue occurs only when I use the customized loader in the ‘datasetfolder’. If I use the ImageFolders with the default loader, this is no dead loop  even without the ‘if’ protection.

# coding: utf-8

# In[ ]:


from __future__ import print_function, division

import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
from sklearn.utils.class_weight import compute_class_weight
import matplotlib.pyplot as plt
import torch.nn.functional as F
import time
import os
import copy
import sys
from torchvision.datasets import ImageFolder

plt.ion()


# In[ ]:


def my_loader(path):
    from torchvision import get_image_backend
    from PIL import Image
    
                
    def my_pil_loader(path):
        print ("loading {}".format(path))
        try:
            with open(path, 'rb') as f:
                img = Image.open(f)
                return img.convert('RGB')
        except:
            print('fail to load {} using PIL'.format(img))

    if get_image_backend() == 'accimage':
        print('loading {} uses accimage'.format(path))
        try:
            return accimage_loader(path)
        except IOError:
            print('fail to load {} using accimage, instead using PIL'.format(path))
            return my_pil_loader(path)
    else:
        print('{} uses PIL'.format(path))
        return my_pil_loader(path)


# In[ ]:


def main():
    data_transforms = transforms.Compose([transforms.Resize(300),
            transforms.CenterCrop(299),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
    
    img_extensions = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.gif', '.octet-stream']
    
    data_dir = './debug/'
    batch_size = 32

    image_datasets = datasets.DatasetFolder(data_dir, my_loader, img_extensions,
                                              data_transforms)
    dataloaders = torch.utils.data.DataLoader(image_datasets, batch_size=batch_size, shuffle=True, num_workers=4)
    
    index = 0
    for inputs, labels in dataloaders:
        print(index)
        print('inputs')
        print(inputs.size())
        print('labels')
        print(labels.size())


# In[ ]:


if __name__ == '__main__':
    main()