위의 세가지 함수들은 모두 사용법이 다르고 사람들마다 자기 편한대로 맞게만 쓰면 되지만,
내가 위의 세가지 함수들을 쓰는 경우는 다음과 같다.
우선, 나는 matmul은 잘 쓰지 않는다. 왜냐면 matmul은 너무 많은 것을 내부적으로 구현해놨고, 이에 따라 내가 헷갈릴 수도 있다. 최대한 explicit하게 코드를 쓰는것을 지향하기 때문에 matmul은 불가피한 경우가 아니면 쓰지 않는다.
- mm은 matrix multiplication으로, [n, m] x [m,p] = [n,p] 를 구현한다.
- bmm은 batch matrix multiplication으로, 두 operand가 모두 batch일 때 사용한다.
- [B, n, m] x [B, m, p] = [B, n, p]
- matrix가 아니고 벡터는?
- matmul을 쓰면 첫번째 operand만 vector이면 어떡하나, 두번째 operand만 vector면 어떡하나, 둘 다 vector면 어떡하냐에 따라 구구절절하게 편리하게 구현을 해놨다.
- 그리고 아마 대부분의 경우 사람들이 기대한 그대로 결과가 나올 것이다.
- 그런데 나는 그게 싫어서
- unsqueeze(), mm() 또는 bmm(), squeeze() 이렇게 chain으로 써서 해결한다.
- 그렇게 싫어하는 matmul()을 쓰는 경우
- 나는 오직 한 경우에만 matmul()을 쓴다. operand가 하나는 batch matrix이고, 나머지 하나는 batch가 아닌 matrix인 경우이다.
- batch가 아닌 operand가 vector이든 matrix이든 matmul() 함수에서는 상관없지만 나는 additional dimension을 prepend하고 다시 없애는 걸 explicit하게 써놓는 걸 선호해서 이 경우에도 prepend를 직접해서 matrix로 만들어서 쓴다.
- torch.matmul() documentation에서 맨 마지막 사용례에 해당한다.
If both arguments are at least 1-dimensional and at least one argument is N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the batched matrix multiply and removed after. If the second argument is 1-dimensional, a 1 is appended to its dimension for the purpose of the batched matrix multiple and removed after. The non-matrix (i.e. batch) dimensions are broadcasted (and thus must be broadcastable). For example, if input is a (j \times 1 \times n \times m) tensor and other is a (k \times m \times p) tensor, out will be an (j \times k \times n \times p) tensor.
'기타' 카테고리의 다른 글
Pytorch GPU device 쓸 때 디버깅 오류 (0) | 2020.06.12 |
---|---|
Tensorboard와 OSError: [Errno 12] Cannot allocate memory 에러 (0) | 2020.04.06 |
shutil 패키지를 이용해서 python에서 파일 복사/이동/삭제하기 (0) | 2020.03.27 |
특정 git branch만 clone하기 (0) | 2020.02.06 |
git rest을 이용해 unstage하거나 unroll하기 (0) | 2020.02.06 |