CoolFace
Apppublic

YiwenC/TorchCode

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
App README

<div align="center">

๐Ÿ”ฅ TorchCode

Crack the PyTorch interview.

Practice implementing operators and architectures from scratch โ€” the exact skills top ML teams test for.

Like LeetCode, but for tensors. Self-hosted. Jupyter-based. Instant feedback.

![PyTorch](https://pytorch.org) ![Jupyter](https://jupyter.org) ![Docker](https://www.docker.com) ![Python](https://python.org) ![License: MIT](LICENSE)

![GitHub Container Registry](https://ghcr.io/duoan/torchcode) ![Hugging Face Spaces](https://huggingface.co/spaces/duoan/TorchCode) Problems GPU

</div>


๐ŸŽฏ Why TorchCode?

Top companies (Meta, Google DeepMind, OpenAI, etc.) expect ML engineers to implement core operations from memory on a whiteboard. Reading papers isn't enough โ€” you need to write softmax, LayerNorm, MultiHeadAttention, and full Transformer blocks cold.

TorchCode gives you a structured practice environment with:

Feature
๐Ÿงฉ13 curated problemsThe most frequently asked PyTorch interview topics
โš–๏ธAutomated judgeCorrectness checks, gradient verification, and timing
๐ŸŽจInstant feedbackColored pass/fail per test case, just like competitive programming
๐Ÿ’กHints when stuckNudges without full spoilers
๐Ÿ“–Reference solutionsStudy optimal implementations after your attempt
๐Ÿ“ŠProgress trackingWhat you've solved, best times, and attempt counts

No cloud. No signup. No GPU needed. Just make run โ€” or try it instantly on Hugging Face.


๐Ÿš€ Quick Start

Option 0 โ€” Try it online (zero install)

[Launch on Hugging Face Spaces](https://huggingface.co/spaces/duoan/TorchCode) โ€” opens a full JupyterLab environment in your browser. Nothing to install.

Option 1 โ€” Pull the pre-built image (fastest)

bash
docker run -p 8888:8888 -e PORT=8888 ghcr.io/duoan/torchcode:latest

Option 2 โ€” Build locally

bash
make run

Open <http://localhost:8888> โ€” that's it. Works with both Docker and Podman (auto-detected).


๐Ÿ“‹ Problem Set

๐Ÿงฑ Fundamentals โ€” "Implement X from scratch"

The bread and butter of ML coding interviews. You'll be asked to write these without torch.nn.

#ProblemWhat You'll ImplementDifficultyKey Concepts
1ReLUrelu(x)EasyActivation functions, element-wise ops
2Softmaxmy_softmax(x, dim)EasyNumerical stability, exp/log tricks
3Linear LayerSimpleLinear (nn.Module)Mediumy = xW^T + b, Kaiming init, nn.Parameter
4LayerNormmy_layer_norm(x, ฮณ, ฮฒ)MediumNormalization, running stats, affine transform
7BatchNormmy_batch_norm(x, ฮณ, ฮฒ)MediumBatch vs layer statistics, train/eval behavior
8RMSNormrms_norm(x, weight)MediumLLaMA-style norm, simpler than LayerNorm

๐Ÿง  Attention Mechanisms โ€” The heart of modern ML interviews

If you're interviewing for any role touching LLMs or Transformers, expect at least one of these.

#ProblemWhat You'll ImplementDifficultyKey Concepts
5Scaled Dot-Product Attentionscaled_dot_product_attention(Q, K, V)Hardsoftmax(QK^T/โˆšd_k)V, the foundation of everything
6Multi-Head AttentionMultiHeadAttention (nn.Module)HardParallel heads, split/concat, projection matrices
9Causal Self-Attentioncausal_attention(Q, K, V)HardAutoregressive masking with -inf, GPT-style
10Grouped Query AttentionGroupQueryAttention (nn.Module)HardGQA (LLaMA 2), KV sharing across heads
11Sliding Window Attentionsliding_window_attention(Q, K, V, w)HardMistral-style local attention, O(nยทw) complexity
12Linear Attentionlinear_attention(Q, K, V)HardKernel trick, ฯ†(Q)(ฯ†(K)^TV), O(nยทdยฒ)

๐Ÿ—๏ธ Full Architecture โ€” Put it all together

#ProblemWhat You'll ImplementDifficultyKey Concepts
13GPT-2 BlockGPT2Block (nn.Module)HardPre-norm, causal MHA + MLP (4x, GELU), residual connections

โš™๏ธ How It Works

Each problem has two notebooks:

FilePurpose
01_relu.ipynbโœ๏ธ Blank template โ€” write your code here
01_relu_solution.ipynb๐Ÿ“– Reference solution โ€” check when stuck

Workflow

text
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

In-Notebook API

python
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

๐Ÿ“… Suggested Study Plan

Total: ~6โ€“8 hours spread across 2โ€“3 weeks. Perfect for interview prep on a deadline.
WeekFocusProblemsTime
1๐Ÿงฑ FoundationsReLU โ†’ Softmax โ†’ Linear โ†’ LayerNorm โ†’ BatchNorm โ†’ RMSNorm1โ€“2 hrs
2๐Ÿง  Attention Deep DiveSDPA โ†’ MHA โ†’ Causal โ†’ GQA โ†’ Sliding Window โ†’ Linear Attn3โ€“4 hrs
3๐Ÿ—๏ธ IntegrationGPT-2 Block + speed run (re-implement all, timed)1โ€“2 hrs

๐Ÿ›๏ธ Architecture

text
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚           Docker / Podman Container      โ”‚
โ”‚                                          โ”‚
โ”‚  JupyterLab (:8888)                      โ”‚
โ”‚    โ”œโ”€โ”€ templates/  (reset on each run)   โ”‚
โ”‚    โ”œโ”€โ”€ solutions/  (reference impl)      โ”‚
โ”‚    โ”œโ”€โ”€ torch_judge/ (auto-grading)       โ”‚
โ”‚    โ””โ”€โ”€ PyTorch (CPU), NumPy              โ”‚
โ”‚                                          โ”‚
โ”‚  Judge checks:                           โ”‚
โ”‚    โœ“ Output correctness (allclose)       โ”‚
โ”‚    โœ“ Gradient flow (autograd)            โ”‚
โ”‚    โœ“ Shape consistency                   โ”‚
โ”‚    โœ“ Edge cases & numerical stability    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Single container. Single port. No database. No frontend framework. No GPU.

๐Ÿ› ๏ธ Commands

bash
make run    # Build & start (http://localhost:8888)
make stop   # Stop the container
make clean  # Stop + remove volumes + reset all progress

๐Ÿงฉ Adding Your Own Problems

TorchCode uses auto-discovery โ€” just drop a new file in torch_judge/tasks/:

python
TASK = {
    "id": "my_task",
    "title": "My Custom Problem",
    "difficulty": "medium",
    "function_name": "my_function",
    "hint": "Think about broadcasting...",
    "tests": [ ... ],
}

No registration needed. The judge picks it up automatically.


โ“ FAQ

<details> <summary><b>Do I need a GPU?</b></summary> <br> No. Everything runs on CPU. The problems test correctness and understanding, not throughput. </details>

<details> <summary><b>Can I keep my solutions between runs?</b></summary> <br> Blank templates reset on every <code>make run</code> so you practice from scratch. Save your work under a different filename if you want to keep it. </details>

<details> <summary><b>How are solutions graded?</b></summary> <br> The judge runs your function against multiple test cases using <code>torch.allclose</code> for numerical correctness, verifies gradients flow properly via autograd, and checks edge cases specific to each operation. </details>

<details> <summary><b>Who is this for?</b></summary> <br> Anyone preparing for ML/AI engineering interviews at top tech companies, or anyone who wants to deeply understand how PyTorch operations work under the hood. </details>


<div align="center">

Built for engineers who want to deeply understand what they build.

If this helped your interview prep, consider giving it a โญ

</div>