How does nn.Embedding work?

lisyuan: <p>I am new in the NLP field am I have some question about <code>nn.Embedding</code>. I have already seen this <a href="https://discuss.pytorch.org/t/what-is-nn-embedding-exactly-doing/12521">post</a>, but I’m still confusing with how <code>nn.Embedding</code> generate the vector representation. From the official website and the answer in this <a href="https://discuss.pytorch.org/t/what-is-nn-embedding-exactly-doing/12521">post</a>. I concluded:</p>
<ol>
<li>It’s only a lookup table, given the index, it will return the corresponding vector.</li>
<li>The vector representation indicated the weighted matrix is initialized as random values and will be updated by backpropagation.</li>
</ol>
<p>Now my question are:</p>
<ol>
<li>If I have 1000 words, using <code>nn.Embedding(1000, 30)</code> to make 30 dimension vectors of each word. Will <code>nn.Embedding</code> generate one-hot vector of each word and create a hidden layer of 30 neuron like word2vec? If so, is it CBOW or Skip-Gram model? What’s the difference between <code>nn.Embedding</code> and <code>nn.Linear</code>
</li>
<li>Now, I am researching about the Visual-Question-Answering tasks. Any suggestion about using pretrain vector representation, e.g. word2vec, in question vocabulary or not using it?</li>
</ol>

qmeeus: <ol>
<li>It’s neither CBOW nor Skip-Gram, which are models trained end-to-end to predict the context given the word, or the word given the context. Here, <code>nn.Embedding</code> is optimized as part of your training task. Consequently, after training, you can expect to have embeddings that are specific to your task rather than generic embeddings that generate a more general representation which can be more or less useful depending on your task. To illustrate, you can imagine having a screwdriver that works on some screws but if your screw is very specific, then you will need to change your tool for your specific task.</li>
<li>Using pretrained vectors is generally a good starting point but you should consider retraining/fine-tuning the vectors for your specific task</li>
</ol>
<p>[EDIT]: difference between Embedding and Linear: Linear expects vectors (e.g. one-hot representation of the words), Embedding expects tokens (e.g. words index)</p>

vdw: <p>An Embedding layer is essentially just a Linear layer. So you could define a your layer as <code>nn.Linear(1000, 30)</code>, and represent each word as a one-hot vector, e.g., <code>[0,0,1,0,...,0]</code> (the length of the vector is 1,000).</p>
<p>As you can see, any word is a unique vector of size 1,000 with a 1 in a unique position, compared to all other words. Now giving such a vector <code>v</code> with <code>v[2]=1</code> (cf. example vector above) to the Linear layer gives you simply the 2nd row of that layer.</p>
<p><code>nn.Embedding</code> just simplifies this. Instead of giving it a big one-hot vector, you just give it an index. This index basically is the same as the position of the single 1 in the one-hot vector.</p>

lisyuan: <p>You explain very clearly! The last question: is the <code>nn.Embedding</code> do the same thing like <code>nn.Linear</code>? But <code>nn.Linear</code> should input a vector representation (e.g, using one-hot) so it can build a look-up table. The <code>nn.Embedding</code> do the same thing but simplified it just using word-index. Let me know if I misunderstand any part. Also, is there any document can be refered? I have searched for a long while!</p>

vdw: <p>It seems you want to implement the CBOW setup of Word2Vec. You can easily find PyTorch implementations for that. For example, I found <a href="https://gist.github.com/GavinXing/9954ea846072e115bb07d9758892382c" rel="nofollow noopener">this implementation</a> in 10 seconds :).</p>
<p>This example uses <code>nn.Embedding</code> so the <code>inputs</code> of the <code>forward()</code> method is a list of word indexes (the implementation doesn’t seem to use batches). But yes, instead of <code>nn.Embedding</code> you could use <code>nn.Linear</code>. The only change needed would be that <code>inputs</code> not has to be a list of one-hot vectors. But I wouldn’t bother, <code>nn.Embedding</code> keeps things simpler.</p>

lisyuan: <p>No, I don’t want to implement CBOW. I just want to know the corresponding architecture matching  with <code>nn.Embedding</code> and if I understand it right or not. So, it looks like the <code>nn.Embedding</code> is equal to the red square part in the picture.</p>

vdw: <p>‘nn.Embedding’ is no architecture, it’s a simple layer at best. In fact, it’s a linear layer just with a specific use.</p>
<p>Internally, <code>nn.Embedding</code> is – like a linear layer – a M x N matrix, with M being the number of words and N being the size of each word vector. There’s nothing more to it. It just matches a word (specified by an index) to the corresponding word vector, i.e., the corresponding row in the matrix.</p>

John_Grabner: <p>Does PyTorch treat backpropagation of (1-hot input to linear layer) the same as (index selection of embedding)?</p>
<p>I’m guessing that PyTorch will calculate the gradient for all entries of the linear layer and all but one will be zero given the 1 hot input.  (ie: lots of computation for a large linear layer).  Or does Pytorch optimize this out?</p>
<p>Will Pytorch do the same for embedding or will PyTorch initialize and backpropagate only to the index embedding?</p>
<p>Assuming limited GPU memory and large CPU memory.  Do both share the same minimal (&gt; zero) amount of data that can be sent to GPU?</p>

vdw: <p><a class="mention" href="/u/john_grabner">@John_Grabner</a> To be honest, I have no idea. Maybe someone with a deeper knowledge of the implementation will reply to this.</p>
<p>If I would have to guess, I would say that this is optimized. After all, this is kind of the purpose of an embedding layer compared to a general linaer layer: exploiting the knowledge that just one index/row is affected – or multiple indices/rows in case multiple inputs.</p>
<p>Just don’t quote me on this <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>

googlebot: <p>Sparse gradients mode can be enabled for nn.Embedding, with it gradient elementwise mean &amp; variance estimates are updated correctly (for specific optimizers); but this may not reduce peak memory, as that gradient tensor is short-lived (due to reverse mode backprop). Instead, it is possible to not move nn.Embedding to GPU (moving just a lookup results in forward() instead).</p>

John_Grabner: <p>Transformers most often have as input the addition of something and a position embedding.<br>
For example, position 1 to 128 represented as <code>torch.nn.Embedding(num_embeddings=128</code>.<br>
I never see <code>torch.nn.Linear</code> to project a float position to embedding. Nor do I see the sparce flag set for the embedding.</p>
<p>If they (Linear and Embedding) are essentially the same, I would assume some people would choose the linear projection (cleaner in my mind when the embedding is for position).</p>
<p>In non AI, non backprogration, a lookup can be implemented much more efficiently than multiplying an array by a mask. Especially so if the table is large.</p>
<p>I believe BERT usage of transformer use very large embedding (52K) to represent words in addition to embeddings for word position.</p>
<p>Scavenged the GitHub repo for PyTorch and found Embedding.cpp in the call path of nn.Embedding.  No idea of how this code does its magic, but embedding_dense_backward_cpu has a bunch of if statements before adding grad_weights while Linear.cpp does a multiplication.</p>
<p>So I’m guessing embedding is much faster in backpropagation over linear especially when large embedding are used. If small embeddings, then essentially the same.</p>
<p>Hoping someone who understands the PyTorch implementation to say for sure.</p>

Wesley_Neill: <p>Hi Chris,</p>
<p>I’m just trying to make the connection between nn.Embedding and nn.Linear. I think I understand what an embedding is: A representation of the input in a different vector space. Would you mind clarifying this point:</p>
<blockquote>
<p>Now giving such a vector <code>v</code> with <code>v[2]=1</code> (cf. example vector above) to the Linear layer gives you simply the 2nd row of that layer.</p>
</blockquote>
<p>I think I’ve made embeddings before by training an LSTM autoencoder to reconstruct the input sequence from the final hidden state. I thought the embedding would then be the hidden state of the encoder.</p>
<p>I’ve only ever done time-series related work with LSTMs, but am trying to learn their NLP applications and can’t find a word written on NLP that doesn’t include the use of an <code>nn.Embedding</code> layer.</p>

vdw: <p>When you time series analysis, your input is presumably already numerical, so the notion of an embedding is not an issues there.</p>
<p>In NLP you typically deal with words, i.e., non-numerical input. So you have to encode your sentences, paragraphs, documents, etc. somehow for the model to “understand” them. The naive approach would be to One-Hot encoding where each word is a vector of the size of your vocabulary with only a single 1 at the index of the corresponding word. For example if the index of word “hello” has the index 42 in your vocabulary, the One-Hot encoded word vector for “hello” would look like:</p>
<pre><code>[0 0 0 0 0 ... 0 0 1 0 ... 0 0 0 0 0 0 ]
</code></pre>
<p>with the whole vector being <code>vocab_size</code> long, and the 1 is at index 42. The problem is that for many NLP applications, your vocabulary can be very large, e.g., way beyond 100,000 words (but let’s stick with 100k). Now, if your input document has, say 100 words, then your input for your model is a <code>M.shape = (100, 100000)</code>. This is annoyingly large…and unnecessarily so, as we see in a bit…</p>
<p>Your first layer getting this input is typically an Linear layer of, say, shape <code>E.shape = (100000, 300)</code> to reduce the dimensionality. If you do the calculations, you will notice that <code>M.dot(E)</code> does nothing more than selecting the rows in E that correspond to the indices of the 1’s in M (because M is One-Hot encoded). If this is unclear, I recommend doing this with a toy example on paper.</p>
<p>Knowing this, there’s no need for the One-Hot encoded matrix M anymore, we only need the indices of the words. <code>nn.Embedding</code> is more or less just a linear layer to facilitate the <code>M.dot(E)</code> but without the need of the large matrix M. This is why you don’t see any example in NLP without an explicit embedding layer (an exception might be character-based models where you vocabulary is small, e.g., &lt; 100 characters).</p>

Wesley_Neill: <p>Ah I see what you are saying! M acts as a sort of permutation matrix on E. I did it on paper and see exactly what you mean now. That also brings clarity to something I’ve often read, that <code>nn.Embedding</code> acts as a sort of lookup table. Okay, great! This has been a big question for me for a while now. Thank you!</p>

vdw: <p>Yes, multiplying a one-hot vector with the embedding matrix basically just makes a lookup.</p>
<p>I also assume(!) that <code>nn.Embedding</code> does backpropagation smarter since it knows which rows in the matrix can only be affected. But I don’t really know about the inner workings.</p>

Guan_Deng: <p>can you show your paper? or make a pic to show? i am still not very sure about this, especially the size parameter<br>
nn.Embedding(num_users, emb_size)</p>

Wesley_Neill: <p>So the idea is that a linear layer is simply a matrix multiplication of the inputs by the weights defined by the layer:</p>
<p><strong><code>y = x * A.T + b</code></strong></p>
<p>Where <strong><code>A</code></strong> is the weight matrix of the linear layer.</p>
<p>Now, imagine that <strong><code>x</code></strong> is one hot encoded vector representing a single word in your vocabulary. This vector is all zeros with a single one. Then you can ask yourself, what is the output of the multiplication <strong><code>x * A.T</code></strong>? The result is a single row of <strong><code>A</code></strong>. If this doesn’t make sense, try it yourself on paper. Multiply a sparse vector by any dense matrix <strong>A</strong>.</p>
<p>After you have confirmed that what I say is true we can imagine next steps:</p>
<p>For one-hot vector <strong><code>x_i</code></strong> (for each word in the vocabulary):<br>
1. Compute <strong><code>y_i = x_i * A </code></strong><br>
2. Stack  <strong><code>y_i</code></strong> for <strong><code>i = 1 ... vocab_size</code></strong> into a new of row vectors… matrix <strong><code>E</code></strong></p>
<p>Now, this matrix <code>E</code> serves two purposes. It is both a linear transformation whose weights can be updated/learned AND a look-up table for your vocabulary.</p>
<p>I hope that makes sense!</p>

FILALI_HOUCEMEDDINE: <p>Thank you for your instructive answer. I’m just wondering if nn.Embedding(…) includes a mechanism to avoid duplicate representation for different words (i.e having duplicate rows in it’s parameter Matrix).</p>

kyduff: <p>It does not. Implementation is <a href="https://github.com/pytorch/pytorch/blob/5b03ff0a09d43d721067e39da10aa23edc6997cd/aten/src/ATen/native/Embedding.cpp#L14-L29" rel="noopener nofollow ugc">here</a>. However the weights are (usually—it’s up to you) initialized randomly and the probability of a collision is theoretically 0. In practice (since machines are digital) the probability of a collision is not actually zero but effectively so for all intents and purposes.</p>

Bharathwajan: <p>hello chris,<br>
i had tried embedding layer but instead of one hot vector instead it gives me a vector of real numbers ,how these values are learned or it was just some random vectors based on the vocabulary <br><br>
if they are random vecors will that get trained during my model training process or it will remain same .<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/5/9/59f7654a339b9a5d5dcf5cac9d1751117f7fd68f.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/59f7654a339b9a5d5dcf5cac9d1751117f7fd68f" title="embedding"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/5/9/59f7654a339b9a5d5dcf5cac9d1751117f7fd68f_2_690x486.jpeg" alt="embedding" data-base62-sha1="cPSxkFl1HshkaFbsfQQMriz78cf" width="690" height="486" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/5/9/59f7654a339b9a5d5dcf5cac9d1751117f7fd68f_2_690x486.jpeg, https://discuss.pytorch.org/uploads/default/optimized/3X/5/9/59f7654a339b9a5d5dcf5cac9d1751117f7fd68f_2_1035x729.jpeg 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/5/9/59f7654a339b9a5d5dcf5cac9d1751117f7fd68f.jpeg 2x" data-dominant-color="262627"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">embedding</span><span class="informations">1076×758 83.5 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>