Pretraining word2vec

:label:sec_word2vec_pretraining

We go on to implement the skip-gram model defined in :numref:sec_word2vec. Then we will pretrain word2vec using negative sampling on the PTB dataset. First of all, let us obtain the data iterator and the vocabulary for this dataset by calling the d2l.load_data_ptb function, which was described in :numref:sec_word2vec_data

```{.python .input} from d2l import mxnet as d2l import math from mxnet import autograd, gluon, np, npx from mxnet.gluon import nn npx.set_np()

batch_size, max_window_size, num_noise_words = 512, 5, 5 data_iter, vocab = d2l.load_data_ptb(batch_size, max_window_size, num_noise_words)

  1. ```{.python .input}
  2. #@tab pytorch
  3. from d2l import torch as d2l
  4. import math
  5. import torch
  6. from torch import nn
  7. batch_size, max_window_size, num_noise_words = 512, 5, 5
  8. data_iter, vocab = d2l.load_data_ptb(batch_size, max_window_size,
  9. num_noise_words)

The Skip-Gram Model

We implement the skip-gram model by using embedding layers and batch matrix multiplications. First, let us review how embedding layers work.

Embedding Layer

As described in :numref:sec_seq2seq, an embedding layer maps a token’s index to its feature vector. The weight of this layer is a matrix whose number of rows equals to the dictionary size (input_dim) and number of columns equals to the vector dimension for each token (output_dim). After a word embedding model is trained, this weight is what we need.

```{.python .input} embed = nn.Embedding(input_dim=20, output_dim=4) embed.initialize() embed.weight

  1. ```{.python .input}
  2. #@tab pytorch
  3. embed = nn.Embedding(num_embeddings=20, embedding_dim=4)
  4. print(f'Parameter embedding_weight ({embed.weight.shape}, '
  5. f'dtype={embed.weight.dtype})')

The input of an embedding layer is the index of a token (word). For any token index $i$, its vector representation can be obtained from the $i^\mathrm{th}$ row of the weight matrix in the embedding layer. Since the vector dimension (output_dim) was set to 4, the embedding layer returns vectors with shape (2, 3, 4) for a minibatch of token indices with shape (2, 3).

```{.python .input}

@tab all

x = d2l.tensor([[1, 2, 3], [4, 5, 6]]) embed(x)

  1. ### Defining the Forward Propagation
  2. In the forward propagation,
  3. the input of the skip-gram model
  4. includes
  5. the center word indices `center`
  6. of shape (batch size, 1)
  7. and
  8. the concatenated context and noise word indices `contexts_and_negatives`
  9. of shape (batch size, `max_len`),
  10. where `max_len`
  11. is defined
  12. in :numref:`subsec_word2vec-minibatch-loading`.
  13. These two variables are first transformed from the
  14. token indices into vectors via the embedding layer,
  15. then their batch matrix multiplication
  16. (described in :numref:`subsec_batch_dot`)
  17. returns
  18. an output of shape (batch size, 1, `max_len`).
  19. Each element in the output is the dot product of
  20. a center word vector and a context or noise word vector.
  21. ```{.python .input}
  22. def skip_gram(center, contexts_and_negatives, embed_v, embed_u):
  23. v = embed_v(center)
  24. u = embed_u(contexts_and_negatives)
  25. pred = npx.batch_dot(v, u.swapaxes(1, 2))
  26. return pred

```{.python .input}

@tab pytorch

def skip_gram(center, contexts_and_negatives, embed_v, embed_u): v = embed_v(center) u = embed_u(contexts_and_negatives) pred = torch.bmm(v, u.permute(0, 2, 1)) return pred

  1. Let us print the output shape of this `skip_gram` function for some example inputs.
  2. ```{.python .input}
  3. skip_gram(np.ones((2, 1)), np.ones((2, 4)), embed, embed).shape

```{.python .input}

@tab pytorch

skip_gram(torch.ones((2, 1), dtype=torch.long), torch.ones((2, 4), dtype=torch.long), embed, embed).shape

  1. ## Training
  2. Before training the skip-gram model with negative sampling,
  3. let us first define its loss function.
  4. ### Binary Cross-Entropy Loss
  5. According to the definition of the loss function
  6. for negative sampling in :numref:`subsec_negative-sampling`,
  7. we will use
  8. the binary cross-entropy loss.
  9. ```{.python .input}
  10. loss = gluon.loss.SigmoidBCELoss()

```{.python .input}

@tab pytorch

class SigmoidBCELoss(nn.Module):

  1. # Binary cross-entropy loss with masking
  2. def __init__(self):
  3. super().__init__()
  4. def forward(self, inputs, target, mask=None):
  5. out = nn.functional.binary_cross_entropy_with_logits(
  6. inputs, target, weight=mask, reduction="none")
  7. return out.mean(dim=1)

loss = SigmoidBCELoss()

  1. Recall our descriptions
  2. of the mask variable
  3. and the label variable in
  4. :numref:`subsec_word2vec-minibatch-loading`.
  5. The following
  6. calculates the
  7. binary cross-entropy loss
  8. for the given variables.
  9. ```{.python .input}
  10. #@tab all
  11. pred = d2l.tensor([[1.1, -2.2, 3.3, -4.4]] * 2)
  12. label = d2l.tensor([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]])
  13. mask = d2l.tensor([[1, 1, 1, 1], [1, 1, 0, 0]])
  14. loss(pred, label, mask) * mask.shape[1] / mask.sum(axis=1)

Below shows how the above results are calculated (in a less efficient way) using the sigmoid activation function in the binary cross-entropy loss. We can consider the two outputs as two normalized losses that are averaged over non-masked predictions.

```{.python .input}

@tab all

def sigmd(x): return -math.log(1 / (1 + math.exp(-x)))

print(f’{(sigmd(1.1) + sigmd(2.2) + sigmd(-3.3) + sigmd(4.4)) / 4:.4f}’) print(f’{(sigmd(-1.1) + sigmd(-2.2)) / 2:.4f}’)

  1. ### Initializing Model Parameters
  2. We define two embedding layers
  3. for all the words in the vocabulary
  4. when they are used as center words
  5. and context words, respectively.
  6. The word vector dimension
  7. `embed_size` is set to 100.
  8. ```{.python .input}
  9. embed_size = 100
  10. net = nn.Sequential()
  11. net.add(nn.Embedding(input_dim=len(vocab), output_dim=embed_size),
  12. nn.Embedding(input_dim=len(vocab), output_dim=embed_size))

```{.python .input}

@tab pytorch

embed_size = 100 net = nn.Sequential(nn.Embedding(num_embeddings=len(vocab), embedding_dim=embed_size), nn.Embedding(num_embeddings=len(vocab), embedding_dim=embed_size))

  1. ### Defining the Training Loop
  2. The training loop is defined below. Because of the existence of padding, the calculation of the loss function is slightly different compared to the previous training functions.
  3. ```{.python .input}
  4. def train(net, data_iter, lr, num_epochs, device=d2l.try_gpu()):
  5. net.initialize(ctx=device, force_reinit=True)
  6. trainer = gluon.Trainer(net.collect_params(), 'adam',
  7. {'learning_rate': lr})
  8. animator = d2l.Animator(xlabel='epoch', ylabel='loss',
  9. xlim=[1, num_epochs])
  10. # Sum of normalized losses, no. of normalized losses
  11. metric = d2l.Accumulator(2)
  12. for epoch in range(num_epochs):
  13. timer, num_batches = d2l.Timer(), len(data_iter)
  14. for i, batch in enumerate(data_iter):
  15. center, context_negative, mask, label = [
  16. data.as_in_ctx(device) for data in batch]
  17. with autograd.record():
  18. pred = skip_gram(center, context_negative, net[0], net[1])
  19. l = (loss(pred.reshape(label.shape), label, mask) *
  20. mask.shape[1] / mask.sum(axis=1))
  21. l.backward()
  22. trainer.step(batch_size)
  23. metric.add(l.sum(), l.size)
  24. if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
  25. animator.add(epoch + (i + 1) / num_batches,
  26. (metric[0] / metric[1],))
  27. print(f'loss {metric[0] / metric[1]:.3f}, '
  28. f'{metric[1] / timer.stop():.1f} tokens/sec on {str(device)}')

```{.python .input}

@tab pytorch

def train(net, dataiter, lr, num_epochs, device=d2l.try_gpu()): def init_weights(m): if type(m) == nn.Embedding: nn.init.xavier_uniform(m.weight) net.apply(init_weights) net = net.to(device) optimizer = torch.optim.Adam(net.parameters(), lr=lr) animator = d2l.Animator(xlabel=’epoch’, ylabel=’loss’, xlim=[1, num_epochs])

  1. # Sum of normalized losses, no. of normalized losses
  2. metric = d2l.Accumulator(2)
  3. for epoch in range(num_epochs):
  4. timer, num_batches = d2l.Timer(), len(data_iter)
  5. for i, batch in enumerate(data_iter):
  6. optimizer.zero_grad()
  7. center, context_negative, mask, label = [
  8. data.to(device) for data in batch]
  9. pred = skip_gram(center, context_negative, net[0], net[1])
  10. l = (loss(pred.reshape(label.shape).float(), label.float(), mask)
  11. / mask.sum(axis=1) * mask.shape[1])
  12. l.sum().backward()
  13. optimizer.step()
  14. metric.add(l.sum(), l.numel())
  15. if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
  16. animator.add(epoch + (i + 1) / num_batches,
  17. (metric[0] / metric[1],))
  18. print(f'loss {metric[0] / metric[1]:.3f}, '
  19. f'{metric[1] / timer.stop():.1f} tokens/sec on {str(device)}')
  1. Now we can train a skip-gram model using negative sampling.
  2. ```{.python .input}
  3. #@tab all
  4. lr, num_epochs = 0.002, 5
  5. train(net, data_iter, lr, num_epochs)

Applying Word Embeddings

After training the word2vec model, we can use the cosine similarity of word vectors from the trained model to find words from the dictionary that are most semantically similar to an input word.

```{.python .input} def get_similar_tokens(query_token, k, embed): W = embed.weight.data() x = W[vocab[query_token]]

  1. # Compute the cosine similarity. Add 1e-9 for numerical stability
  2. cos = np.dot(W, x) / np.sqrt(np.sum(W * W, axis=1) * np.sum(x * x) + 1e-9)
  3. topk = npx.topk(cos, k=k+1, ret_typ='indices').asnumpy().astype('int32')
  4. for i in topk[1:]: # Remove the input words
  5. print(f'cosine sim={float(cos[i]):.3f}: {vocab.to_tokens(i)}')

get_similar_tokens(‘chip’, 3, net[0])

  1. ```{.python .input}
  2. #@tab pytorch
  3. def get_similar_tokens(query_token, k, embed):
  4. W = embed.weight.data
  5. x = W[vocab[query_token]]
  6. # Compute the cosine similarity. Add 1e-9 for numerical stability
  7. cos = torch.mv(W, x) / torch.sqrt(torch.sum(W * W, dim=1) *
  8. torch.sum(x * x) + 1e-9)
  9. topk = torch.topk(cos, k=k+1)[1].cpu().numpy().astype('int32')
  10. for i in topk[1:]: # Remove the input words
  11. print(f'cosine sim={float(cos[i]):.3f}: {vocab.to_tokens(i)}')
  12. get_similar_tokens('chip', 3, net[0])

Summary

  • We can train a skip-gram model with negative sampling using embedding layers and the binary cross-entropy loss.
  • Applications of word embeddings include finding semantically similar words for a given word based on the cosine similarity of word vectors.

Exercises

  1. Using the trained model, find semantically similar words for other input words. Can you improve the results by tuning hyperparameters?
  2. When a training corpus is huge, we often sample context words and noise words for the center words in the current minibatch when updating model parameters. In other words, the same center word may have different context words or noise words in different training epochs. What are the benefits of this method? Try to implement this training method.

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab: