The above math should map nicely into pytorch operations. i.e. you’ll be able to use tensor.norm, tensor.log, and tensor.sum(dim) that should simplify your code.
I’m curious how you’re running into those errors though.