Python / Python Deep Learning and Neural Networks Interview Questions
What is the difference between model.eval(), torch.no_grad(), and torch.inference_mode()? When do you use each?
These three mechanisms serve different but complementary purposes that are often confused. Understanding the distinction prevents subtle bugs in training, validation, and inference code.
| Mechanism | What it controls | Effect |
|---|---|---|
| model.eval() | Layer behaviour (Dropout, BatchNorm) | Disables Dropout; BatchNorm uses running stats instead of batch stats |
| model.train() | Layer behaviour (Dropout, BatchNorm) | Enables Dropout; BatchNorm uses current batch stats |
| torch.no_grad() | Gradient tracking | Stops building the computation graph; saves memory; tensors cannot call .backward() |
| torch.inference_mode() | Gradient tracking + view tracking | Stricter than no_grad; ~10% faster; returned tensors cannot be used in autograd at all |
import torch
import torch.nn as nn
model = nn.Sequential(
nn.Linear(10, 64), nn.ReLU(),
nn.BatchNorm1d(64), nn.Dropout(0.5),
nn.Linear(64, 1)
)
# ─── Training ───────────────────────────────────────────────────────
model.train() # Dropout ACTIVE, BatchNorm uses batch stats
x = torch.randn(32, 10)
out1 = model(x)
out2 = model(x) # DIFFERENT — Dropout randomly drops each call
# ─── Validation (compute val loss, need backward later? No) ─────────
model.eval()
with torch.no_grad():
# Dropout OFF, BatchNorm uses running stats, no computation graph
val_out = model(x)
val_loss = nn.MSELoss()(val_out, torch.zeros(32, 1))
# ─── Inference / deployment ─────────────────────────────────────────
model.eval()
with torch.inference_mode(): # fastest; cannot go back to autograd
pred = model(torch.randn(1, 10))
# COMMON BUG: forgetting model.eval() at inference
# model.eval() and torch.no_grad() are INDEPENDENT — you need BOTH:
# - model.eval() alone: still builds graph (memory waste)
# - torch.no_grad() alone: Dropout still active (wrong predictions)
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
