본문 바로가기
C.W.K.
Stream
Lesson 10 of 11 · published

requires_grad: Autograd로 들어가는 문

~10 min · autograd, requires_grad, graph

Level 0텐서 탐구자
0 XP0/62 lessons0/13 achievements
0/120 XP to next level120 XP to go0% complete

표시 하나로 전체 기울기 추적을 켜

requires_grad=True는 PyTorch에 '이 텐서에서 일어나는 연산을 기록해 두었다가 나중에 기울기를 계산해 줘'라고 요청하는 설정이야. 일반 계산을 학습 가능한 계산으로 바꾸는 스위치라고 생각하면 돼.

세 가지를 알아 둬:

  1. 텐서의 기본값은 requires_grad=False야. 기울기 추적이 필요하다면 명시적으로 켜야 해.
  2. 연산 입력 중 하나라도 requires_grad=True이면 출력도 requires_grad=True가 돼. 기울기 추적 속성이 출력으로 전파되는 거야.
  3. nn.Module 안에서 nn.Parameter로 만든 모델 매개변수는 자동으로 requires_grad=True가 돼. 직접 설정할 일은 거의 없어.

텐서의 grad_fn 속성을 보면 어떤 연산이 그 텐서를 만들었는지 알 수 있어. 직접 만든 리프 텐서는 grad_fn=None이고, 중간 텐서에는 <AddBackward0>, <MulBackward0> 같은 함수가 붙어. 다음 트랙에서 autograd를 자세히 다룰 거야. 지금은 requires_grad=True가 문을 열고, 이 설정을 직접 켜거나 nn.Parameter가 대신 켜 준다는 것만 기억해.

Code

requires_grad 전환과 전파·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()
전이 학습을 위한 매개변수 동결·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

사전 학습된 resnet18을 불러와 마지막 계층을 제외한 모든 계층을 동결해. 동결 전후의 학습 가능한 매개변수 수를 출력하고, 이어서 layer4의 동결도 풀어 새 개수를 출력해. 그 두 숫자가 특징 추출과 부분 미세 조정의 차이를 보여 줄 거야.

Progress

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

댓글 0

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

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