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

PyTorch ↔ NumPy (그리고 GPU 주의점)

~10 min · numpy, interop, memory-sharing

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

변환은 간단하지만 메모리 공유 여부는 확인해야 해

PyTorch와 NumPy는 쉽게 오갈 수 있어. 꼭 기억할 건 언제 메모리를 공유하고 언제 복사하는가야:

  • torch.from_numpy(arr): 메모리를 공유해. 한쪽을 바꾸면 다른 쪽도 바뀌어.
  • tensor.numpy(): 텐서가 CPU에 있고 연속 배치라면 메모리를 공유해. GPU 텐서에는 바로 쓸 수 없어.
  • torch.tensor(arr): 항상 복사해. 서로 독립된 데이터를 원할 때 써.
  • torch.as_tensor(arr): 가능하면 메모리를 공유하고, 불가능하면 복사해. 어느 쪽이어도 괜찮을 때 유용해.

GPU 규칙

NumPy 배열로 바꿀 수 있는 건 CPU 텐서뿐이야. GPU에 있다면 먼저 .cpu()로 옮겨. 기울기를 추적 중이라면 그보다 먼저 .detach()를 호출해 계산 그래프와 연결을 끊어야 해. 그렇지 않으면 NumPy가 변환을 거부해.

모델 출력을 NumPy 배열로 바꾸는 완전한 연쇄는 output.detach().cpu().numpy()야. 평가지표를 계산하거나 그래프를 그릴 때 계속 쓰게 되니 순서까지 익혀 둬.

Code

양방향 메모리 공유·python
import torch
import numpy as np

# numpy → tensor (shares memory)
arr = np.array([1.0, 2.0, 3.0])
t = torch.from_numpy(arr)
arr[0] = 99
print(t)   # tensor([99.,  2.,  3.]) — yes, changed

# tensor → numpy (shares memory if CPU)
t2 = torch.tensor([4.0, 5.0, 6.0])
arr2 = t2.numpy()
t2[0] = 88
print(arr2)  # [88. 5. 6.] — yes, changed
독립된 복사본이 필요할 때: .clone()과 .copy()·python
import torch
import numpy as np

# I want PyTorch ownership without NumPy peeking in
arr = np.array([1.0, 2.0, 3.0])
t = torch.from_numpy(arr).clone()
arr[0] = 99
print(t)   # tensor([1., 2., 3.]) — independent

# Or in NumPy land
t = torch.tensor([1.0, 2.0, 3.0])
arr = t.numpy().copy()
GPU + autograd 춤·python
import torch

# A model output: on GPU, has gradient tracking
output = torch.randn(4, 10, device="cuda", requires_grad=True)

# Wrong — fails because of grad
# arr = output.numpy()
# RuntimeError: Can't call numpy() on Tensor that requires grad.

# Wrong — fails because of device
# arr = output.detach().numpy()
# TypeError: can't convert cuda:0 device type tensor to numpy.

# Right — detach first, then move to CPU, then numpy
arr = output.detach().cpu().numpy()
print(type(arr), arr.shape)  # <class 'numpy.ndarray'> (4, 10)

# Memorize this chain. You'll use it every time you plot or compute a metric.

External links

Exercise

아무 nn.Linear 모델이나 골라 작은 배치의 예측을 만들고 NumPy 배열로 변환해. 먼저 detach()를 주석 처리한 뒤 오류를 읽어. 다음에는 텐서를 GPU로 옮기고 .cpu()를 주석 처리해 두 번째 오류도 읽어. 두 메시지를 익혀 두면 실전 디버깅 시간이 줄어들 거야.

Progress

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

댓글 0

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

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