convention: trailing underscore = mutate
trailing underscore 가 있는 PyTorch op 는 자기 tensor 를 in-place 로 mutate: add_, mul_, zero_, fill_, uniform_, normal_, clamp_. underscore 없는 버전은 새 tensor 반환하고 input 변경 안 함.
왜 신경 써? 두 가지 이유:
- Memory. in-place 는 새 tensor 할당 회피. 1B-parameter model 에선 의미 있음.
- Autograd 안전성. in-place op 는 autograd graph 를 손상시킬 수 있음. PyTorch 가 감지해서 명확한 에러 내지만, 룰 알아둬: backward 에 필요한 tensor 를 mutate 하지 마.
in-place op 가 routine 인 곳
optimizer.zero_grad()가 모든 parameter 의p.grad.zero_()호출 (또는set_to_none=True넘기면p.grad = None설정 — modern PyTorch 의 default 이고 약간 더 빠름).- Custom weight initialization 은 보통
torch.no_grad()블록 안의.uniform_()/.normal_(). - EMA (exponential moving average) update 의 teacher / momentum network 가 교과서 in-place 영역.
그 패턴 밖에선 non-mutating 버전에 기대. 정상 model 코드에서 추가 in-place 의 메모리 절약은 autograd 위험에 비해 거의 가치 없음.