[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-109698":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":14,"subscribersCount":14,"size":14,"stars1d":14,"stars7d":14,"stars30d":15,"stars90d":14,"forks30d":14,"starsTrendScore":14,"compositeScore":16,"rankGlobal":9,"rankLanguage":9,"license":17,"archived":18,"fork":18,"defaultBranch":19,"hasWiki":20,"hasPages":18,"topics":21,"createdAt":9,"pushedAt":29,"updatedAt":30,"readmeContent":31,"aiSummary":32,"trendingCount":14,"starSnapshotCount":14,"syncStatus":33,"lastSyncTime":34,"discoverSource":35},109698,"tiny-transformer-from-scratch","Zguoxu\u002Ftiny-transformer-from-scratch","Zguoxu","A tiny Transformer built from scratch in PyTorch, with an English-to-Chinese translation demo | 用 PyTorch 从零实现的小型 Transformer，附英译中演示，帮助理解模型原理",null,"Jupyter Notebook",103,4,101,0,1,42.2,"MIT License",false,"main",true,[22,23,24,25,26,27,28],"attention-mechanism","deep-learning","educational","from-scratch","machine-translation","pytorch","transformer","2026-11-02 04:04:24","2026-11-14 10:31:15","# Tiny Transformer from Scratch\n\n**English** | [简体中文](README.zh-CN.md)\n\n[![Open In Colab](https:\u002F\u002Fcolab.research.google.com\u002Fassets\u002Fcolab-badge.svg)](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FZguoxu\u002Ftiny-transformer-from-scratch\u002Fblob\u002Fmain\u002Ftiny_transformer.ipynb)\n\n**New to this? [Click here to run the demo in your browser](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FZguoxu\u002Ftiny-transformer-from-scratch\u002Fblob\u002Fmain\u002Ftiny_transformer.ipynb) — no local installation needed.**\n\nAfter opening Colab, sign in to Google and choose **Runtime → Run all**. Use a standard CPU runtime; no GPU is needed.\n\n**Understand how a Transformer translates English into Chinese—with a single Python file.**\n\nA small Transformer implemented from scratch in PyTorch, covering token embeddings, positional encoding, multi-head attention, the encoder and decoder, training, and autoregressive generation.\n\nNo `nn.Transformer` or `nn.MultiheadAttention`. Designed for learners who know the basics of PyTorch and want to follow the computations inside a Transformer.\n\n## Features\n\n- **One Python file**: data processing, the model, training, and translation all live in `transformer.py`.\n- **Core components implemented by hand**: scaled dot-product attention, multi-head attention, causal masking, and cross-attention.\n- **No dataset downloads**: 8 built-in English–Chinese sentence pairs, a model dimension of 32, 2 attention heads, 2 encoder layers, and 2 decoder layers.\n- **A complete workflow**: build vocabularies → train the model → save the loss curve → generate a Chinese translation.\n- **Chinese code comments**: explanations of key components and training steps for Chinese-speaking learners.\n\n## Architecture\n\n![Transformer encoder–decoder architecture](assets\u002Farchitecture.svg)\n\nThe encoder and decoder each stack two layers. In decoder cross-attention, queries come from the decoder, while keys and values come from the encoder output. Each attention and feed-forward sublayer uses a residual connection followed by layer normalization, matching the implementation.\n\n[Download PNG](assets\u002Farchitecture.png)\n\n## Example\n\nInput:\n\n```text\nthere is a black dog under the chair\n```\n\nOutput from an actual run:\n\n```text\n椅子下面有一只黑色狗\n```\n\nTraining log:\n\n```text\nEpoch   1 | loss=2.1297\nEpoch  20 | loss=0.0163\nEpoch  40 | loss=0.0050\nEpoch  60 | loss=0.0025\nEpoch  80 | loss=0.0015\nEpoch 100 | loss=0.0010\n```\n\n### Training loss\n\n![Transformer training loss over 100 epochs on the 8 built-in sentence pairs](assets\u002Floss_curve.png)\n\nThe horizontal axis shows training epochs. The vertical axis shows the average of the per-sentence cross-entropy losses within each epoch. Each run saves the curve to `assets\u002Floss_curve.png`.\n\nThis is a small learning demo with only 8 training pairs and fixed vocabularies. Input containing words outside the source vocabulary raises an error. The example input combines familiar training words in a new way; the sample output and low training loss do not demonstrate general translation ability. Results may vary slightly across environments.\n\n## Run in your browser\n\n1. [Click here to open the notebook in Google Colab](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FZguoxu\u002Ftiny-transformer-from-scratch\u002Fblob\u002Fmain\u002Ftiny_transformer.ipynb).\n2. Sign in to your Google account if prompted. A standard CPU runtime is enough.\n3. From the top menu, choose **Runtime → Run all** to execute the notebook from start to finish.\n4. Scroll down to see the training log, loss curve, and Chinese translation.\n5. In the final code cell, edit `english` using words from the displayed vocabulary, then click the **▶** button to its left to translate again.\n\nThe notebook includes explanations in English and Chinese. No local Python setup is needed.\n\n## Quick start\n\nVerified with Python 3.12. Requires PyTorch and Matplotlib.\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002FZguoxu\u002Ftiny-transformer-from-scratch.git\ncd tiny-transformer-from-scratch\npython -m venv .venv\n```\n\nActivate the virtual environment:\n\n```bash\n# macOS \u002F Linux\nsource .venv\u002Fbin\u002Factivate\n\n# Windows PowerShell\n.venv\\Scripts\\Activate.ps1\n```\n\nInstall dependencies and run:\n\n```bash\npython -m pip install -r requirements.txt\npython transformer.py\n```\n\nThe program trains for 100 epochs, then saves and displays the loss curve. **Close the plot window** to continue and see the translation in your terminal.\n\nTo save the plot and print the translation on a server without a graphical display, run (macOS \u002F Linux):\n\n```bash\nMPLBACKEND=Agg python transformer.py\n```\n\n## Suggested reading order\n\n| Step | Code | What to look for |\n| --- | --- | --- |\n| 1. Data and vocabularies | `en_cn_pairs`, `source_ids`, `target_ids` | Converting text to token IDs; the roles of BOS and EOS |\n| 2. Input representations | `TokenEmbedding`, `PositionalEncoding` | Adding token embeddings and sinusoidal positional encodings |\n| 3. Attention | `attention`, `AttentionHead`, `MultiHeadAttention` | Q, K, V, scaled dot products, and concatenating heads |\n| 4. Encoder | `EncoderLayer`, `Encoder` | Self-attention, feed-forward networks, residual connections, and layer normalization |\n| 5. Decoder | `DecoderLayer`, `Decoder` | Causal masking and cross-attention to encoder outputs |\n| 6. Complete model | `Transformer` | Encoding, decoding, and projecting to the target vocabulary |\n| 7. Training and generation | Training loop, `translate` | Shifted targets, cross-entropy, and greedy token-by-token generation |\n\n## Try it yourself\n\n- Change `HEADS` and compare training behavior. Make sure `D` is divisible by `HEADS`.\n- Change `NUM_LAYERS` to explore how model depth affects training.\n- Add sentence pairs to `en_cn_pairs`, then rerun to rebuild the vocabularies and train.\n- Edit the English input on the last line to try new combinations of words from the existing vocabulary.\n- Read the causal mask in `attention` to understand how the decoder avoids attending to future tokens.\n\n## Project structure\n\n```text\ntiny-transformer-from-scratch\u002F\n├── README.md\n├── README.zh-CN.md\n├── LICENSE\n├── tiny_transformer.ipynb\n├── transformer.py\n├── requirements.txt\n├── .gitignore\n└── assets\u002F\n    ├── architecture.svg\n    ├── architecture.png\n    └── loss_curve.png\n```\n\nIf this project helps you understand Transformers, give it a ⭐ Star so you can revisit it later. Questions and learning discussions are welcome in Issues.\n\n## License\n\nReleased under the [MIT License](LICENSE). You may use, modify, and redistribute this project, including commercially, provided you retain the copyright and license notices. The software is provided without warranty.\n","这是一个用 PyTorch 从零实现的极简 Transformer 模型，专为教学与原理理解设计。项目完整实现了词嵌入、位置编码、缩放点积注意力、多头注意力、因果掩码、交叉注意力、编码器-解码器结构及自回归翻译流程，所有组件均手动编写，不依赖 torch.nn.Transformer 等高层封装。内置 8 对英汉句对，支持端到端训练与推理，输出中文翻译结果，并可视化训练损失曲线。适用于深度学习初学者、NLP 教学演示及 Transformer 内部机制探究场景。",2,"2026-11-24 04:37:12","CREATED_QUERY"]