title: Faster way to do multiple embeddings in PyTorch?
body: <p>I'm working on a <a href="https://github.com/AlliedToasters/dfencoder" rel="noreferrer">torch-based library</a> for building autoencoders with tabular datasets.</p>
  
  <p>One big feature is learning embeddings for categorical features. </p>
  
  <p>In practice, however, training many embedding layers simultaneously is creating some slowdowns. I am using for-loops to do this and running the for-loop on each iteration is (I think) what's causing the slowdowns.</p>
  
  <p>When building the model, I associate embedding layers with each categorical feature in the user's dataset:</p>
  
  <pre><code>        for ft in self.categorical_fts:
              feature = self.categorical_fts[ft]
              n_cats = len(feature['cats']) + 1
              embed_dim = compute_embedding_size(n_cats)
              embed_layer = torch.nn.Embedding(n_cats, embed_dim)
              feature['embedding'] = embed_layer
  
  </code></pre>
  
  <p>Then, with a call to .forward():</p>
  
  <pre><code>        embeddings = []
          for i, ft in enumerate(self.categorical_fts):
              feature = self.categorical_fts[ft]
              emb = feature['embedding'](codes[i])
              embeddings.append(emb)
  
          #num and bin are numeric and binary features
          x = torch.cat(num + bin + embeddings, dim=1)
  </code></pre>
  
  <p>Then <code>x</code> goes into dense layers.</p>
  
  <p>This gets the job done but running this for loop during each forward pass really slows down training, especially when a dataset has tens or hundreds of categorical columns. </p>
  
  <p>Does anybody know of a way of vectorizing something like this? Thanks!</p>
  
  <p>UPDATE:
  For more clarity, I made this sketch of how I'm feeding categorical features into the network. You can see that each categorical column has its own embedding matrix, while numeric features are concatenated directly to their output before being passed into the feed-forward network.</p>
  
  <p><a href="https://i.stack.imgur.com/xxCPi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xxCPi.png" alt="diagram"></a></p>
  
  <p>Can we do this without iterating through each embedding matrix?</p>