{ "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/27_vit_patch.ipynb)\n", "\n", "# ๐ŸŸ  Medium: ViT Patch Embedding\n", "\n", "Implement the **patch embedding** layer from Vision Transformer (ViT).\n", "\n", "### Signature\n", "```python\n", "class PatchEmbedding(nn.Module):\n", " def __init__(self, img_size, patch_size, in_channels, embed_dim): ...\n", " def forward(self, x: Tensor) -> Tensor:\n", " # x: (B, C, H, W)\n", " # Returns: (B, num_patches, embed_dim)\n", "```\n", "\n", "### Algorithm\n", "1. Reshape image into non-overlapping patches: `(B, C, H, W)` โ†’ `(B, N, C*P*P)`\n", "2. Project each patch: `nn.Linear(C*P*P, embed_dim)`\n", "3. `num_patches = (img_size // patch_size) ** 2`" ], "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 PatchEmbedding(nn.Module):\n", " def __init__(self, img_size, patch_size, in_channels, embed_dim):\n", " super().__init__()\n", " pass # self.num_patches, self.proj\n", "\n", " def forward(self, x):\n", " pass # reshape to patches, project" ], "execution_count": null }, { "cell_type": "code", "metadata": {}, "outputs": [], "source": [ "# ๐Ÿงช Debug\n", "pe = PatchEmbedding(32, 8, 3, 64)\n", "x = torch.randn(2, 3, 32, 32)\n", "print('Output:', pe(x).shape)\n", "print('Patches:', pe.num_patches)" ], "execution_count": null }, { "cell_type": "code", "metadata": {}, "outputs": [], "source": [ "# โœ… SUBMIT\n", "from torch_judge import check\n", "check('vit_patch')" ], "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 }