duoan/TorchCode

GitHub: duoan/TorchCode

面向机器学习工程师的 PyTorch 面试刷题平台,提供三十九道从基础算子到前沿架构的实战题目,支持自动评测和即时反馈。

Stars: 764 | Forks: 30

## 标题: TorchCode emoji: 🔥 colorFrom: red colorTo: yellow sdk: docker app_port: 7860 pinned: false
# 🔥 TorchCode **攻克 PyTorch 面试。** 练习从头实现算子和架构 —— 这正是顶级 ML 团队考察的技能。 *就像 LeetCode,只不过是针对张量的。可自托管。基于 Jupyter。即时反馈。* [![PyTorch](https://img.shields.io/badge/PyTorch-ee4c2c?style=for-the-badge&logo=pytorch&logoColor=white)](https://pytorch.org) [![Jupyter](https://img.shields.io/badge/Jupyter-F37626?style=for-the-badge&logo=jupyter&logoColor=white)](https://jupyter.org) [![Docker](https://img.shields.io/badge/Docker-2496ED?style=for-the-badge&logo=docker&logoColor=white)](https://www.docker.com) [![Python](https://img.shields.io/badge/Python_3.11-3776AB?style=for-the-badge&logo=python&logoColor=white)](https://python.org) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow?style=for-the-badge)](LICENSE) [![GitHub Container Registry](https://img.shields.io/badge/ghcr.io-TorchCode-blue?style=flat-square&logo=github)](https://ghcr.io/duoan/torchcode) [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Spaces-TorchCode-blue?style=flat-square)](https://huggingface.co/spaces/duoan/TorchCode) ![Problems](https://img.shields.io/badge/problems-39-orange?style=flat-square) ![GPU](https://img.shields.io/badge/GPU-not%20required-brightgreen?style=flat-square)
## 🎯 为什么选择 TorchCode? 顶级公司(Meta, Google DeepMind, OpenAI 等)期望 ML 工程师能**凭记忆在白板上**实现核心操作。光读论文是不够的 —— 你需要编写 `softmax`, `LayerNorm`, `MultiHeadAttention` 以及完整的 Transformer 代码块。 TorchCode 为你提供了一个**结构化的练习环境**,包含: | | 功能 | | |---|---|---| | 🧩 | **39 道精选题目** | PyTorch 面试中最常问到的主题 | | ⚖️ | **自动评测** | 正确性检查、梯度验证和计时 | | 🎨 | **即时反馈** | 每个测试用例都有彩色的通过/失败提示,就像竞技编程一样 | | 💡 | **卡住时的提示** | 提供指引而非完全剧透 | | 📖 | **参考解答** | 在尝试后学习最优实现 | | 📊 | **进度追踪** | 你解决了哪些题、最佳时间和尝试次数 | | 🔄 | **一键重置** | 工具栏按钮可将任何 notebook 重置回空白模板 —— 随心所欲地多次练习同一道题 | | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](#) | **在 Colab 中打开** | 每个 notebook 都有 "Open in Colab" 徽章 + 工具栏按钮 —— 在 Google Colab 中运行题目,零配置 | 无需云服务。无需注册。无需 GPU。只需 `make run` —— 或在 Hugging Face 上即时体验。 ## 🚀 快速开始 ### 选项 0 — 在线试用(零安装) **[在 Hugging Face Spaces 上启动](https://huggingface.co/spaces/duoan/TorchCode)** —— 在浏览器中打开完整的 JupyterLab 环境。无需安装任何东西。 或者直接在 Google Colab 中打开任何题目 —— 每个 notebook 都有一个 [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/duoan/TorchCode/blob/master/templates/01_relu.ipynb) 徽章。 ### 选项 1 — 拉取预构建镜像(最快) ``` docker run -p 8888:8888 -e PORT=8888 ghcr.io/duoan/torchcode:latest ``` ### 选项 2 — 本地构建 ``` make run ``` 打开 **** —— 就这么简单。同时支持 Docker 和 Podman(自动检测)。 ## 📋 题目集 ### 🧱 基础篇 — “从头实现 X” ML 编码面试的基本功。你会被要求在不使用 `torch.nn` 的情况下编写这些内容。 | # | 题目 | 你将实现的内容 | 难度 | 频率 | 核心概念 | |:---:|---------|----------------------|:----------:|:----:|--------------| | 1 | ReLU Open In Colab | `relu(x)` | ![Easy](https://img.shields.io/badge/Easy-4CAF50?style=flat-square) | 🔥 | 激活函数, 逐元素操作 | | 2 | Softmax Open In Colab | `my_softmax(x, dim)` | ![Easy](https://img.shields.io/badge/Easy-4CAF50?style=flat-square) | 🔥 | 数值稳定性, exp/log 技巧 | | 16 | Cross-Entropy Loss Open In Colab | `cross_entropy_loss(logits, targets)` | ![Easy](https://img.shields.io/badge/Easy-4CAF50?style=flat-square) | 🔥 | Log-softmax, logsumexp 技巧 | | 17 | Dropout Open In Colab | `MyDropout` (nn.Module) | ![Easy](https://img.shields.io/badge/Easy-4CAF50?style=flat-square) | 🔥 | 训练/评估模式, 倒数缩放 | | 18 | Embedding Open In Colab | `MyEmbedding` (nn.Module) | ![Easy](https://img.shields.io/badge/Easy-4CAF50?style=flat-square) | 🔥 | 查找表, `weight[indices]` | | 19 | GELU Open In Colab | `my_gelu(x)` | ![Easy](https://img.shields.io/badge/Easy-4CAF50?style=flat-square) | ⭐ | 高斯误差线性单元, `torch.erf` | | 20 | Kaiming Init Open In Colab | `kaiming_init(weight)` | ![Easy](https://img.shields.io/badge/Easy-4CAF50?style=flat-square) | ⭐ | `std = sqrt(2/fan_in)`, 方差缩放 | | 21 | Gradient Clipping Open In Colab | `clip_grad_norm(params, max_norm)` | ![Easy](https://img.shields.io/badge/Easy-4CAF50?style=flat-square) | ⭐ | 基于范数的裁剪, 保持方向 | | 31 | Gradient Accumulation Open In Colab | `accumulated_step(model, opt, ...)` | ![Easy](https://img.shields.io/badge/Easy-4CAF50?style=flat-square) | 💡 | 微批次, 损失缩放 | | 3 | Linear Layer Open In Colab | `SimpleLinear` (nn.Module) | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | 🔥 | `y = xW^T + b`, Kaiming 初始化, `nn.Parameter` | | 4 | LayerNorm Open In Colab | `my_layer_norm(x, γ, β)` | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | 🔥 | 归一化, 运行统计量, 仿射变换 | | 7 | BatchNorm Open In Colab | `my_batch_norm(x, γ, β)` | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | ⭐ | 批次与层统计量对比, 训练/评估行为 | | 8 | RMSNorm Open In Colab | `rms_norm(x, weight)` | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | ⭐ | LLaMA 风格归一化, 比 LayerNorm 更简单 | | 15 | SwiGLU MLP Open In Colab | `SwiGLUMLP` (nn.Module) | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | ⭐ | 门控 FFN, `SiLU(gate) * up`, LLaMA/Mistral 风格 | | 22 | Conv2d Open In Colab | `my_conv2d(x, weight, ...)` | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | 🔥 | 卷积, unfold, 步长/填充 | ### 🧠 注意力机制 — 现代 ML 面试的核心 如果你正在面试任何涉及 LLM 或 Transformers 的职位,至少会遇到其中一道题。 | # | 题目 | 你将实现的内容 | 难度 | 频率 | 核心概念 | |:---:|---------|----------------------|:----------:|:----:|--------------| | 23 | Cross-Attention Open In Colab | `MultiHeadCrossAttention` (nn.Module) | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | ⭐ | Encoder-decoder, Q 来自解码器, K/V 来自编码器 | | 5 | Scaled Dot-Product Attention Open In Colab | `scaled_dot_product_attention(Q, K, V)` | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 🔥 | `softmax(QK^T/√d_k)V`, 一切的基础 | | 6 | Multi-Head Attention Open In Colab | `MultiHeadAttention` (nn.Module) | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 🔥 | 并行头, 拆分/拼接, 投影矩阵 | | 9 | Causal Self-Attention Open In Colab | `causal_attention(Q, K, V)` | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 🔥 | 使用 `-inf` 的自回归掩码, GPT 风格 | | 10 | Grouped Query Attention Open In Colab | `GroupQueryAttention` (nn.Module) | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | ⭐ | GQA (LLaMA 2), 跨头 KV 共享 | | 11 | Sliding Window Attention Open In Colab | `sliding_window_attention(Q, K, V, w)` | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | ⭐ | Mistral 风格的局部注意力, O(n·w) 复杂度 | | 12 | Linear Attention Open In Colab | `linear_attention(Q, K, V)` | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 💡 | 核技巧, `φ(Q)(φ(K)^TV)`, O(n·d²) | | 14 | KV Cache Attention Open In Colab | `KVCacheAttention` (nn.Module) | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 🔥 | 增量解码, 缓存 K/V, prefill vs decode | | 24 | RoPE Open In Colab | `apply_rope(q, k)` | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 🔥 | 旋转位置嵌入, 通过旋转表示相对位置 | | 25 | Flash Attention Open In Colab | `flash_attention(Q, K, V, block_size)` | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 💡 | 分块注意力, 在线 softmax, 内存高效 | ### 🏗️ 架构与适应 — 整合所有内容 | # | 题目 | 你将实现的内容 | 难度 | 频率 | 核心概念 | |:---:|---------|----------------------|:----------:|:----:|--------------| | 26 | LoRA Open In Colab | `LoRALinear` (nn.Module) | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | ⭐ | 低秩适应, 冻结基座 + `BA` 更新 | | 27 | ViT Patch Embedding Open In Colab | `PatchEmbedding` (nn.Module) | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | 💡 | 图像 → 块 → 线性投影 | | 13 | GPT-2 Block Open In Colab | `GPT2Block` (nn.Module) | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | ⭐ | Pre-norm, 因果 MHA + MLP (4x, GELU), 残差连接 | | 28 | Mixture of Experts Open In Colab | `MixtureOfExperts` (nn.Module) | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | ⭐ | Mixtral 风格, top-k 路由, 专家 MLP | ### ⚙️ 训练与优化 | # | 题目 | 你将实现的内容 | 难度 | 频率 | 核心概念 | |:---:|---------|----------------------|:----------:|:----:|--------------| | 29 | Adam Optimizer Open In Colab | `MyAdam` | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | ⭐ | 动量 + RMSProp, 偏差修正 | | 30 |a href="https://github.com/duoan/TorchCode/blob/master/templates/30_cosine_lr.ipynb" target="_blank">Cosine LR Scheduler Open In Colab | `cosine_lr_schedule(step, ...)` | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | ⭐ | 线性预热 + 余弦退火 | ### 🎯 推理与解码 | # | 题目 | 你将实现的内容 | 难度 | 频率 | 核心概念 | |:---:|---------|----------------------|:----------:|:----:|--------------| | 32 | Top-k / Top-p Sampling Open In Colab | `sample_top_k_top_p(logits, ...)` | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | 🔥 | Nucleus 采样, 温度缩放 | | 33 | Beam Search Open In Colab | `beam_search(log_prob_fn, ...)` | ![Medium](https://img.shields.io/badge/Medium-FF9800?style=flat-square) | 🔥 | 假设扩展, 剪枝, eos 处理 | | 34 | Speculative Decoding Open In Colab | `speculative_decode(target, draft, ...)` | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 💡 | 接受/拒绝, 草稿模型加速 | ### 🔬 进阶篇 — 差异化亮点 | # | 题目 | 你将实现的内容 | 难度 | 频率 | 核心概念 | |:---:|---------|----------------------|:----------:|:----:|--------------| | 35 | BPE Tokenizer Open In Colab | `SimpleBPE` | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 💡 | 字节对编码, 合并规则, 子词拆分 | | 36 | INT8 Quantization Open In Colab | `Int8Linear` (nn.Module) | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 💡 | 逐通道量化, scale/zero-point, buffer vs param | | 37 | DPO Loss Open In Colab | `dpo_loss(chosen, rejected, ...)` | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 💡 | 直接偏好优化, 对齐训练 | | 38 | GRPO Loss Open In Colab | `grpo_loss(logps, rewards, group_ids, eps)` | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 💡 | 组相对策略优化, RLAIF, 组内归一化优势 | | 39 | PPO Loss Open In Colab | `ppo_loss(new_logps, old_logps, advantages, clip_ratio)` | ![Hard](https://img.shields.io/badge/Hard-F44336?style=flat-square) | 💡 | PPO 裁剪代理损失, 策略梯度, 信赖域 | ## ⚙️ 运作原理 每道题有 **两个** notebook: | 文件 | 用途 | |------|---------| | `01_relu.ipynb` | ✏️ 空白模板 —— 在这里编写你的代码 | | `01_relu_solution.ipynb` | 📖 参考解答 —— 卡住时查看 | ### 工作流程 ``` 1. Open a blank notebook → Read the problem description 2. Implement your solution → Use only basic PyTorch ops 3. Debug freely → print(x.shape), check gradients, etc. 4. Run the judge cell → check("relu") 5. See instant colored feedback → ✅ pass / ❌ fail per test case 6. Stuck? Get a nudge → hint("relu") 7. Review the reference solution → 01_relu_solution.ipynb 8. Click 🔄 Reset in the toolbar → Blank slate — practice again! ``` ### Notebook 内 API ``` from torch_judge import check, hint, status check("relu") # Judge your implementation hint("causal_attention") # Get a hint without full spoiler status() # Progress dashboard — solved / attempted / todo ``` ## 📅 建议学习计划 | 周次 | 重点 | 题目 | 时间 | |:----:|-------|----------|:----:| | **1** | 🧱 基础 | ReLU → Softmax → CE Loss → Dropout → Embedding → GELU → Linear → LayerNorm → BatchNorm → RMSNorm → SwiGLU MLP → Conv2d | 2–3 小时 | | **2** | 🧠 注意力深入 | SDPA → MHA → Cross-Attn → Causal → GQA → KV Cache → Sliding Window → RoPE → Linear Attn → Flash Attn | 3–4 小时 | | **3** | 🏗️ 架构 + 训练 | GPT-2 Block → LoRA → MoE → ViT Patch → Adam → Cosine LR → Grad Clip → Grad Accumulation → Kaiming Init | 3–4 小时 | | **4** | 🎯 推理 + 进阶 | Top-k/p Sampling → Beam Search → Speculative Decoding → BPE → INT8 Quant → DPO Loss → GRPO Loss → PPO Loss + 速通 | 3–4 小时 | ## 🏛️ 架构 ``` ┌──────────────────────────────────────────┐ │ Docker / Podman Container │ │ │ │ JupyterLab (:8888) │ │ ├── templates/ (reset on each run) │ │ ├── solutions/ (reference impl) │ │ ├── torch_judge/ (auto-grading) │ │ ├── torchcode-labext (JLab plugin) │ │ │ 🔄 Reset — restore template │ │ │ 🔗 Colab — open in Colab │ │ └── PyTorch (CPU), NumPy │ │ │ │ Judge checks: │ │ ✓ Output correctness (allclose) │ │ ✓ Gradient flow (autograd) │ │ ✓ Shape consistency │ │ ✓ Edge cases & numerical stability │ └──────────────────────────────────────────┘ ``` 单容器。单端口。无数据库。无前端框架。无 GPU。 ## 🛠️ 命令 ``` make run # Build & start (http://localhost:8888) make stop # Stop the container make clean # Stop + remove volumes + reset all progress ``` ## 🧩 添加自定义题目 TorchCode 采用自动发现机制 —— 只需在 `torch_judge/tasks/` 中放入一个新文件: ``` TASK = { "id": "my_task", "title": "My Custom Problem", "difficulty": "medium", "function_name": "my_function", "hint": "Think about broadcasting...", "tests": [ ... ], } ``` 无需注册。评测器会自动识别。 ## ❓ 常见问题
我需要 GPU 吗?
不需要。所有内容都在 CPU 上运行。这些题目测试的是正确性和理解程度,而非吞吐量。
我可以在运行之间保留我的解答吗?
空白模板在每次 make run 时都会重置,以便你从头练习。如果你想保留你的作品,请将其保存在不同的文件名下。你也可以随时点击 notebook 工具栏中的 🔄 Reset 按钮来恢复空白模板,而无需重启。
我可以改用 Google Colab 吗?
可以!每个 notebook 顶部都有一个 Open in Colab 徽章。点击它可直接在 Google Colab 中打开题目 —— 无需 Docker 或本地设置。你也可以使用 JupyterLab 内部的 Colab 工具栏按钮。
解答如何评分?
评测器使用 torch.allclose 对你的函数进行多个测试用例的数值正确性检查,通过 autograd 验证梯度是否正确流动,并检查每个操作特有的边缘情况。
这是给谁用的?
任何准备顶级科技公司 ML/AI 工程师面试的人,或者任何想要深入理解 PyTorch 操作底层原理的人。
**为那些想要深入理解自己所构建内容的工程师而打造。** 如果这对你准备面试有所帮助,请考虑给个 ⭐
标签:Apex, DeepMind面试, DNS解析, Docker, GPT-2, Jupyter, LeetCode, Meta面试, Python, PyTorch, Softmax, Transformer, 代码练习, 凭据扫描, 在线试用, 大模型, 安全防御评估, 开源项目, 张量操作, 教育平台, 无后门, 机器学习, 求职, 注意力机制, 深度学习, 白板编程, 算法实现, 自动评分, 自托管, 请求拦截, 逆向工具, 面试准备