본문 바로가기

유용 노트

model.eval() 과 with torch.no_grad() 차이

pytorch에서 inferance나 valid를 할 때

model.eval() 과 with torch.no_grad(): 를 사용하는데 왜 둘다 하는걸까??

같은 역할을 하지 않을까?? 라는 궁금증에 차이점을 알아보았습니다.


with torch.no_grad():

  • with torch.no_grad() statement에 코드를 포함 시키면 pytorch는 autograd engine을 꺼버린다.
  • 자동으로 gradient를 트래킹하지 않는다는 말
  • backpropagation을 안하므로 autograd engine을 끔으로서 메모리 사용량과 연산속도를 높인다.

model.eval()

  • model.eval()의 역할은 약간 다르다.
  • 모델에서 train과 eval시에 다르게 동작하는 layer가 존재(ex. Dropout, BatchNorm...)
  • 이런 layer의 동작을 바꾸는 목적으로 사용

'유용 노트' 카테고리의 다른 글

[python] 정규식 정리 (re) - 스크랩  (0) 2022.05.06
[python] 헷갈리는 list comprehension, 자주 실수하는 dict  (0) 2022.05.05
[python] yield  (0) 2022.05.04
Imbalanced data 다루기  (0) 2022.03.17