The error is raised, if the k value is larger than the size of the specified dimension as seen here:
output = torch.randn(3, 2)

maxk = 1
_, pred = output.topk(maxk, 1, True, True) # works

maxk = 2
_, pred = output.topk(maxk, 1, True, True) # works

maxk = 3
_, pred = output.topk(maxk, 1, True, True) # fails
> RuntimeError: selected index k out of range

so you would have to check output.shape and make sure dim1 is larger or equal to maxk.