Solved by KFrank in post #2 
              
              
                Hi Bin! 

I think, in general, if your g() is built from a broadcastable operation 
and a reduction operation, you can accomplish your goal with pytorch 
broadcasting. 

In your specific case, you can use unsqueeze() in the appropriate 
locations to replace the nested loops with  broadcasting, and t…