Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

630
Views
RuntimeError: "nll_loss_forward_reduce_cuda_kernel_2d_index" no implementado para 'Int': Pytorch

Entonces, estaba tratando de codificar un chatbot usando Pytorch siguiendo este tutorial .

Código: (Mínimo, Reproducible)

 tags = [] for intent in intents['intents']: tag = intent['tag'] tags.append(tag) tags = sorted(set(tags)) X_train = [] X_train = np.array(X_train) class ChatDataset(Dataset): def __init__(self): self.n_sample = len(X_train) self.x_data = X_train #Hyperparameter batch_size = 8 hidden_size = 47 output_size = len(tags) input_size = len(X_train[0]) learning_rate = 0.001 num_epochs = 1000 dataset = ChatDataset() train_loader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True, num_workers=0) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # using gpu model = NeuralNet(input_size, hidden_size, output_size).to(device) # loss and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) for epoch in range(num_epochs): for (words, labels) in train_loader: words = words.to(device) labels = labels.to(device) #forward outputs = model(words) loss = criterion(outputs, labels) #the line where it is showing the problem #backward and optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if (epoch +1) % 100 == 0: print(f'epoch {epoch+1}/{num_epochs}, loss={loss.item():.4f}') print(f'final loss, loss={loss.item():.4f}')

Código completo (si es necesario)

Recibo este error al intentar obtener la función de pérdida.

RuntimeError: "nll_loss_forward_reduce_cuda_kernel_2d_index" not implemented for 'Int'

Rastrear:

Traceback (most recent call last): File "train.py", line 91, in <module> loss = criterion(outputs, labels) File "C:\Users\PC\anaconda3\lib\site-packages\torch\nn\modules\module.py", line 1102, in _call_impl return forward_call(*input, **kwargs) File "C:\Users\PC\anaconda3\lib\site-packages\torch\nn\modules\loss.py", line 1150, in forward return F.cross_entropy(input, target, weight=self.weight, File "C:\Users\PC\anaconda3\lib\site-packages\torch\nn\functional.py", line 2846, in cross_entropy return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing) RuntimeError: "nll_loss_forward_reduce_cuda_kernel_2d_index" not implemented for 'Int'

Pero mirando el tutorial, parece funcionar perfectamente allí, mientras que no es así en mi caso.

¿Qué hacer ahora?

Gracias.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

En mi caso, resolví este problema convirtiendo el tipo de objetivos a torch.LongTensor antes de almacenar los datos en la GPU de la siguiente manera:

 for inputs, targets in data_loader: targets = targets.type(torch.LongTensor) # casting to long inputs, targets = inputs.to(device), targets.to(device) ... ... loss = self.criterion(output, targets)
over 4 years ago · Santiago Trujillo Report

0

Supongo que seguiste el tutorial de Python Engineer en YouTube (¡yo también lo hice y me encontré con los mismos problemas!). La solución de @Phoenix funcionó para mí. Todo lo que tenía que hacer era emitir la etiqueta (él la llama objetivo) de esta manera:

 for epoch in range(num_epochs): for (words, labels) in train_loader: words = words.to(device) labels = labels.type(torch.LongTensor) # <---- Here (casting) labels = labels.to(device) #forward outputs = model(words) loss = criterion(outputs, labels) #backward and optimizer step optimizer.zero_grad() loss.backward() optimizer.step() if (epoch + 1) % 100 == 0: print(f'epoch{epoch+1}/{num_epochs}, loss={loss.item():.4f}')

Funcionó y se imprimió en el terminal la evolución de la pérdida. ¡Gracias @Phoenix!

PD: aquí está el enlace a la serie de videos. Obtuve este código de: el video de Python Engineer (esta es la parte 4 de 4)

over 4 years ago · Santiago Trujillo Report

0

Simplemente verifique qué está devolviendo su model , debe ser de tipo float , es decir, su variable de outputs . De lo contrario, cámbielo a tipo float .
Creo que has devuelto el tipo int en el método de reenvío

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!