{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/duoan/TorchCode/blob/master/templates/18_embedding.ipynb)\n", "\n", "# ๐ŸŸข Easy: Embedding Layer\n", "\n", "Implement an **embedding lookup table** from scratch.\n", "\n", "### Signature\n", "```python\n", "class MyEmbedding(nn.Module):\n", " def __init__(self, num_embeddings: int, embedding_dim: int): ...\n", " def forward(self, indices: Tensor) -> Tensor: ...\n", "```\n", "\n", "### Rules\n", "- `self.weight`: `nn.Parameter` of shape `(num_embeddings, embedding_dim)`\n", "- Forward: index into weight matrix โ€” `weight[indices]`\n", "- Do NOT use `nn.Embedding`" ], "outputs": [] }, { "cell_type": "code", "metadata": {}, "source": [ "# Install torch-judge in Colab (no-op in JupyterLab/Docker)\n", "try:\n", " import google.colab\n", " get_ipython().run_line_magic('pip', 'install -q torch-judge')\n", "except ImportError:\n", " pass\n" ], "outputs": [], "execution_count": null }, { "cell_type": "code", "metadata": {}, "outputs": [], "source": [ "import torch\n", "import torch.nn as nn" ], "execution_count": null }, { "cell_type": "code", "metadata": {}, "outputs": [], "source": [ "# โœ๏ธ YOUR IMPLEMENTATION HERE\n", "\n", "class MyEmbedding(nn.Module):\n", " def __init__(self, num_embeddings, embedding_dim):\n", " super().__init__()\n", " pass\n", "\n", " def forward(self, indices):\n", " pass" ], "execution_count": null }, { "cell_type": "code", "metadata": {}, "outputs": [], "source": [ "# ๐Ÿงช Debug\n", "emb = MyEmbedding(10, 4)\n", "idx = torch.tensor([0, 3, 7])\n", "print('Output shape:', emb(idx).shape)\n", "print('Matches manual:', torch.equal(emb(idx)[0], emb.weight[0]))" ], "execution_count": null }, { "cell_type": "code", "metadata": {}, "outputs": [], "source": [ "# โœ… SUBMIT\n", "from torch_judge import check\n", "check('embedding')" ], "execution_count": null } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.11.0" } }, "nbformat": 4, "nbformat_minor": 4 }