Skip to content

Repository files navigation

titleTorchCode
emojiπŸ”₯
colorFromred
colorToyellow
sdkdocker
app_port7860
pinnedfalse

πŸ”₯ TorchCode

Crack the PyTorch interview.

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

An interactive coding platform, but for tensors. Self-hosted. Jupyter-based. Instant feedback.

PyTorchJupyterDockerPythonLicense: MIT

GitHub starsGitHub Container RegistryHugging Face SpacesProblemsGPU

Star History Chart


🎯 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 code.

TorchCode gives you a structured practice environment with:

Feature
🧩41 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
πŸ”„One-click resetToolbar button to reset any notebook back to its blank template β€” practice the same problem as many times as you want
Open In ColabOpen in ColabEvery notebook has an "Open in Colab" badge + toolbar button β€” run problems in Google Colab with zero setup

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 β€” opens a full JupyterLab environment in your browser. Nothing to install.

Or open any problem directly in Google Colab β€” every notebook has an Open In Colab badge.

Option 0b β€” Use the judge in Colab (pip)

In Google Colab, install the judge from PyPI so you can run check(...) without cloning the repo:

!pip install torch-judge

Then in a notebook cell:

fromtorch_judgeimportcheck, status, hint, reset_progressstatus() # list all problems and your progresscheck("relu") # run tests for the "relu" taskhint("relu") # show a hint

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

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

If the registry image is unavailable for your platform, use Option 2 instead. This is the common path on Apple Silicon / arm64.

Option 2 β€” Build locally

make run

make run will try the prebuilt image first and automatically fall back to a local build when needed.

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

Option 3 β€” Standalone Web UI (Next.js + FastAPI)

For a modern, standalone coding experience with an integrated IDE and dual-pane layout:

  1. Start Backend (FastAPI):
    pip install -r api/requirements.txt
    python -m uvicorn api.main:app --port 8000 --reload
  2. Start Frontend (Next.js):
    cd web
    npm install
    npm run dev
  3. Open http://localhost:3000 in your browser.

TorchCode UI Preview


πŸ“‹ Problem Set

Frequency: πŸ”₯ = very likely in interviews, ⭐ = commonly asked, πŸ’‘ = emerging / differentiator

🧱 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 ImplementDifficultyFreqKey Concepts
1ReLUOpen In Colabrelu(x)EasyπŸ”₯Activation functions, element-wise ops
2SoftmaxOpen In Colabmy_softmax(x, dim)EasyπŸ”₯Numerical stability, exp/log tricks
16Cross-Entropy LossOpen In Colabcross_entropy_loss(logits, targets)EasyπŸ”₯Log-softmax, logsumexp trick
17DropoutOpen In ColabMyDropout (nn.Module)EasyπŸ”₯Train/eval mode, inverted scaling
18EmbeddingOpen In ColabMyEmbedding (nn.Module)EasyπŸ”₯Lookup table, weight[indices]
19GELUOpen In Colabmy_gelu(x)Easy⭐Gaussian error linear unit, torch.erf
20Kaiming InitOpen In Colabkaiming_init(weight)Easy⭐std = sqrt(2/fan_in), variance scaling
21Gradient ClippingOpen In Colabclip_grad_norm(params, max_norm)Easy⭐Norm-based clipping, direction preservation
31Gradient AccumulationOpen In Colabaccumulated_step(model, opt, ...)EasyπŸ’‘Micro-batching, loss scaling
40Linear RegressionOpen In ColabLinearRegression (3 methods)MediumπŸ”₯Normal equation, GD from scratch, nn.Linear
3Linear LayerOpen In ColabSimpleLinear (nn.Module)MediumπŸ”₯y = xW^T + b, Kaiming init, nn.Parameter
4LayerNormOpen In Colabmy_layer_norm(x, Ξ³, Ξ²)MediumπŸ”₯Normalization, running stats, affine transform
7BatchNormOpen In Colabmy_batch_norm(x, γ, β)Medium⭐Batch vs layer statistics, train/eval behavior
8RMSNormOpen In Colabrms_norm(x, weight)Medium⭐LLaMA-style norm, simpler than LayerNorm
15SwiGLU MLPOpen In ColabSwiGLUMLP (nn.Module)Medium⭐Gated FFN, SiLU(gate) * up, LLaMA/Mistral-style
22Conv2dOpen In Colabmy_conv2d(x, weight, ...)MediumπŸ”₯Convolution, unfold, stride/padding

🧠 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 ImplementDifficultyFreqKey Concepts
23Cross-AttentionOpen In ColabMultiHeadCrossAttention (nn.Module)Medium⭐Encoder-decoder, Q from decoder, K/V from encoder
5Scaled Dot-Product AttentionOpen In Colabscaled_dot_product_attention(Q, K, V)HardπŸ”₯softmax(QK^T/√d_k)V, the foundation of everything
6Multi-Head AttentionOpen In ColabMultiHeadAttention (nn.Module)HardπŸ”₯Parallel heads, split/concat, projection matrices
9Causal Self-AttentionOpen In Colabcausal_attention(Q, K, V)HardπŸ”₯Autoregressive masking with -inf, GPT-style
10Grouped Query AttentionOpen In ColabGroupQueryAttention (nn.Module)Hard⭐GQA (LLaMA 2), KV sharing across heads
11Sliding Window AttentionOpen In Colabsliding_window_attention(Q, K, V, w)Hard⭐Mistral-style local attention, O(n·w) complexity
12Linear AttentionOpen In Colablinear_attention(Q, K, V)HardπŸ’‘Kernel trick, Ο†(Q)(Ο†(K)^TV), O(nΒ·dΒ²)
14KV Cache AttentionOpen In ColabKVCacheAttention (nn.Module)HardπŸ”₯Incremental decoding, cache K/V, prefill vs decode
24RoPEOpen In Colabapply_rope(q, k)HardπŸ”₯Rotary position embedding, relative position via rotation
25Flash AttentionOpen In Colabflash_attention(Q, K, V, block_size)HardπŸ’‘Tiled attention, online softmax, memory-efficient

πŸ—οΈ Architecture & Adaptation β€” Put it all together

#ProblemWhat You'll ImplementDifficultyFreqKey Concepts
26LoRAOpen In ColabLoRALinear (nn.Module)Medium⭐Low-rank adaptation, frozen base + BA update
27ViT Patch EmbeddingOpen In ColabPatchEmbedding (nn.Module)MediumπŸ’‘Image β†’ patches β†’ linear projection
13GPT-2 BlockOpen In ColabGPT2Block (nn.Module)Hard⭐Pre-norm, causal MHA + MLP (4x, GELU), residual connections
28Mixture of ExpertsOpen In ColabMixtureOfExperts (nn.Module)Hard⭐Mixtral-style, top-k routing, expert MLPs

βš™οΈ Training & Optimization

#ProblemWhat You'll ImplementDifficultyFreqKey Concepts
29Adam OptimizerOpen In ColabMyAdamMedium⭐Momentum + RMSProp, bias correction
30Cosine LR SchedulerOpen In Colabcosine_lr_schedule(step, ...)Medium⭐Linear warmup + cosine annealing

🎯 Inference & Decoding

#ProblemWhat You'll ImplementDifficultyFreqKey Concepts
32Top-k / Top-p SamplingOpen In Colabsample_top_k_top_p(logits, ...)MediumπŸ”₯Nucleus sampling, temperature scaling
33Beam SearchOpen In Colabbeam_search(log_prob_fn, ...)MediumπŸ”₯Hypothesis expansion, pruning, eos handling
34Speculative DecodingOpen In Colabspeculative_decode(target, draft, ...)HardπŸ’‘Accept/reject, draft model acceleration

πŸ”¬ Advanced β€” Differentiators

#ProblemWhat You'll ImplementDifficultyFreqKey Concepts
35BPE TokenizerOpen In ColabSimpleBPEHardπŸ’‘Byte-pair encoding, merge rules, subword splits
36INT8 QuantizationOpen In ColabInt8Linear (nn.Module)HardπŸ’‘Per-channel quantize, scale/zero-point, buffer vs param
37DPO LossOpen In Colabdpo_loss(chosen, rejected, ...)HardπŸ’‘Direct preference optimization, alignment training
38GRPO LossOpen In Colabgrpo_loss(logps, rewards, group_ids, eps)HardπŸ’‘Group relative policy optimization, RLAIF, within-group normalized advantages
39PPO LossOpen In Colabppo_loss(new_logps, old_logps, advantages, clip_ratio)HardπŸ’‘PPO clipped surrogate loss, policy gradient, trust region
41OPD LossOpen In Colabopd_loss(student_logits, teacher_logits, ...)HardπŸ’‘On-policy distillation, reverse KL, multi-teacher alignment

βš™οΈ 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

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!

In-Notebook API

fromtorch_judgeimportcheck, hint, statuscheck("relu") # Judge your implementationhint("causal_attention") # Get a hint without full spoilerstatus() # Progress dashboard β€” solved / attempted / todo

πŸ“… Suggested Study Plan

Total: ~12–16 hours spread across 3–4 weeks. Perfect for interview prep on a deadline.

WeekFocusProblemsTime
1🧱 FoundationsReLU β†’ Softmax β†’ CE Loss β†’ Dropout β†’ Embedding β†’ GELU β†’ Linear β†’ LayerNorm β†’ BatchNorm β†’ RMSNorm β†’ SwiGLU MLP β†’ Conv2d2–3 hrs
2🧠 Attention Deep DiveSDPA β†’ MHA β†’ Cross-Attn β†’ Causal β†’ GQA β†’ KV Cache β†’ Sliding Window β†’ RoPE β†’ Linear Attn β†’ Flash Attn3–4 hrs
3πŸ—οΈ Architecture + TrainingGPT-2 Block β†’ LoRA β†’ MoE β†’ ViT Patch β†’ Adam β†’ Cosine LR β†’ Grad Clip β†’ Grad Accumulation β†’ Kaiming Init3–4 hrs
4🎯 Inference + AdvancedTop-k/p Sampling β†’ Beam Search β†’ Speculative Decoding β†’ BPE β†’ INT8 Quant β†’ DPO Loss β†’ GRPO Loss β†’ PPO Loss β†’ OPD Loss + speed run3–4 hrs

πŸ›οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ 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 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

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

πŸ› οΈ Commands

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/:

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.


πŸ“¦ Publishing torch-judge to PyPI (maintainers)

The judge is published as a separate package so Colab/users can pip install torch-judge without cloning the repo.

Automatic (GitHub Action)

Pushing to master after changing the package version triggers .github/workflows/pypi-publish.yml, which builds and uploads to PyPI. No git tag is required.

  1. Bump version in torch_judge/_version.py (e.g. __version__ = "0.1.1").
  2. Configure PyPI Trusted Publisher (one-time):
    • PyPI β†’ Your project torch-judge β†’ Publishing β†’ Add a new pending publisher
    • Owner: duoan, Repository: TorchCode, Workflow: pypi-publish.yml, Environment: (leave empty)
    • Run the workflow once (push a version bump to master or Actions β†’ Publish torch-judge to PyPI β†’ Run workflow); PyPI will then link the publisher.
  3. Release: commit the version bump and git push origin master.

Alternatively, use an API token: add repository secret PYPI_API_TOKEN (value = pypi-... from PyPI) and set TWINE_USERNAME=__token__ and TWINE_PASSWORD from that secret in the workflow if you prefer not to use Trusted Publishing.

Manual

pip install build twine
python -m build
twine upload dist/*

Version is in torch_judge/_version.py; bump it before each release.


❓ FAQ

Do I need a GPU?
No. Everything runs on CPU. The problems test correctness and understanding, not throughput.
Can I keep my solutions between runs?
Blank templates reset on every make run so you practice from scratch. Save your work under a different filename if you want to keep it. You can also click the πŸ”„ Reset button in the notebook toolbar at any time to restore the blank template without restarting.
Can I use Google Colab instead?
Yes! Every notebook has an Open in Colab badge at the top. Click it to open the problem directly in Google Colab β€” no Docker or local setup needed. You can also use the Colab toolbar button inside JupyterLab.
How are solutions graded?
The judge runs your function against multiple test cases using torch.allclose for numerical correctness, verifies gradients flow properly via autograd, and checks edge cases specific to each operation.
Who is this for?
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.

🀝 Contributors

Thanks to everyone who has contributed to TorchCode.

duoan
duoan
Ando233
Ando233
abhijitmjj
abhijitmjj
laitifranz
laitifranz
hrlics
hrlics
HareshKarnan
HareshKarnan
ThierryHJ
ThierryHJ
Zuozhuo
Zuozhuo
reidemeister94
reidemeister94

Auto-generated from the GitHub contributors graph with avatars and GitHub usernames.


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

If this helped your interview prep, consider giving it a ⭐


β˜• Buy Me a Coffee

Buy Me A Coffee

BMC QR Code

Scan to support

About

πŸ”₯ LeetCode for PyTorch β€” practice implementing softmax, attention, GPT-2 and more from scratch with instant auto-grading. Jupyter-based, self-hosted or try online.

Topics

Resources

Stars

4.6k stars

Watchers

9 watching

Forks

Releases

Packages

Contributors

Languages