πŸ€– AI/ML

PyTorch

Facebook PyTorch

Facebook's deep learning framework. Dynamic computation graphs. The most popular in research.

πŸ“– Detailed Explanation

PyTorch is an open-source deep learning framework released in 2016 by the Facebook (now Meta) AI Research team. By combining Python's intuitive syntax with NumPy-style tensor operations, it greatly reduced the complexity of earlier deep learning frameworks. Thanks to its "Pythonic" design philosophy, it was quickly adopted by both researchers and developers, and it has now established itself as the most popular deep learning framework in academia.

PyTorch's core feature is the Dynamic Computational Graph. Whereas TensorFlow 1.x used a static graph, in which the entire model was defined first and then executed, PyTorch generates the graph immediately as the code runs. This is called the "Define-by-Run" approach; it makes debugging easy and allows conditionals and loops to be used freely, which is advantageous for implementing complex models. GPU acceleration is supported through the CUDA backend, and a tensor can be moved to the GPU with a single line, `.to('cuda')`.

The PyTorch ecosystem is very rich. There are domain-specific libraries such as TorchVision (computer vision), TorchText (natural language processing), and TorchAudio (speech processing), and it has been adopted as the default backend of Hugging Face Transformers, which has made it even more important in the LLM era. PyTorch Lightning reduces training-loop boilerplate, PyTorch Geometric supports graph neural networks, and torchserve supports model serving. `torch.compile()`, introduced in PyTorch 2.0 in 2022, automatically optimizes models and provides a 20-30% speedup.

There are also various ways to deploy PyTorch models in production environments. TorchScript allows models to run in C++ without a Python dependency, and models can be exported in ONNX format for inference in other frameworks. Recently, ExecuTorch has appeared and simplified deployment to mobile and edge devices. As a mature framework covering the entire cycle from training to deployment, PyTorch has become an essential skill for AI/ML engineers.

πŸ’» Code Example

This is the full pipeline for defining and training a simple neural network with PyTorch:

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset

# 1. λ””λ°”μ΄μŠ€ μ„€μ • (GPU κ°€μš©μ‹œ μžλ™ μ‚¬μš©)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")

# 2. κ°„λ‹¨ν•œ 신경망 μ •μ˜
class SimpleNet(nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(input_size, hidden_size),
            nn.ReLU(),
            nn.Dropout(0.2),
            nn.Linear(hidden_size, hidden_size),
            nn.ReLU(),
            nn.Linear(hidden_size, num_classes)
        )

    def forward(self, x):
        return self.layers(x)

# 3. 데이터 μ€€λΉ„ (μ˜ˆμ‹œ: 랜덀 데이터)
X = torch.randn(1000, 20)  # 1000개 μƒ˜ν”Œ, 20 features
y = torch.randint(0, 3, (1000,))  # 3 classes

dataset = TensorDataset(X, y)
train_loader = DataLoader(dataset, batch_size=32, shuffle=True)

# 4. λͺ¨λΈ, μ†μ‹€ν•¨μˆ˜, μ˜΅ν‹°λ§ˆμ΄μ € μ„€μ •
model = SimpleNet(input_size=20, hidden_size=64, num_classes=3).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# 5. ν•™μŠ΅ 루프
for epoch in range(10):
    model.train()
    total_loss = 0
    for batch_x, batch_y in train_loader:
        batch_x, batch_y = batch_x.to(device), batch_y.to(device)

        optimizer.zero_grad()
        outputs = model(batch_x)
        loss = criterion(outputs, batch_y)
        loss.backward()
        optimizer.step()

        total_loss += loss.item()

    print(f"Epoch {epoch+1}/10, Loss: {total_loss/len(train_loader):.4f}")

# 6. μΆ”λ‘ 
model.eval()
with torch.no_grad():
    sample = torch.randn(1, 20).to(device)
    prediction = model(sample)
    predicted_class = prediction.argmax(dim=1).item()
    print(f"Predicted class: {predicted_class}")

# 7. λͺ¨λΈ μ €μž₯ 및 λ‘œλ“œ
torch.save(model.state_dict(), "model.pt")
# λ‘œλ“œ: model.load_state_dict(torch.load("model.pt"))

# 8. PyTorch 2.0 torch.compile() μ΅œμ ν™” (선택적)
# compiled_model = torch.compile(model)  # 20-30% 속도 ν–₯상

How to implement it more cleanly with PyTorch Lightning:

import pytorch_lightning as pl
from torch.utils.data import DataLoader

class LitModel(pl.LightningModule):
    def __init__(self):
        super().__init__()
        self.model = SimpleNet(20, 64, 3)
        self.criterion = nn.CrossEntropyLoss()

    def training_step(self, batch, batch_idx):
        x, y = batch
        logits = self.model(x)
        loss = self.criterion(logits, y)
        self.log("train_loss", loss, prog_bar=True)
        return loss

    def configure_optimizers(self):
        return optim.Adam(self.parameters(), lr=0.001)

# ν•™μŠ΅ (GPU/TPU μžλ™ 지원, 체크포인트 μžλ™ μ €μž₯)
trainer = pl.Trainer(max_epochs=10, accelerator="auto")
trainer.fit(LitModel(), train_dataloaders=train_loader)

πŸ“Š Performance & Cost

Item Requirements / Cost
License BSD-3-Clause (completely free, commercial use allowed)
CPU Training Possible (small-scale models/datasets)
GPU recommended (Vision) RTX 3060 or higher (8GB VRAM)
GPU recommended (LLM) RTX 4090 / A100 (24-80GB VRAM)
Cloud cost (A100) $1.5~3/hr (AWS, GCP, Azure)
Cloud cost (RTX 4090) $0.4~0.8/hr (Lambda Labs, Vast.ai)
Apple Silicon MPS backend support (M1/M2/M3)

Tip: To reduce training costs, use Mixed Precision (fp16/bf16), Gradient Checkpointing, and DeepSpeed/FSDP distributed training. The free Google Colab tier is also sufficient for simple experiments.

πŸ—£οΈ Say It Like This in Practice

πŸ’Ό In Meetings

"We're planning to proceed with PyTorch for this project. Hugging Face models support PyTorch by default, and since the team members are also familiar with it, onboarding costs should be low."

πŸ‘” In Interviews

"Thanks to PyTorch's dynamic computational graph, I can set breakpoints and check tensor shapes when debugging just like in regular Python, so development productivity is high. With torch.compile() in 2.0, production performance has also improved considerably."

πŸ”§ In Technical Discussions

"When training large-scale models, PyTorch FSDP is simpler to configure than DeepSpeed. However, for memory profiling, Nsight Systems is more accurate than torch.cuda.memory_stats()."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Common Mistakes & Cautions

❌
Missing model.eval(): If you don't set eval() mode during inference, Dropout and BatchNorm operate in training mode, and the results will differ. Always use model.eval() together with torch.no_grad().
❌
Gradient accumulation: If you omit optimizer.zero_grad(), the gradients from the previous batch accumulate. Call zero_grad() at the start of every batch, or use the optimizer's set_to_none=True option.
βœ…
Best Practice: Match the device and dtype before tensor operations. Call tensor.to(device) and model.to(device) only once at initialization, and setting pin_memory=True in the DataLoader speeds up CPU-GPU transfers.

πŸ”— Related Terms

πŸ“š Learn More