PyTorch Generating Matrix using a Kernel Function without For-Loops
I am trying to generate a matrix (tensor object on PyTorch) that is similar to Gram matrix except I need to apply a kernel function instead of inner product on my input matrix.
For loops like the one below works:
N = x.shape[0] # x.shape = (N,d)
G = torch.zeros((N,N)) 
for i in range(N):
    for j in range(N):
        G[i][j] = K(x[i], x[j])

where x is my input tensor whose shape is (N,d) and the kernel function K(a,b) yields a real value after performing some math. For example:
def K(a,b):
   return ((1+(a*b)).sum()).pow(2) #second degree polynomial.

I want to generate this matrix, G without having to change the kernel function K() and of course, without for-loops!
My initial attempt is to use a lambda approach but this code below obviously doesn't work as it only yields a list of k(x[i],x[i]).
G = torch.tensor(list(map(lambda a,b: K(a,b),x,x))

How can I use the lambda function to yield N-by-N matrix?
What would be some other ways to tackle this problem?
Any insight would be appreciated.

You can calculate G from x simply with:
G = (1 + torch.matmul(x, x.T)).pow(2)

