[오류Error] RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same

2024. 4. 17. 10:04·오류Error
728x90
반응형
import torch
import torch.nn as nn
import torch.nn.functional as F

class SimpleCNN(nn.Module):
    def __init__(self):
        super(SimpleCNN, self).__init__()
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=4, kernel_size=3, stride=1, padding=1)
        self.conv2 = nn.Conv2d(in_channels=4, out_channels=8, kernel_size=3, stride=1, padding=1)
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
        self.flatten = nn.Flatten()  # Flatten 모듈 추가
        self.fc1 = nn.Linear(8 * 16 * 16, 100)  # 입력 크기 조정 필요
        self.fc2 = nn.Linear(100, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.relu(self.conv2(x))
        x = self.pool(x)
        x = self.flatten(x)  # Flatten 함수 호출
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

# 모델의 정의 및 요약 정보 출력
model = SimpleCNN()
print(model)

from torchsummary import summary

INPUT_SIZE = 32
model = SimpleCNN() # 모델 인스턴스 생성
summary(model, input_size=(3, INPUT_SIZE, INPUT_SIZE))

 

간단한 딥러닝 코드를 돌리던 중 아래와 같은 에러가 발생했다. 

 

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-14-04359cf02c9c> in <cell line: 5>()
      3 INPUT_SIZE = 32
      4 model = SimpleCNN()  # 모델 인스턴스 생성
----> 5 summary(model, input_size=(3, INPUT_SIZE, INPUT_SIZE))

7 frames
/usr/local/lib/python3.10/dist-packages/torch/nn/modules/conv.py in _conv_forward(self, input, weight, bias)
    454                             weight, bias, self.stride,
    455                             _pair(0), self.dilation, self.groups)
--> 456         return F.conv2d(input, weight, bias, self.stride,
    457                         self.padding, self.dilation, self.groups)
    458 

RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same

 

위 오류 메시지는 모델의 입력 데이터와 가중치 데이터가 서로 다른 디바이스에 위치해 있기 때문에 발생합니다. 오류 메시지에는 `Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same`라고 나와 있어, 입력 데이터는 CUDA(즉, GPU)를 사용하는 반면, 모델의 가중치는 CPU에 있음을 의미합니다.

이 문제를 해결하기 위해 모델과 입력 데이터가 동일한 디바이스(모두 CPU 또는 모두 GPU)에 있어야 합니다. 만약 GPU에서 모델을 실행하고자 한다면, 모델과 입력 데이터 모두를 GPU로 옮겨야 합니다.

 

다음은 모델과 데이터를 GPU로 옮기는 코드입니다

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = SimpleCNN().to(device)  # 모델을 GPU로 옮김
summary(model, input_size=(3, INPUT_SIZE, INPUT_SIZE))

# 입력 데이터도 GPU로 옮겨야 할 경우, 다음과 같이 할 수 있습니다.
# data = data.to(device)


이 코드는 먼저 사용 가능한 경우 GPU를 사용하도록 설정하고, 모델을 해당 디바이스로 이동시킵니다. 


 

해결 완료!

 

728x90
반응형
저작자표시 (새창열림)

'오류Error' 카테고리의 다른 글

[오류Error] VS Code Remote-SSH: "원격 호스트가 VS Code Server를 실행하기 위한 필수 구성 요소를 충족하지 않습니다" 오류 해결 후기  (7) 2025.04.11
[오류Error] Resource punkt_tab not found. Please use the NLTK Downloader to obtain the resource:  (0) 2024.11.22
[오류Error] FileNotFoundError: [Errno 2] JVM DLL not found: /Library/Java/JavaVirtualMachines/microsoft-11.jdk/Contents/Home/lib/jli/libjli.dylib"  (1) 2024.11.15
[오류Error] exception: install mecab in order to use it: http://konlpy.org/en/latest/install/  (0) 2024.02.08
[오류Error] 'utf-8' codec can't decode byte 0xc1 in position 0: invalid start byte  (0) 2022.05.21
'오류Error' 카테고리의 다른 글
  • [오류Error] Resource punkt_tab not found. Please use the NLTK Downloader to obtain the resource:
  • [오류Error] FileNotFoundError: [Errno 2] JVM DLL not found: /Library/Java/JavaVirtualMachines/microsoft-11.jdk/Contents/Home/lib/jli/libjli.dylib"
  • [오류Error] exception: install mecab in order to use it: http://konlpy.org/en/latest/install/
  • [오류Error] 'utf-8' codec can't decode byte 0xc1 in position 0: invalid start byte
ISFP의 블로그
ISFP의 블로그
이건 첫 번째 레슨, 업무에서 마주친 문제 해결 경험 공유하기 이건 두 번째 레슨, 개인적으로 공부한 데이터/AI 지식을 기록하기 이건 세 번째 레슨, 다른 사람과 비교하지 말고 오직 어제의 나와 비교하기
  • ISFP의 블로그
    resultofeffort
    ISFP의 블로그
  • 전체
    오늘
    어제
    • 분류 전체보기 (117)
      • python (25)
      • pythonML (27)
      • Linux (0)
      • 오류Error (8)
      • information (7)
      • Deep learning (5)
      • pytorch (29)
      • 코딩테스트 (4)
      • 밑바닥 DL (4)
      • 논문 리뷰 (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    머신러닝
    분류
    cnn
    machinelearning
    nlp
    티스토리챌린지
    오블완
    deeplearning
    텍스트전처리
    토큰화
    Python
    Pandas
    pytorch
    인공지능
    Ai
    konlpy
    자연어처리
    딥러닝
    Deep Learning
    데이터분석
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
ISFP의 블로그
[오류Error] RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same
상단으로

티스토리툴바