C.W.K.
Stream
Lesson 10 of 11 · published

requires_grad — Autograd 의 게이트웨이

~10 min · autograd, requires_grad, graph

Level 0Tensor 호기심
0 XP0/62 lessons0/13 achievements
0/120 XP to next level120 XP to go0% complete

Flag 하나가 전체 기계를 켜

requires_grad=True 는 PyTorch 에게 '이 tensor 봐 — 일어나는 모든 걸 기록해서 나중에 gradient 계산할 수 있게' 라고 말해. 계산기를 학습 기계로 바꾸는 single switch.

알아둘 세 가지:

  1. tensor default 는 requires_grad=False. opt-in 해야 함.
  2. op 의 아무 input 이 requires_grad=True 면, output 도 requires_grad=True — property 가 propagate.
  3. Model parameter (nn.Module 안의 nn.Parameter 통해 만들어진 것) 는 자동으로 requires_grad=True. 직접 설정할 일 거의 없음.

tensor 의 grad_fn attribute 가 어떤 op 가 만들었는지 알려줘 (있으면). Leaf tensor — 직접 만든 것 — 는 grad_fn=None. Intermediate 는 <AddBackward0>, <MulBackward0> 같은 거. 다음 트랙에서 autograd 제대로 다룰 거야; 지금은 requires_grad=True 가 문이고, 문은 너 또는 너 대신 nn.Parameter 가 연다는 것만 알아둬.

Code

requires_grad toggle 과 inheritance·python
import torch

t = torch.tensor([1.0, 2.0, 3.0])
print(t.requires_grad)  # False (default)

# Two ways to enable
t = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
t.requires_grad_(True)         # in-place version, with the underscore

# Inheritance: any op involving a tracked tensor produces a tracked tensor
y = t * 2 + 1
print(y.requires_grad)  # True
print(y.grad_fn)        # <AddBackward0>
nn.Parameter 가 대신 해줌·python
import torch
import torch.nn as nn

linear = nn.Linear(10, 4)
for name, p in linear.named_parameters():
    print(name, p.requires_grad, type(p).__name__)
# weight True Parameter
# bias   True Parameter

# nn.Parameter is a subclass of Tensor that:
#   - sets requires_grad=True
#   - registers itself with the parent nn.Module so it appears in .parameters()
transfer learning 위한 parameter freeze·python
import torch.nn as nn
from torchvision.models import resnet18, ResNet18_Weights

model = resnet18(weights=ResNet18_Weights.DEFAULT)

# Freeze the backbone
for p in model.parameters():
    p.requires_grad = False

# Replace the head with a fresh layer (which is unfrozen by default)
model.fc = nn.Linear(model.fc.in_features, 5)

trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"Trainable params: {trainable:,}")
# Trainable params: 2,565  (only the new head)

External links

Exercise

pretrained resnet18 잡기. 마지막 layer 빼고 모든 layer freeze. trainable parameter 수를 freeze 전후로 print. 그 다음 layer4 도 unfreeze 하고 새 count print. 'feature extraction' 과 'fine-tuning' 의 차이가 그 두 숫자 사이에 살아.

Progress

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

댓글 0

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

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