C.W.K.
Stream
Lesson 08 of 11 · published

PyTorch ↔ NumPy (그리고 GPU caveat)

~10 min · numpy, interop, memory-sharing

Level 0Tensor 호기심
0 XP0/62 lessons0/13 achievements
0/120 XP to next level120 XP to go0% complete

무료 변환, 가끔 무료 메모리

PyTorch 와 NumPy 는 trivial 하게 inter-operate. 외울 건 하나: 변환이 메모리를 공유할 때와 copy 할 때:

  • torch.from_numpy(arr) — 메모리 공유. 한쪽 mutate 하면 다른 쪽도 mutate.
  • tensor.numpy() — tensor 가 CPU 이고 contiguous 면 메모리 공유. GPU 면 에러.
  • torch.tensor(arr) — 항상 copy. 독립성 원할 때.
  • torch.as_tensor(arr) — 가능하면 메모리 공유, 아니면 copy. 어느 쪽이든 상관없을 때 유용.

GPU 룰

NumPy array 는 CPU tensor 에서만 얻을 수 있어. GPU 에 있으면 먼저 옮겨 (.cpu()). gradient 있으면 .detach() 먼저 — graph attachment 제거. 안 그러면 NumPy 가 변환 거부.

'model output 을 numpy 로 줘' 의 완전한 주문: output.detach().cpu().numpy(). 이 chain 외워 — metric 계산이나 plot 할 때 끊임없이 쓸 거야.

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 model 에서든 작은 batch 에 prediction 생성. NumPy 로 변환하고 chain 단계별 검증: detach() comment-out 하고 에러 읽기, 그 다음 .cpu() comment-out (먼저 tensor 를 GPU 로) 하고 그 에러 읽기. 두 메시지 다 외우면 실제 디버깅 시간 절약.

Progress

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

댓글 0

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

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