πŸ€– AI/ML

Training

Training / Learning

The process by which a model learns from data. In contrast to inference, it is a core stage of AI development.

πŸ“– Detailed Explanation

Training is the process by which a machine learning model learns patterns from data and adjusts its weights. The model compares input data with the correct answers (labels) and updates its parameters in the direction that minimizes the loss. This is a concept contrasted with the Inference stage.

Deep learning training is carried out through the Backpropagation algorithm. Proposed in 1986 by Rumelhart, Hinton, and Williams, this method propagates the error from the output layer toward the input layer and computes the gradient of each weight. Optimizers such as SGD and Adam then use these gradients to update the weights.

Training is divided into Pre-training and Fine-tuning. Large models such as GPT and BERT are first pre-trained on large-scale data and then fine-tuned for specific tasks. This two-stage approach has become the standard in modern AI.

In practice, training requires considering multiple factors such as hardware resources like GPUs/TPUs, large-scale datasets, and hyperparameter tuning. Training a GPT-4-level model requires thousands of GPUs and costs millions of dollars, and techniques to make this more efficient, such as distributed training and mixed-precision training, are being actively researched.

πŸ’» Code Example

This is a basic Training Loop example using PyTorch.

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

# κ°„λ‹¨ν•œ 신경망 μ •μ˜
class SimpleNN(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(input_dim, hidden_dim),
            nn.ReLU(),
            nn.Dropout(0.2),
            nn.Linear(hidden_dim, output_dim)
        )

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

# 데이터 μ€€λΉ„ (μ˜ˆμ‹œ)
X = torch.randn(1000, 10)  # 1000개 μƒ˜ν”Œ, 10개 νŠΉμ„±
y = torch.randint(0, 2, (1000,))  # 이진 λΆ„λ₯˜

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

# λͺ¨λΈ, μ†μ‹€ν•¨μˆ˜, μ˜΅ν‹°λ§ˆμ΄μ € μ„€μ •
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = SimpleNN(input_dim=10, hidden_dim=64, output_dim=2).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# Training Loop
num_epochs = 10
for epoch in range(num_epochs):
    model.train()  # ν›ˆλ ¨ λͺ¨λ“œ
    total_loss = 0
    correct = 0

    for batch_X, batch_y in train_loader:
        batch_X, batch_y = batch_X.to(device), batch_y.to(device)

        # Forward pass
        outputs = model(batch_X)
        loss = criterion(outputs, batch_y)

        # Backward pass
        optimizer.zero_grad()  # 기울기 μ΄ˆκΈ°ν™”
        loss.backward()        # μ—­μ „νŒŒ
        optimizer.step()       # κ°€μ€‘μΉ˜ μ—…λ°μ΄νŠΈ

        total_loss += loss.item()
        correct += (outputs.argmax(dim=1) == batch_y).sum().item()

    accuracy = correct / len(dataset) * 100
    print(f"Epoch [{epoch+1}/{num_epochs}] "
          f"Loss: {total_loss/len(train_loader):.4f} "
          f"Accuracy: {accuracy:.2f}%")

# λͺ¨λΈ μ €μž₯
torch.save(model.state_dict(), "model.pth")
print("Training complete! Model saved.")

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

πŸ’¬ In a Meeting
"For this model's Training, we expect about 3 days on 8 A100s. We'll save a checkpoint every epoch, and upload the final model to S3."
πŸ’¬ In an Interview
"I have experience with large-scale model Training. I used DeepSpeed ZeRO-3 to train a 70B-parameter model in a distributed manner across 8 GPUs."
πŸ’¬ In a Technical Discussion
"During Training, increasing the gradient accumulation steps raises the effective batch size, which stabilizes learning. However, convergence speed may become slightly slower."

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

⚠️ Common Mistakes & Cautions

❌

Neglecting Overfitting

If you ignore the signal that only the Training loss decreases while the Validation loss rises, generalization performance degrades. Use Early stopping.

❌

Setting the Learning rate incorrectly

If it is too large, it diverges, and if it is too small, convergence is slow. Use a Learning rate scheduler or warmup.

βœ…

The right way

Make Train/Val/Test splitting, checkpoint saving, experiment logging (WandB, TensorBoard), and fixing the seed for reproducibility your baseline.

πŸ”— Related Terms

πŸ“š Learn More