🤖 AI/ML

Batch Size

Batch Size

The number of samples used in a single training step. Affects memory and training stability. A hyperparameter.

📖 Detailed Explanation

Batch Size is the number of training samples used in a single gradient update. Instead of processing the entire dataset at once, training proceeds sequentially on small groups (batches), and the size of each group is the batch size. It is one of the most important hyperparameters in deep learning.

Mini-batch gradient descent has been studied since the 1960s, but it became practically important only after GPU parallel processing became widespread in the 2010s. The key is balancing GPU memory and computational efficiency, and in recent large-scale model training, techniques that increase the effective batch size through gradient accumulation and distributed training have become standard.

Batch size has a profound effect on training dynamics. Small batches (32 or fewer) are noisy, which favors generalization, but training is unstable; large batches (1024 or more) are stable but prone to falling into sharp minima. Theoretically, if you increase the batch size by a factor of N, you need to increase the learning rate by a factor of sqrt(N) to maintain similar training dynamics.

In practice, the common approach is to start with the largest batch size that GPU memory allows and reduce it if training instability appears. On a V100 16GB, a batch size of about 32 is appropriate for BERT-base, and 64-128 is appropriate on an A100 40GB. If memory is insufficient, you can use gradient accumulation to increase the effective batch size.

💻 Code Example

# Batch Size와 Gradient Accumulation 예제
import torch
from torch.utils.data import DataLoader, TensorDataset

# 1. 기본 DataLoader 설정
dataset = TensorDataset(
    torch.randn(1000, 10),  # 입력
    torch.randint(0, 2, (1000,))  # 레이블
)

# Batch size 설정
batch_size = 32
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)

print(f"데이터셋 크기: {len(dataset)}")
print(f"배치 크기: {batch_size}")
print(f"배치 수 (iterations per epoch): {len(dataloader)}")

# 2. Gradient Accumulation으로 Effective Batch Size 키우기
model = torch.nn.Linear(10, 2)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
criterion = torch.nn.CrossEntropyLoss()

# 실제 배치: 8, Accumulation steps: 4 -> Effective batch: 32
actual_batch_size = 8
accumulation_steps = 4
effective_batch_size = actual_batch_size * accumulation_steps

small_dataloader = DataLoader(dataset, batch_size=actual_batch_size, shuffle=True)

# 학습 루프
model.train()
optimizer.zero_grad()

for i, (inputs, labels) in enumerate(small_dataloader):
    outputs = model(inputs)
    loss = criterion(outputs, labels)

    # Gradient 누적을 위해 나누기
    loss = loss / accumulation_steps
    loss.backward()

    # accumulation_steps마다 업데이트
    if (i + 1) % accumulation_steps == 0:
        optimizer.step()
        optimizer.zero_grad()
        print(f"Step {(i+1)//accumulation_steps}: "
              f"Effective batch size = {effective_batch_size}")

    if i >= 15:  # 예시용 조기 종료
        break

# 3. 배치 크기에 따른 Learning Rate 스케일링
def get_scaled_lr(base_lr, base_batch_size, target_batch_size):
    """Linear scaling rule"""
    return base_lr * (target_batch_size / base_batch_size)

base_lr = 1e-3
base_batch = 32
target_batch = 256

scaled_lr = get_scaled_lr(base_lr, base_batch, target_batch)
print(f"\n배치 {base_batch} -> {target_batch}로 변경 시")
print(f"Learning rate: {base_lr} -> {scaled_lr}")

🗣️ Examples of Practical Conversations

In a discussion on resolving GPU memory errors

"If CUDA OOM appears, first try cutting the batch size in half. If that still doesn't work, turn on gradient checkpointing or apply mixed precision (FP16), which cuts memory use in half. When you reduce the batch, maintain the effective batch with gradient accumulation."

While debugging a training instability issue

"If the loss oscillates, the batch size is too small or the learning rate is too high. You can raise the batch from 32 to 128 and, following the linear scaling rule, raise the LR by 4x as well, or alternatively raise only the batch, keep the LR the same, and use a longer warmup."

In a technical interview

"There is research showing that training with large batches converges to sharp minima and degrades generalization performance. Solutions include using layer-wise adaptive learning rate methods such as LARS and LAMB, or giving a sufficient warmup. GPT-3 training also used batch size rampup, which gradually increases the batch size."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

📊 Recommended Batch Size Guide by GPU

GPU VRAM BERT-base ResNet-50 LLaMA 7B
RTX 3090 24GB 32 64 1 (QLoRA)
RTX 4090 24GB 32 64 2 (QLoRA)
A100 40/80GB 64~128 128~256 4~8
H100 80GB 128 256 8~16

💡 Practical Tip: When OOM occurs → reduce the batch by 50% or enable FP16/BF16. When you reduce the batch, maintain the effective batch with Gradient Accumulation. Recommended for BERT fine-tuning: 16~32; for LLMs: 1~4 (memory limit).

⚠️ Cautions

1
Interaction with BatchNorm

Batch Normalization uses batch statistics, so if the batch size is too small (8 or fewer), the estimates become unstable. For small batches, use GroupNorm or LayerNorm.

2
Learning Rate Adjustment Is Required

When you change the batch size, you must adjust the learning rate as well. If you increase the batch by a factor of N, increase the LR by a factor between sqrt(N) and N, and adjust the warmup steps accordingly.

3
Batch Size During Evaluation

During evaluation there is no gradient computation, so there is spare memory, which means you can set the evaluation batch size 2-4 times larger than for training. Doing so greatly improves evaluation speed.

🔗 Related Terms

📚 Learn More