내가 보려고 만든 블로그

Torch의 Forward 함수는 왜 작동하는 것 일까? 본문

Data Science/Pytorch,Tensorflow

Torch의 Forward 함수는 왜 작동하는 것 일까?

정의김 2021. 11. 22. 21:19
class model(nn.module):
	def __init__(self):
    	pass
    
    def forward(sefl):
    	pass

Torch로 모델을 만들다 보면 항상 궁금한 것이 있었다. 보통 토치에서 모델을 만들때 다음과 같은 형태로 모델을 만드는데 이렇게 만들어진 클래스를 model = model() 과 같이 인스턴스한 한 후 input을 넣기만 하면 모델이 동작을 한다는 점이다. 분명히 forward부분을 정의만하고 사용한 적이 없는데도 말이다. 궁금해서 module.nn의 소스코드를 열어보았다.

https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/module.py

 

GitHub - pytorch/pytorch: Tensors and Dynamic neural networks in Python with strong GPU acceleration

Tensors and Dynamic neural networks in Python with strong GPU acceleration - GitHub - pytorch/pytorch: Tensors and Dynamic neural networks in Python with strong GPU acceleration

github.com

 

그 결과 다음과 같이 1156번째 줄에서 _call_impl 함수를 가져오는 것을 발견하였다.

 

그리고 _call_impl 을 보면 

self.forward 를 리턴하는 것을 확인할수 있다. 근데 __call__ 만으로 def __call__ 과 같은 callable 함수가 실행된다는 것이 잘 이해가 가지 않았다.그래서 ai 단톡방에 물어보았더니 다음과 같은 대답을 얻었다. 직접도 해보았다.

이게 되네??? 어쨋든 고민해결