I have done it before. Dice loss can be coded without defining any custom function. I did it both ways, defining custom function and also using nn.Module to check both gave same results. Please check your code and follow the guidelines on how to define custom function, it varies slightly based on which version of PyTorch you are using.