런타임 오류:입력 유형(토치).FloatTensor) 및 체중 유형(torch.cuda).FloatTensor)는 같아야 합니다.
다음 항목:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
for data in dataloader:
inputs, labels = data
outputs = model(inputs)
다음 오류를 표시합니다.
런타임 오류:입력 유형(토치).FloatTensor) 및 체중 유형(torch.cuda).FloatTensor)는 같아야 합니다.
모델은 GPU에 있지만 데이터는 CPU에 있기 때문에 이 오류가 발생합니다. 따라서 입력 텐서를 GPU에 보내야 합니다.
inputs, labels = data # this is what you had
inputs, labels = inputs.cuda(), labels.cuda() # add this line
또는 이와 같이 코드의 나머지 부분과 일관성을 유지하려면 다음과 같이 하십시오.
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
inputs, labels = inputs.to(device), labels.to(device)
입력 텐서가 GPU에 있지만 모델 가중치가 없는 경우에도 동일한 오류가 발생합니다.이 경우 모델 가중치를 GPU로 전송해야 합니다.
model = MyModel()
if torch.cuda.is_available():
model.cuda()
의 설명서와 그 반대의 설명서를 참조하십시오.
사용할 새 API.to()
방법.
이점은 분명하고 중요합니다.당신의 기기는 내일 "cuda"가 아닌 다른 것일 수 있습니다.
- cp
- 쿠다
- mkldn
- 오픈글
- opencl
- 깊이 있는
- 엉덩이
- msnpu
- xla
그러니 피하도록 하라.model.cuda()
장치를 확인하는 것은 잘못된 것이 아닙니다.
dev = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
또는 하드 코딩:
dev=torch.device("cuda")
다음과 동일:
dev="cuda"
일반적으로 다음 코드를 사용할 수 있습니다.
model.to(dev)
data = data.to(dev)
이전 답변에서 이미 언급했듯이 모델이 GPU에서 교육을 받았지만 CPU에서 테스트를 받은 것이 문제일 수 있습니다. 그렇다면 모델의 가중치와 데이터를 다음과 같이 GPU에서 CPU로 포팅해야 합니다.
device = args.device # "cuda" / "cpu"
if "cuda" in device and not torch.cuda.is_available():
device = "cpu"
data = data.to(device)
model.to(device)
참고: 여기서는 구성 인수가 GPU 또는 CPU로 설정되어 있는지 확인하여 이 코드를 (GPU에서) 교육 및 테스트(CPU에서) 모두에 사용할 수 있습니다.
모델을 로드할 때 가중치와 입력값이 모두 동일한 장치에 있어야 합니다. 우리는 다음을 사용하여 이를 수행할 수 있습니다..to(device)
남의 지적대로
그러나 저장된 가중치와 입력 텐서의 데이터 유형도 다를 수 있습니다.이 경우 모델 가중치와 입력의 데이터 유형도 변경해야 합니다.
model = torch.load(PATH).type(torch.FloatTensor).to(device)
input = input.type(torch.FloatTensor).to(device)
(피토치 설명서 참조):
자체 텐서에 이미 올바른 torch.dtype 및 torch.device가 있으면 자체가 반환됩니다.그렇지 않으면 반환된 텐서는 원하는 torch.dtype 및 torch.device를 사용하는 자체 복사본입니다.
즉, 다음을 수행해야 할 수도 있습니다.
model = model.to("cuda")
data = data.to("cuda")
다음과 같은 기능을 제공합니다.
model.to("cuda")
data.to("cuda")
첫 번째 접근법을 사용하면 안전한 쪽으로 갈 수 있습니다.
* when you get this error::RuntimeError: Input type
(torch.FloatTensor) and weight type (torch.cuda.FloatTensor should
be the same
# Move tensors to GPU is CUDA is available
# Check if CUDA is available
train_on_gpu = torch.cuda.is_available()
If train_on_gpu:
print("CUDA is available! Training on GPU...")
else:
print("CUDA is not available. Training on CPU...")
-------------------
# Move tensors to GPU is CUDA is available
if train_on_gpu:
model.cuda()
나도 같은 문제가 있어, 내 CNN 모델:
class CNN(nn.Module):
def __init__(self):
super(CNN,self).__init__()
self.device = torch.device(device)
self.dummy_param = nn.Parameter(torch.empty(0))
l1 = nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding= (1,1)).to(device)
l2 = nn.Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1,1)).to(device)
l3 = nn.Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)).to(device)
l4 = nn.Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)).to(device)
l5 = nn.Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)).to(device)
self.layers = [l1,l2,l3,l4,l5]
self.layers = [l1,l2]
def forward(self,x):
features = []
for l in self.layers:
x = l(x)
features.append(x)
return features
저는 Conv2d.to (기기)에 제 일을 의뢰했습니다.
먼저 Cuda를 사용할 수 있는지 여부를 확인합니다.
if torch.cuda.is_available():
device = 'cuda'
else:
device = 'cpu'
일부 모델을 로드하려는 경우 다음을 수행합니다.
checkpoint = torch.load('./generator_release.pth', map_location=device)
G = Generator().to(device)
이제 다음 오류가 발생할 수 있습니다.
런타임 오류:입력 유형(토치).FloatTensor) 및 체중 유형(torch.cuda).FloatTensor)는 같아야 합니다.
다음을 통해 입력 데이터 유형을 torch.tensor에서 torch.cuda.tensor로 변환해야 합니다.
if torch.cuda.is_available():
data = data.cuda()
result = G(data)
그런 다음 결과를 torch.cuda.corch에서 torch.coda.coda로 변환합니다.
if torch.cuda.is_available():
result = result.cpu()
x = x.to(device, dtype=torch.float32)
y = y.to(device, dtype=torch.float32)
효과가 있어요, 완벽하게 괜찮아요...
언급URL : https://stackoverflow.com/questions/59013109/runtimeerror-input-type-torch-floattensor-and-weight-type-torch-cuda-floatte
'programing' 카테고리의 다른 글
있나요?SQLite용 NET/C# 래퍼? (0) | 2023.05.04 |
---|---|
실생활 예제, SQL에서 OUTER / CROSS APPLE을 사용하는 경우 (0) | 2023.05.04 |
오류 - IIS 메타베이스에 액세스할 수 없습니다. (0) | 2023.05.04 |
각도:라이프사이클 후크가 구성 요소에서 사용할 수 있는 데이터를 입력하는 경우 (0) | 2023.05.04 |
부분적으로 복사된 파일로 scp를 재개하는 방법은 무엇입니까? (0) | 2023.05.04 |