{
 "cells": [
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "execute:\n",
    "  enabled: false\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-1 fw=all -->\n",
    "\n",
    "# Pretraining word2vec\n",
    "\n",
    "\n",
    "We go on to implement the skip-gram\n",
    "model defined in\n",
    "that section.\n",
    "Then\n",
    "we will pretrain word2vec using negative sampling\n",
    "on the PTB dataset.\n",
    "First of all,\n",
    "let's obtain the data iterator\n",
    "and the vocabulary for this dataset\n",
    "by calling the `d2l.load_data_ptb`\n",
    "function, which was described in that section"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-pretraining-word2vec"
   },
   "source": [
    "from d2l import torch as d2l\n",
    "import math\n",
    "import torch\n",
    "from torch import nn\n",
    "\n",
    "batch_size, max_window_size, num_noise_words = 512, 5, 5\n",
    "data_iter, vocab = d2l.load_data_ptb(batch_size, max_window_size,\n",
    "                                     num_noise_words)"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-2 fw=all -->\n",
    "\n",
    "## The Skip-Gram Model\n",
    "\n",
    "We implement the skip-gram model\n",
    "by using embedding layers and batch matrix multiplications.\n",
    "First, let's review\n",
    "how embedding layers work.\n",
    "\n",
    "\n",
    "### Embedding Layer\n",
    "\n",
    "As described in that section,\n",
    "an embedding layer\n",
    "maps a token's index to its feature vector.\n",
    "The weight of this layer\n",
    "is a matrix whose number of rows equals to\n",
    "the dictionary size (`input_dim`) and\n",
    "number of columns equals to\n",
    "the vector dimension for each token (`output_dim`).\n",
    "After a word embedding model is trained,\n",
    "this weight is what we need."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-embedding-layer-1"
   },
   "source": [
    "embed = nn.Embedding(num_embeddings=20, embedding_dim=4)\n",
    "print(f'Parameter embedding_weight ({embed.weight.shape}, '\n",
    "      f'dtype={embed.weight.dtype})')"
   ],
   "execution_count": 2,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Parameter embedding_weight (torch.Size([20, 4]), dtype=torch.float32)\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-3 fw=all -->\n",
    "\n",
    "The input of an embedding layer is the\n",
    "index of a token (word).\n",
    "For any token index $i$,\n",
    "its vector representation\n",
    "can be obtained from\n",
    "the $i^\\textrm{th}$ row of the weight matrix\n",
    "in the embedding layer.\n",
    "Since the vector dimension (`output_dim`)\n",
    "was set to 4,\n",
    "the embedding layer\n",
    "returns vectors with shape (2, 3, 4)\n",
    "for a minibatch of token indices with shape\n",
    "(2, 3)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-embedding-layer-2"
   },
   "source": [
    "x = d2l.tensor([[1, 2, 3], [4, 5, 6]])\n",
    "embed(x)"
   ],
   "execution_count": 3,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "tensor([[[ 0.0794,  0.4566, -1.8318,  0.0370],\n         [-0.3005,  0.9329, -0.7579, -0.8366],\n         [-0.5757,  0.1299, -1.1041, -0.7266]],\n\n        [[-1.5791,  0.0219, -0.3503, -0.8378],\n         [-0.5352,  0.8726, -0.2184, -0.4465],\n         [-0.4829,  1.5386, -0.9559, -0.8959]]], grad_fn=<EmbeddingBackward0>)"
     },
     "metadata": {},
     "execution_count": 3
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-4 fw=all -->\n",
    "\n",
    "### Defining the Forward Propagation\n",
    "\n",
    "In the forward propagation,\n",
    "the input of the skip-gram model\n",
    "includes\n",
    "the center word indices `center`\n",
    "of shape (batch size, 1)\n",
    "and\n",
    "the concatenated context and noise word indices `contexts_and_negatives`\n",
    "of shape (batch size, `max_len`),\n",
    "where `max_len`\n",
    "is defined\n",
    "in that section.\n",
    "These two variables are first transformed from the\n",
    "token indices into vectors via the embedding layer,\n",
    "then their batch matrix multiplication\n",
    "(described in that section)\n",
    "returns\n",
    "an output of shape (batch size, 1, `max_len`).\n",
    "Each element in the output is the dot product of\n",
    "a center word vector and a context or noise word vector."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-defining-the-forward-propagation-1"
   },
   "source": [
    "def skip_gram(center, contexts_and_negatives, embed_v, embed_u):\n",
    "    v = embed_v(center)\n",
    "    u = embed_u(contexts_and_negatives)\n",
    "    pred = torch.bmm(v, u.permute(0, 2, 1))\n",
    "    return pred"
   ],
   "execution_count": 4,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-5 fw=all -->\n",
    "\n",
    "Let's print the output shape of this `skip_gram` function for some example inputs."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-defining-the-forward-propagation-2"
   },
   "source": [
    "skip_gram(torch.ones((2, 1), dtype=torch.long),\n",
    "          torch.ones((2, 4), dtype=torch.long), embed, embed).shape"
   ],
   "execution_count": 5,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "torch.Size([2, 1, 4])"
     },
     "metadata": {},
     "execution_count": 5
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-6 fw=all -->\n",
    "\n",
    "## Training\n",
    "\n",
    "Before training the skip-gram model with negative sampling,\n",
    "let's first define its loss function.\n",
    "\n",
    "\n",
    "### Binary Cross-Entropy Loss\n",
    "\n",
    "According to the definition of the loss function\n",
    "for negative sampling in that section, \n",
    "we will use \n",
    "the binary cross-entropy loss."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-binary-cross-entropy-loss-1"
   },
   "source": [
    "class SigmoidBCELoss(nn.Module):\n",
    "    # Binary cross-entropy loss with masking\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "\n",
    "    def forward(self, inputs, target, mask=None):\n",
    "        out = nn.functional.binary_cross_entropy_with_logits(\n",
    "            inputs, target, weight=mask, reduction=\"none\")\n",
    "        return out.mean(dim=1)\n",
    "\n",
    "loss = SigmoidBCELoss()"
   ],
   "execution_count": 6,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-7 fw=all -->\n",
    "\n",
    "Recall our descriptions\n",
    "of the mask variable\n",
    "and the label variable in\n",
    "that section.\n",
    "The following\n",
    "calculates the \n",
    "binary cross-entropy loss\n",
    "for the given variables."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-binary-cross-entropy-loss-2"
   },
   "source": [
    "pred = d2l.tensor([[1.1, -2.2, 3.3, -4.4]] * 2)\n",
    "label = d2l.tensor([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]])\n",
    "mask = d2l.tensor([[1, 1, 1, 1], [1, 1, 0, 0]])\n",
    "loss(pred, label, mask) * mask.shape[1] / mask.sum(axis=1)"
   ],
   "execution_count": 7,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "tensor([0.9352, 1.8462])"
     },
     "metadata": {},
     "execution_count": 7
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-8 fw=all -->\n",
    "\n",
    "Below shows\n",
    "how the above results are calculated\n",
    "(in a less efficient way)\n",
    "using the\n",
    "sigmoid activation function\n",
    "in the binary cross-entropy loss.\n",
    "We can consider \n",
    "the two outputs as\n",
    "two normalized losses\n",
    "that are averaged over non-masked predictions."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-binary-cross-entropy-loss-3"
   },
   "source": [
    "def sigmd(x):\n",
    "    return -math.log(1 / (1 + math.exp(-x)))\n",
    "\n",
    "print(f'{(sigmd(1.1) + sigmd(2.2) + sigmd(-3.3) + sigmd(4.4)) / 4:.4f}')\n",
    "print(f'{(sigmd(-1.1) + sigmd(-2.2)) / 2:.4f}')"
   ],
   "execution_count": 8,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "0.9352\n1.8462\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-9 fw=all -->\n",
    "\n",
    "### Initializing Model Parameters\n",
    "\n",
    "We define two embedding layers\n",
    "for all the words in the vocabulary\n",
    "when they are used as center words\n",
    "and context words, respectively.\n",
    "The word vector dimension\n",
    "`embed_size` is set to 100."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-initializing-model-parameters"
   },
   "source": [
    "embed_size = 100\n",
    "net = nn.Sequential(nn.Embedding(num_embeddings=len(vocab),\n",
    "                                 embedding_dim=embed_size),\n",
    "                    nn.Embedding(num_embeddings=len(vocab),\n",
    "                                 embedding_dim=embed_size))"
   ],
   "execution_count": 9,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-10 fw=all -->\n",
    "\n",
    "### Defining the Training Loop\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-defining-the-training-loop-1"
   },
   "source": [
    "def train(net, data_iter, lr, num_epochs, device=d2l.try_gpu()):\n",
    "    def init_weights(module):\n",
    "        if type(module) == nn.Embedding:\n",
    "            nn.init.xavier_uniform_(module.weight)\n",
    "    net.apply(init_weights)\n",
    "    net = net.to(device)\n",
    "    optimizer = torch.optim.Adam(net.parameters(), lr=lr)\n",
    "    animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n",
    "                            xlim=[1, num_epochs])\n",
    "    # Sum of normalized losses, no. of normalized losses\n",
    "    metric = d2l.Accumulator(2)\n",
    "    for epoch in range(num_epochs):\n",
    "        timer, num_batches = d2l.Timer(), len(data_iter)\n",
    "        for i, batch in enumerate(data_iter):\n",
    "            optimizer.zero_grad()\n",
    "            center, context_negative, mask, label = [\n",
    "                data.to(device) for data in batch]\n",
    "\n",
    "            pred = skip_gram(center, context_negative, net[0], net[1])\n",
    "            l = (loss(pred.reshape(label.shape).float(), label.float(), mask)\n",
    "                     / mask.sum(axis=1) * mask.shape[1])\n",
    "            l.sum().backward()\n",
    "            optimizer.step()\n",
    "            metric.add(l.sum(), l.numel())\n",
    "            if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:\n",
    "                animator.add(epoch + (i + 1) / num_batches,\n",
    "                             (metric[0] / metric[1],))\n",
    "    print(f'loss {metric[0] / metric[1]:.3f}, '\n",
    "          f'{metric[1] / timer.stop():.1f} tokens/sec on {str(device)}')"
   ],
   "execution_count": 10,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-11 fw=all -->\n",
    "\n",
    "Now we can train a skip-gram model using negative sampling."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-defining-the-training-loop-2"
   },
   "source": [
    "lr, num_epochs = 0.002, 5\n",
    "train(net, data_iter, lr, num_epochs)"
   ],
   "execution_count": 11,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "loss 0.410, 405527.4 tokens/sec on cuda:0\n"
     ]
    },
    {
     "output_type": "display_data",
     "data": {
      "image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"255.825pt\" height=\"183.35625pt\" viewBox=\"0 0 255.825 183.35625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n <metadata>\n  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n   <cc:Work>\n    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n    <dc:date>2026-07-19T13:55:44.847497</dc:date>\n    <dc:format>image/svg+xml</dc:format>\n    <dc:creator>\n     <cc:Agent>\n      <dc:title>Matplotlib v3.10.8, https://matplotlib.org/</dc:title>\n     </cc:Agent>\n    </dc:creator>\n   </cc:Work>\n  </rdf:RDF>\n </metadata>\n <defs>\n  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n </defs>\n <g id=\"figure_1\">\n  <g id=\"patch_1\">\n   <path d=\"M 0 183.35625 \nL 255.825 183.35625 \nL 255.825 0 \nL 0 0 \nz\n\" style=\"fill: #ffffff\"/>\n  </g>\n  <g id=\"axes_1\">\n   <g id=\"patch_2\">\n    <path d=\"M 50.14375 145.8 \nL 245.44375 145.8 \nL 245.44375 7.2 \nL 50.14375 7.2 \nz\n\" style=\"fill: #ffffff\"/>\n   </g>\n   <g id=\"matplotlib.axis_1\">\n    <g id=\"xtick_1\">\n     <g id=\"line2d_1\">\n      <path d=\"M 50.14375 145.8 \nL 50.14375 7.2 \n\" clip-path=\"url(#pb42cba7787)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_2\">\n      <defs>\n       <path id=\"m7c313b8219\" d=\"M 0 0 \nL 0 3.5 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m7c313b8219\" x=\"50.14375\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_1\">\n      <!-- 1 -->\n      <g transform=\"translate(46.9625 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-31\" d=\"M 794 531 \nL 1825 531 \nL 1825 4091 \nL 703 3866 \nL 703 4441 \nL 1819 4666 \nL 2450 4666 \nL 2450 531 \nL 3481 531 \nL 3481 0 \nL 794 0 \nL 794 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-31\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_2\">\n     <g id=\"line2d_3\">\n      <path d=\"M 98.96875 145.8 \nL 98.96875 7.2 \n\" clip-path=\"url(#pb42cba7787)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_4\">\n      <g>\n       <use xlink:href=\"#m7c313b8219\" x=\"98.96875\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_2\">\n      <!-- 2 -->\n      <g transform=\"translate(95.7875 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \nL 3431 531 \nL 3431 0 \nL 469 0 \nL 469 531 \nQ 828 903 1448 1529 \nQ 2069 2156 2228 2338 \nQ 2531 2678 2651 2914 \nQ 2772 3150 2772 3378 \nQ 2772 3750 2511 3984 \nQ 2250 4219 1831 4219 \nQ 1534 4219 1204 4116 \nQ 875 4013 500 3803 \nL 500 4441 \nQ 881 4594 1212 4672 \nQ 1544 4750 1819 4750 \nQ 2544 4750 2975 4387 \nQ 3406 4025 3406 3419 \nQ 3406 3131 3298 2873 \nQ 3191 2616 2906 2266 \nQ 2828 2175 2409 1742 \nQ 1991 1309 1228 531 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-32\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_3\">\n     <g id=\"line2d_5\">\n      <path d=\"M 147.79375 145.8 \nL 147.79375 7.2 \n\" clip-path=\"url(#pb42cba7787)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_6\">\n      <g>\n       <use xlink:href=\"#m7c313b8219\" x=\"147.79375\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_3\">\n      <!-- 3 -->\n      <g transform=\"translate(144.6125 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-33\" d=\"M 2597 2516 \nQ 3050 2419 3304 2112 \nQ 3559 1806 3559 1356 \nQ 3559 666 3084 287 \nQ 2609 -91 1734 -91 \nQ 1441 -91 1130 -33 \nQ 819 25 488 141 \nL 488 750 \nQ 750 597 1062 519 \nQ 1375 441 1716 441 \nQ 2309 441 2620 675 \nQ 2931 909 2931 1356 \nQ 2931 1769 2642 2001 \nQ 2353 2234 1838 2234 \nL 1294 2234 \nL 1294 2753 \nL 1863 2753 \nQ 2328 2753 2575 2939 \nQ 2822 3125 2822 3475 \nQ 2822 3834 2567 4026 \nQ 2313 4219 1838 4219 \nQ 1578 4219 1281 4162 \nQ 984 4106 628 3988 \nL 628 4550 \nQ 988 4650 1302 4700 \nQ 1616 4750 1894 4750 \nQ 2613 4750 3031 4423 \nQ 3450 4097 3450 3541 \nQ 3450 3153 3228 2886 \nQ 3006 2619 2597 2516 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-33\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_4\">\n     <g id=\"line2d_7\">\n      <path d=\"M 196.61875 145.8 \nL 196.61875 7.2 \n\" clip-path=\"url(#pb42cba7787)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_8\">\n      <g>\n       <use xlink:href=\"#m7c313b8219\" x=\"196.61875\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_4\">\n      <!-- 4 -->\n      <g transform=\"translate(193.4375 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \nL 825 1625 \nL 2419 1625 \nL 2419 4116 \nz\nM 2253 4666 \nL 3047 4666 \nL 3047 1625 \nL 3713 1625 \nL 3713 1100 \nL 3047 1100 \nL 3047 0 \nL 2419 0 \nL 2419 1100 \nL 313 1100 \nL 313 1709 \nL 2253 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-34\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"xtick_5\">\n     <g id=\"line2d_9\">\n      <path d=\"M 245.44375 145.8 \nL 245.44375 7.2 \n\" clip-path=\"url(#pb42cba7787)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_10\">\n      <g>\n       <use xlink:href=\"#m7c313b8219\" x=\"245.44375\" y=\"145.8\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_5\">\n      <!-- 5 -->\n      <g transform=\"translate(242.2625 160.398438) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \nL 3169 4666 \nL 3169 4134 \nL 1269 4134 \nL 1269 2991 \nQ 1406 3038 1543 3061 \nQ 1681 3084 1819 3084 \nQ 2600 3084 3056 2656 \nQ 3513 2228 3513 1497 \nQ 3513 744 3044 326 \nQ 2575 -91 1722 -91 \nQ 1428 -91 1123 -41 \nQ 819 9 494 109 \nL 494 744 \nQ 775 591 1075 516 \nQ 1375 441 1709 441 \nQ 2250 441 2565 725 \nQ 2881 1009 2881 1497 \nQ 2881 1984 2565 2268 \nQ 2250 2553 1709 2553 \nQ 1456 2553 1204 2497 \nQ 953 2441 691 2322 \nL 691 4666 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-35\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_6\">\n     <!-- epoch -->\n     <g transform=\"translate(132.565625 174.076563) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \nL 3597 1613 \nL 953 1613 \nQ 991 1019 1311 708 \nQ 1631 397 2203 397 \nQ 2534 397 2845 478 \nQ 3156 559 3463 722 \nL 3463 178 \nQ 3153 47 2828 -22 \nQ 2503 -91 2169 -91 \nQ 1331 -91 842 396 \nQ 353 884 353 1716 \nQ 353 2575 817 3079 \nQ 1281 3584 2069 3584 \nQ 2775 3584 3186 3129 \nQ 3597 2675 3597 1894 \nz\nM 3022 2063 \nQ 3016 2534 2758 2815 \nQ 2500 3097 2075 3097 \nQ 1594 3097 1305 2825 \nQ 1016 2553 972 2059 \nL 3022 2063 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \nL 1159 -1331 \nL 581 -1331 \nL 581 3500 \nL 1159 3500 \nL 1159 2969 \nQ 1341 3281 1617 3432 \nQ 1894 3584 2278 3584 \nQ 2916 3584 3314 3078 \nQ 3713 2572 3713 1747 \nQ 3713 922 3314 415 \nQ 2916 -91 2278 -91 \nQ 1894 -91 1617 61 \nQ 1341 213 1159 525 \nz\nM 3116 1747 \nQ 3116 2381 2855 2742 \nQ 2594 3103 2138 3103 \nQ 1681 3103 1420 2742 \nQ 1159 2381 1159 1747 \nQ 1159 1113 1420 752 \nQ 1681 391 2138 391 \nQ 2594 391 2855 752 \nQ 3116 1113 3116 1747 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \nQ 1497 3097 1228 2736 \nQ 959 2375 959 1747 \nQ 959 1119 1226 758 \nQ 1494 397 1959 397 \nQ 2419 397 2687 759 \nQ 2956 1122 2956 1747 \nQ 2956 2369 2687 2733 \nQ 2419 3097 1959 3097 \nz\nM 1959 3584 \nQ 2709 3584 3137 3096 \nQ 3566 2609 3566 1747 \nQ 3566 888 3137 398 \nQ 2709 -91 1959 -91 \nQ 1206 -91 779 398 \nQ 353 888 353 1747 \nQ 353 2609 779 3096 \nQ 1206 3584 1959 3584 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \nL 3122 2828 \nQ 2878 2963 2633 3030 \nQ 2388 3097 2138 3097 \nQ 1578 3097 1268 2742 \nQ 959 2388 959 1747 \nQ 959 1106 1268 751 \nQ 1578 397 2138 397 \nQ 2388 397 2633 464 \nQ 2878 531 3122 666 \nL 3122 134 \nQ 2881 22 2623 -34 \nQ 2366 -91 2075 -91 \nQ 1284 -91 818 406 \nQ 353 903 353 1747 \nQ 353 2603 823 3093 \nQ 1294 3584 2113 3584 \nQ 2378 3584 2631 3529 \nQ 2884 3475 3122 3366 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \nL 3513 0 \nL 2938 0 \nL 2938 2094 \nQ 2938 2591 2744 2837 \nQ 2550 3084 2163 3084 \nQ 1697 3084 1428 2787 \nQ 1159 2491 1159 1978 \nL 1159 0 \nL 581 0 \nL 581 4863 \nL 1159 4863 \nL 1159 2956 \nQ 1366 3272 1645 3428 \nQ 1925 3584 2291 3584 \nQ 2894 3584 3203 3211 \nQ 3513 2838 3513 2113 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-65\"/>\n      <use xlink:href=\"#DejaVuSans-70\" transform=\"translate(61.523438 0)\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(125 0)\"/>\n      <use xlink:href=\"#DejaVuSans-63\" transform=\"translate(186.181641 0)\"/>\n      <use xlink:href=\"#DejaVuSans-68\" transform=\"translate(241.162109 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"matplotlib.axis_2\">\n    <g id=\"ytick_1\">\n     <g id=\"line2d_11\">\n      <path d=\"M 50.14375 145.76792 \nL 245.44375 145.76792 \n\" clip-path=\"url(#pb42cba7787)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_12\">\n      <defs>\n       <path id=\"m4c7a952df2\" d=\"M 0 0 \nL -3.5 0 \n\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </defs>\n      <g>\n       <use xlink:href=\"#m4c7a952df2\" x=\"50.14375\" y=\"145.76792\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_7\">\n      <!-- 0.40 -->\n      <g transform=\"translate(20.878125 149.567139) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \nQ 1547 4250 1301 3770 \nQ 1056 3291 1056 2328 \nQ 1056 1369 1301 889 \nQ 1547 409 2034 409 \nQ 2525 409 2770 889 \nQ 3016 1369 3016 2328 \nQ 3016 3291 2770 3770 \nQ 2525 4250 2034 4250 \nz\nM 2034 4750 \nQ 2819 4750 3233 4129 \nQ 3647 3509 3647 2328 \nQ 3647 1150 3233 529 \nQ 2819 -91 2034 -91 \nQ 1250 -91 836 529 \nQ 422 1150 422 2328 \nQ 422 3509 836 4129 \nQ 1250 4750 2034 4750 \nz\n\" transform=\"scale(0.015625)\"/>\n        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \nL 1344 794 \nL 1344 0 \nL 684 0 \nL 684 794 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-34\" transform=\"translate(95.410156 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(159.033203 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_2\">\n     <g id=\"line2d_13\">\n      <path d=\"M 50.14375 114.8476 \nL 245.44375 114.8476 \n\" clip-path=\"url(#pb42cba7787)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_14\">\n      <g>\n       <use xlink:href=\"#m4c7a952df2\" x=\"50.14375\" y=\"114.8476\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_8\">\n      <!-- 0.45 -->\n      <g transform=\"translate(20.878125 118.646818) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-34\" transform=\"translate(95.410156 0)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(159.033203 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_3\">\n     <g id=\"line2d_15\">\n      <path d=\"M 50.14375 83.927279 \nL 245.44375 83.927279 \n\" clip-path=\"url(#pb42cba7787)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_16\">\n      <g>\n       <use xlink:href=\"#m4c7a952df2\" x=\"50.14375\" y=\"83.927279\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_9\">\n      <!-- 0.50 -->\n      <g transform=\"translate(20.878125 87.726497) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(95.410156 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(159.033203 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_4\">\n     <g id=\"line2d_17\">\n      <path d=\"M 50.14375 53.006958 \nL 245.44375 53.006958 \n\" clip-path=\"url(#pb42cba7787)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_18\">\n      <g>\n       <use xlink:href=\"#m4c7a952df2\" x=\"50.14375\" y=\"53.006958\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_10\">\n      <!-- 0.55 -->\n      <g transform=\"translate(20.878125 56.806177) scale(0.1 -0.1)\">\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(95.410156 0)\"/>\n       <use xlink:href=\"#DejaVuSans-35\" transform=\"translate(159.033203 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"ytick_5\">\n     <g id=\"line2d_19\">\n      <path d=\"M 50.14375 22.086637 \nL 245.44375 22.086637 \n\" clip-path=\"url(#pb42cba7787)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n     </g>\n     <g id=\"line2d_20\">\n      <g>\n       <use xlink:href=\"#m4c7a952df2\" x=\"50.14375\" y=\"22.086637\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n      </g>\n     </g>\n     <g id=\"text_11\">\n      <!-- 0.60 -->\n      <g transform=\"translate(20.878125 25.885856) scale(0.1 -0.1)\">\n       <defs>\n        <path id=\"DejaVuSans-36\" d=\"M 2113 2584 \nQ 1688 2584 1439 2293 \nQ 1191 2003 1191 1497 \nQ 1191 994 1439 701 \nQ 1688 409 2113 409 \nQ 2538 409 2786 701 \nQ 3034 994 3034 1497 \nQ 3034 2003 2786 2293 \nQ 2538 2584 2113 2584 \nz\nM 3366 4563 \nL 3366 3988 \nQ 3128 4100 2886 4159 \nQ 2644 4219 2406 4219 \nQ 1781 4219 1451 3797 \nQ 1122 3375 1075 2522 \nQ 1259 2794 1537 2939 \nQ 1816 3084 2150 3084 \nQ 2853 3084 3261 2657 \nQ 3669 2231 3669 1497 \nQ 3669 778 3244 343 \nQ 2819 -91 2113 -91 \nQ 1303 -91 875 529 \nQ 447 1150 447 2328 \nQ 447 3434 972 4092 \nQ 1497 4750 2381 4750 \nQ 2619 4750 2861 4703 \nQ 3103 4656 3366 4563 \nz\n\" transform=\"scale(0.015625)\"/>\n       </defs>\n       <use xlink:href=\"#DejaVuSans-30\"/>\n       <use xlink:href=\"#DejaVuSans-2e\" transform=\"translate(63.623047 0)\"/>\n       <use xlink:href=\"#DejaVuSans-36\" transform=\"translate(95.410156 0)\"/>\n       <use xlink:href=\"#DejaVuSans-30\" transform=\"translate(159.033203 0)\"/>\n      </g>\n     </g>\n    </g>\n    <g id=\"text_12\">\n     <!-- loss -->\n     <g transform=\"translate(14.798437 86.157813) rotate(-90) scale(0.1 -0.1)\">\n      <defs>\n       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \nL 1178 4863 \nL 1178 0 \nL 603 0 \nL 603 4863 \nz\n\" transform=\"scale(0.015625)\"/>\n       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \nL 2834 2853 \nQ 2591 2978 2328 3040 \nQ 2066 3103 1784 3103 \nQ 1356 3103 1142 2972 \nQ 928 2841 928 2578 \nQ 928 2378 1081 2264 \nQ 1234 2150 1697 2047 \nL 1894 2003 \nQ 2506 1872 2764 1633 \nQ 3022 1394 3022 966 \nQ 3022 478 2636 193 \nQ 2250 -91 1575 -91 \nQ 1294 -91 989 -36 \nQ 684 19 347 128 \nL 347 722 \nQ 666 556 975 473 \nQ 1284 391 1588 391 \nQ 1994 391 2212 530 \nQ 2431 669 2431 922 \nQ 2431 1156 2273 1281 \nQ 2116 1406 1581 1522 \nL 1381 1569 \nQ 847 1681 609 1914 \nQ 372 2147 372 2553 \nQ 372 3047 722 3315 \nQ 1072 3584 1716 3584 \nQ 2034 3584 2315 3537 \nQ 2597 3491 2834 3397 \nz\n\" transform=\"scale(0.015625)\"/>\n      </defs>\n      <use xlink:href=\"#DejaVuSans-6c\"/>\n      <use xlink:href=\"#DejaVuSans-6f\" transform=\"translate(27.783203 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(88.964844 0)\"/>\n      <use xlink:href=\"#DejaVuSans-73\" transform=\"translate(141.064453 0)\"/>\n     </g>\n    </g>\n   </g>\n   <g id=\"line2d_21\">\n    <path d=\"M 11.08375 13.5 \nL 20.84875 60.641546 \nL 30.61375 79.527893 \nL 40.37875 89.575918 \nL 50.14375 95.959663 \nL 59.90875 100.792401 \nL 69.67375 104.55147 \nL 79.43875 107.66467 \nL 89.20375 110.332165 \nL 98.96875 112.689235 \nL 108.73375 115.199008 \nL 118.49875 117.421784 \nL 128.26375 119.457173 \nL 138.02875 121.297559 \nL 147.79375 122.974235 \nL 157.55875 125.078035 \nL 167.32375 126.963249 \nL 177.08875 128.70025 \nL 186.85375 130.280144 \nL 196.61875 131.716739 \nL 206.38375 133.601622 \nL 216.14875 135.283251 \nL 225.91375 136.822946 \nL 235.67875 138.224345 \nL 245.44375 139.5 \n\" clip-path=\"url(#pb42cba7787)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_3\">\n    <path d=\"M 50.14375 145.8 \nL 50.14375 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_4\">\n    <path d=\"M 245.44375 145.8 \nL 245.44375 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_5\">\n    <path d=\"M 50.14375 145.8 \nL 245.44375 145.8 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n   <g id=\"patch_6\">\n    <path d=\"M 50.14375 7.2 \nL 245.44375 7.2 \n\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n   </g>\n  </g>\n </g>\n <defs>\n  <clipPath id=\"pb42cba7787\">\n   <rect x=\"50.14375\" y=\"7.2\" width=\"195.3\" height=\"138.6\"/>\n  </clipPath>\n </defs>\n</svg>\n"
     },
     "metadata": {}
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-12 fw=all -->\n",
    "\n",
    "## Applying Word Embeddings\n",
    "\n",
    "\n",
    "After training the word2vec model,\n",
    "we can use the cosine similarity\n",
    "of word vectors from the trained model\n",
    "to \n",
    "find words from the dictionary\n",
    "that are most semantically similar\n",
    "to an input word."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "id": "word2vec-pretraining-applying-word-embeddings"
   },
   "source": [
    "def get_similar_tokens(query_token, k, embed):\n",
    "    W = embed.weight.data\n",
    "    x = W[vocab[query_token]]\n",
    "    # Compute the cosine similarity. Add 1e-9 for numerical stability\n",
    "    cos = torch.mv(W, x) / torch.sqrt(torch.sum(W * W, dim=1) *\n",
    "                                      torch.sum(x * x) + 1e-9)\n",
    "    topk = torch.topk(cos, k=k+1)[1].cpu().numpy().astype('int32')\n",
    "    for i in topk[1:]:  # Remove the input words\n",
    "        print(f'cosine sim={float(cos[i]):.3f}: {vocab.to_tokens(i)}')\n",
    "\n",
    "get_similar_tokens('chip', 3, net[0])"
   ],
   "execution_count": 12,
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "cosine sim=0.731: bugs\ncosine sim=0.650: memory\ncosine sim=0.649: desktop\n"
     ]
    }
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-13 fw=all -->\n",
    "\n",
    "## Summary\n",
    "\n",
    "* We can train a skip-gram model with negative sampling using embedding layers and the binary cross-entropy loss.\n",
    "* Applications of word embeddings include finding semantically similar words for a given word based on the cosine similarity of word vectors.\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Using the trained model, find semantically similar words for other input words. Can you improve the results by tuning hyperparameters?\n",
    "1. 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."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- d2l:prose id=word2vec-pretraining-md-14 fw=pytorch -->\n",
    "\n",
    "[Discussions](https://d2l.discourse.group/t/1335)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "d2l-pytorch",
   "display_name": "d2l (PyTorch)",
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
