title: How to compute the cosine_similarity in pytorch for all rows in a matrix with respect to all rows in another matrix
body: <p>In pytorch, given that I have 2 matrixes how would I compute cosine similarity of all rows in each with all rows in the other.</p>
  
  <p>For example </p>
  
  <p>Given the input =</p>
  
  <pre><code>matrix_1 = [a b] 
             [c d] 
  matrix_2 = [e f] 
             [g h]
  </code></pre>
  
  <p>I would like the output to be </p>
  
  <p>output =</p>
  
  <pre><code> [cosine_sim([a b] [e f])  cosine_sim([a b] [g h])]
   [cosine_sim([c d] [e f])  cosine_sim([c d] [g h])] 
  </code></pre>
  
  <p>At the moment I am using torch.nn.functional.cosine_similarity(matrix_1, matrix_2) which returns the cosine of the row with only that corresponding row in the other matrix. </p>
  
  <p>In my example I have only 2 rows, but I would like a solution which works for many rows. I would even like to handle the case where the number of rows in the each matrix is different. </p>
  
  <p>I realize that I could use the expand, however I want to do it without using such a large memory footprint.</p>