Python / PyTorch Fundamentals Interview Questions
What is torch.compile() and how does it speed up PyTorch model execution?
Introduced in PyTorch 2.0, torch.compile() performs just-in-time compilation of a model. Instead of executing each tensor operation eagerly (PyTorch's default), it captures the computation graph, fuses operations, and generates optimised kernels — primarily reducing GPU memory round-trips.
import torch
import torch.nn as nn
import time
model = nn.Sequential(
nn.Linear(1024, 1024), nn.GELU(),
nn.Linear(1024, 512), nn.GELU(),
nn.Linear(512, 10),
).cuda()
# Compile the model — wraps it, does NOT change the API
compiled_model = torch.compile(model)
x = torch.randn(256, 1024).cuda()
# First call triggers compilation (slow — may take 10-60 seconds)
out = compiled_model(x)
# Subsequent calls use the compiled, optimised kernels (fast)
for _ in range(5):
out = compiled_model(x)
# Compilation modes — trade compile time for runtime speed
model_default = torch.compile(model) # balanced
model_reduce = torch.compile(model, mode="reduce-overhead") # less Python overhead
model_max = torch.compile(model, mode="max-autotune") # slowest compile, fastest run
# Benchmark comparison
def benchmark(fn, x, n=100):
for _ in range(5): fn(x) # warmup
torch.cuda.synchronize()
start = time.time()
for _ in range(n): fn(x)
torch.cuda.synchronize()
return time.time() - start
eager_time = benchmark(model, x)
compiled_time = benchmark(compiled_model, x)
print(f"Eager: {eager_time:.3f}s, Compiled: {compiled_time:.3f}s")
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...
