Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions test/test_nn.py
Original file line number Diff line number Diff line change
Expand Up @@ -2935,6 +2935,13 @@ def _test_loss_equal_input_target_shape(self, cast):
def test_loss_equal_input_target_shape(self):
self._test_loss_equal_input_target_shape(lambda x: x)

def test_NLLLoss_mismatched_batch(self):
x = torch.randn((10, 3), requires_grad=True)
# t should have size (10,)
t = torch.zeros((3,), dtype=torch.int64)
with self.assertRaisesRegex(ValueError, 'Expected.*batch_size'):
F.nll_loss(x, t)

def test_RNN_cell_no_broadcasting(self):
def test(cell_module, input, hx, input_size, hidden_size):
cell = cell_module(input_size, hidden_size)
Expand Down
10 changes: 7 additions & 3 deletions torch/nn/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -1365,7 +1365,7 @@ def nll_loss(input, target, weight=None, size_average=True, ignore_index=-100, r
in case of 2D Loss, or :math:`(N, C, d_1, d_2, ..., d_K)` where :math:`K > 1`
in the case of K-dimensional loss.
target: :math:`(N)` where each value is :math:`0 \leq \text{targets}[i] \leq C-1`,
or :math:`(N, C, d_1, d_2, ..., d_K)` where :math:`K \geq 1` for
or :math:`(N, d_1, d_2, ..., d_K)` where :math:`K \geq 1` for
K-dimensional loss.
weight (Tensor, optional): a manual rescaling weight given to each
class. If given, has to be a Tensor of size `C`
Expand All @@ -1388,6 +1388,12 @@ def nll_loss(input, target, weight=None, size_average=True, ignore_index=-100, r
dim = input.dim()
if torch.is_tensor(weight):
weight = weight
if dim < 2:
raise ValueError('Expected 2 or more dimensions (got {})'.format(dim))

if input.size(0) != target.size(0):
raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'
.format(input.size(0), target.size(0)))
if dim == 2:
return torch._C._nn.nll_loss(input, target, weight, size_average, ignore_index, reduce)
elif dim == 4:
Expand All @@ -1405,8 +1411,6 @@ def nll_loss(input, target, weight=None, size_average=True, ignore_index=-100, r
return torch._C._nn.nll_loss2d(input, target, weight, size_average, ignore_index, reduce)
out = torch._C._nn.nll_loss2d(input, target, weight, size_average, ignore_index, reduce)
return out.view(out_size)
else:
raise ValueError('Expected 2 or more dimensions (got {})'.format(dim))


def poisson_nll_loss(input, target, log_input=True, full=False, size_average=True, eps=1e-8, reduce=True):
Expand Down