RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument index in method wrapper_CUDA__index_select)

AFL·2024년 1월 29일

error shooting

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument index in method wrapper_CUDA__index_select)

tensor 가 어떤건 cpu 에, 어떤건 cuda 에 올라가 있어서 생긴 에러다.
type 을 바꿔서 시도해보았지만 type 문제는 아니었다. (input 데이터의 dtype 을 int64에서 float64로)

결국 input 데이터와 weight, bias 를 넘겨주는 부분에서 cuda 로 지정해주어서 해결했다. 오류 나는 곳 따라가서 torch.nn.functional 까지 내려가서 억지로 설정해줌으로써 해결을 해서 이 방법이 맞는지는 모르겠지만 어쨌든 cuda 에 돌아가서 이렇게 해결해서 돌리는 중이다..

torch.nn.functional.embedding() 에서 input.cuda(), weight.cuda() 설정

def embedding(
    input: Tensor,
    weight: Tensor,
    padding_idx: Optional[int] = None,
    max_norm: Optional[float] = None,
    norm_type: float = 2.0,
    scale_grad_by_freq: bool = False,
    sparse: bool = False,
) -> Tensor:
    r"""A simple lookup table that looks up embeddings in a fixed dictionary and size.
	
    ...
    
    ### ADD
    input = input.cuda()
    weight = weight.cuda()
    
    return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)

torch.nn.functional.layer_norm() 에서 weight.cuda(), bias.cuda() 설정

def layer_norm(
    input: Tensor,
    normalized_shape: List[int],
    weight: Optional[Tensor] = None,
    bias: Optional[Tensor] = None,
    eps: float = 1e-5,
) -> Tensor:
    r"""Applies Layer Normalization for last certain number of dimensions.

    See :class:`~torch.nn.LayerNorm` for details.
    """
    if has_torch_function_variadic(input, weight, bias):
        return handle_torch_function(
            layer_norm, (input, weight, bias), input, normalized_shape, weight=weight, bias=bias, eps=eps
        )

    ## ADD
    weight = weight.cuda()
    bias = bias.cuda()
    
    return torch.layer_norm(input, normalized_shape, weight, bias, eps, torch.backends.cudnn.enabled)

torch.nn.modules.linear.Linear.forward() 에서 self.weight.cuda(), self.bias.cuda()

def forward(self, input: Tensor) -> Tensor:
    ## ADD 
    weight = self.weight.cuda()
    bias = self.bias.cuda()

    return F.linear(input, weight, bias)

참고

https://velog.io/@seanko29/PyTorch%EC%97%90%EB%9F%AC-%ED%95%B4%EA%B2%B0-RuntimeError-Expected-all-tensors-to-be-on-the-same-device-but-found-at-least-two-devices-cuda1-and-cuda0-when-checking-argument-for-argument-weight-in-method-wrappercudnnconvolution

profile
공부해서 남주자

0개의 댓글