코딩 및 기타

[torch][warn] userWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow.

정지홍 2025. 11. 4. 11:09

 

 

creating a tensor from a list of numpy.

ndarrays is extremelt slow.

please consider converting the list to a single numpy.

ndarray with numpy.array() before converting to a tensor

 

  • 원인
    • 현재 numpy 배열들의 list를 그대로 torch.tensor()에 넣는것이 원인.
      • 이 방식은 내부에서 원소 하나하나를 파이썬 루프로 복사해서 tensor를 만들기 때문에, 매우 느리고 메모리가 낭비됨.
      • 즉, 학습은 돌아가지만 속도 손해 발생.
  • 왜 저 방식이 느린가?
    • torch.tensor( list_of_ndarrays ) ----> 각 원소(ndarray)를 개별 텐서로 바꾼뒤 다시 하나의 텐서로 합치려는 과정을 거친다.
    • 반면에 np.stack으로, 먼저 하나의 큰 ndarray로 만든뒤에 torch.from_numpy로 바꾸면, 복사 없이 바로 tensor가 된다.
       
       
       
       

기존의 코드
수정후

def scene_collate(batch):
    trajectories = []
    meta = []
    scene = []

    for _traj, _meta, _scene in batch:
        # _traj가 torch.Tensor면 넘파이로 변환, 아니면 float32로 통일
        if torch.is_tensor(_traj):
            _traj = _traj.detach().cpu().numpy()
        _traj = np.asarray(_traj, dtype=np.float32)
        trajectories.append(_traj)
        meta.append(_meta)
        scene.append(_scene)

    # 리스트 → 하나의 큰 ndarray로 묶은 뒤 제로-카피로 텐서화
    traj_np = np.stack(trajectories, axis=0)        # (B, Nw, T, 2)
    traj_t  = torch.from_numpy(traj_np).contiguous()

    # 기존 동작과 호환: batch_size=1을 가정해 첫 축을 제거
    return traj_t.squeeze(0), meta, scene[0]