C.W.K.
Stream
Lesson 05 of 06 · published

Gradient accumulation

~8 min · custom-train

Level 0Keras 도제
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

큰 effective batch size 가 필요한데 GPU 메모리 부족 — 작은 batch 로 forward/backward 여러 번, gradient 누적, 한 번에 step. 효과적 batch size = micro_batch × accumulate_steps.

train_step 안에서 self.accumulated_grads 같은 list 로 누적, accumulate_steps 도달 시 apply_gradients + reset. small VRAM 으로도 large-batch effect — vision transformer fine-tune 의 표준 트릭.

Code

accumulation_steps = 4  # Effective batch = batch_size × 4

for step, (x, y) in enumerate(dataset):
    # Compute gradients
    y_pred = model(x, training=True)
    loss = loss_fn(y, y_pred) / accumulation_steps

    grads = optimizer.compute_gradients(
        loss, model.trainable_variables
    )

    # Accumulate
    if step % accumulation_steps == 0:
        accumulated_grads = grads
    else:
        accumulated_grads = [
            (a + g) for a, g in zip(accumulated_grads, grads)
        ]

    # Apply every N steps
    if (step + 1) % accumulation_steps == 0:
        optimizer.apply(accumulated_grads)

External links

Exercise

동작하는 CIFAR-10 모델에 custom train_step 으로 gradient accumulation 구현 (4 micro-batch 누적 후 apply). 4 배 큰 batch 학습과 동작 일치하는지 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.