C.W.K.
Stream
Lesson 07 of 08 · published

Forward Pass

~22 min · forward, shapes, autograd

Level 0Curious
0 XP0/73 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

Forward 가 실제 뭘 의미하나

Forward pass 는 input data x 를 모든 layer 통과시켜 순서대로 output y (logit, probability, embedding — head 가 반환하는 무엇이든) 를 만드는 행위. 도중에 PyTorch 가 모든 operation 을 computation graph 에 기록해서 backward 가 나중에 gradient 계산할 수 있게 해. 본인 forward() method 가 올바르게 해야 할 유일한 일이야.

forward()model(x) 할 때 자동 호출. 절대 model.forward(x) 직접 호출하지 마 — normalization mode, gradient tracking, DDP synchronization 같은 hook 을 건너뛰게 돼.

팁: forward() 쓰면, 모든 중간 tensor 의 shape 를 line 옆에 적어. 미래 본인 (그리고 본인 model 디버깅하는 다음 사람) 이 고마워할 거야.

Train mode vs eval mode

일부 layer 는 training 과 evaluation 에서 다르게 행동: dropout (train 에서 active, eval 에서 identity), batch normalization (train 에서 batch statistics, eval 에서 running statistics). model.train()model.eval() 로 switch. Validation 에서 eval() 잊는 게 noisy metric 만드는 유명한 버그 — training-loop track 에서 다시 볼 거야.

Gradient 필요 없으면 멈춰

Inference 와 transfer learning 의 frozen backbone 에는 forward call 을 torch.no_grad() (또는 latest, fastest path 인 torch.inference_mode()) 로 wrap. PyTorch 가 computation graph 안 만들고 묶였을 memory 풀어줘.

원칙: Forward 에 대해 기억할 3 가지: .forward() 가 아니라 model 호출, inference 에 eval() switch, gradient 필요 없을 때 inference_mode() 사용.

Code

A complete, shape-annotated forward pass·python
import torch, torch.nn as nn

class TinyVisionMLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.fc1 = nn.Linear(28 * 28, 256)
        self.act = nn.ReLU()
        self.dropout = nn.Dropout(p=0.1)
        self.fc2 = nn.Linear(256, 10)
    def forward(self, x):              # x:    [B, 1, 28, 28]
        x = self.flatten(x)            # x:    [B, 784]
        x = self.act(self.fc1(x))      # x:    [B, 256]
        x = self.dropout(x)            # x:    [B, 256]
        return self.fc2(x)             # logits: [B, 10]

model = TinyVisionMLP()
batch = torch.randn(32, 1, 28, 28)

model.train()
logits_train = model(batch)

model.eval()
with torch.inference_mode():
    logits_eval = model(batch)

print(logits_train.shape, logits_eval.shape)

External links

Exercise

CIFAR-10 분류하는 3 layer MLP 의 forward pass 작성 (input shape [B, 3, 32, 32], output shape [B, 10]). 모든 중간 tensor shape 를 comment 에 annotate. Model 을 train 과 eval 사이 switch 하면서 dropout 이 mode 마다 다르게 행동하는지 확인.

Progress

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

댓글 0

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

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