Thanks for the code. It was really helpful with all those comments.
I’m not sure which pytorch version it was, but on using pytorch 1.0.0, I was getting an error on
_, pred = output.topk(input=maxk, dim=1, largest=True, sorted=True)

So to make it work, I changed it to
_, pred = torch.topk(output, maxk, dim=1, largest=True, sorted=True)