Issues after implementing minibatching

I am trying to classify sequences by a binary feature. I have a dataset of sequence/label pairs and am using a simple one-layer LSTM to classify each sequence. Before I implemented minibatching, I was getting reasonable accuracy on a test set (80%), and the training loss would go from 0.6 to 0.3 (averaged).

I implemented minibatching, using parts of this tutorial: https://pytorch.org/tutorials/beginner/chatbot_tutorial.html

However, now my model won’t do better than 70-72% (70% of the data has one label) with batch size set to 1 and all other parameters exactly the same. Additionally, the loss starts out at 0.0106 and quickly gets really really small, with no significant change in results. I feel like the results between no batching and batching with size 1 should be the same, so I probably have a bug, but for the life of me I can’t find it. My code is below.

Training code (one epoch):

for i in t:
    model.zero_grad()

    # prep inputs
    last = i+self.params['batch_size']
    last = last if last < len(train_data) else len(train_data)
    batch_in, lengths, batch_targets = self.batch2TrainData(train_data[shuffled][i:last], word_to_ix, label_to_ix)

    # forward pass.
    tag_scores = model(batch_in, lengths)

    # compute loss, then do backward pass, then update gradients
    loss = loss_function(tag_scores, batch_targets)
    loss.backward()

    # Clip gradients: gradients are modified in place
    nn.utils.clip_grad_norm_(model.parameters(), 50.0)

    optimizer.step()

Functions:

def prep_sequence(self, seq, to_ix):
    idxs = [to_ix[w] for w in seq]
    return torch.tensor(idxs, dtype=torch.long)

# transposes batch_in
def zeroPadding(self, l, fillvalue=0):
    return list(itertools.zip_longest(*l, fillvalue=fillvalue))

# Returns padded input sequence tensor and lengths
def inputVar(self, batch_in, word_to_ix):
    idx_batch = [self.prep_sequence(seq, word_to_ix) for seq in batch_in]
    lengths = torch.tensor([len(idxs) for idxs in idx_batch])
    padList = self.zeroPadding(idx_batch)
    padVar = torch.LongTensor(padList)
    return padVar, lengths

# Returns all items for a given batch of pairs
def batch2TrainData(self, batch, word_to_ix, label_to_ix):
    # sort by dec length
    batch = batch[np.argsort([len(x['turn']) for x in batch])[::-1]]
    input_batch, output_batch = [], []
    for pair in batch:
        input_batch.append(pair['turn'])
        output_batch.append(pair['label'])
    inp, lengths = self.inputVar(input_batch, word_to_ix)
    output = self.prep_sequence(output_batch, label_to_ix)
    return inp, lengths, output

Model:

class LSTMClassifier(nn.Module):

    def __init__(self, params, vocab_size, tagset_size, weights_matrix=None):
        super(LSTMClassifier, self).__init__()
        self.hidden_dim = params['hidden_dim']

        if weights_matrix is not None:
            self.word_embeddings = nn.Embedding.from_pretrained(weights_matrix)
        else:
            self.word_embeddings = nn.Embedding(vocab_size, params['embedding_dim'])

        # The LSTM takes word embeddings as inputs, and outputs hidden states
        # with dimensionality params['hidden_dim'].
        self.lstm = nn.LSTM(params['embedding_dim'], self.hidden_dim, bidirectional=False)

        # The linear layer that maps from hidden state space to tag space
        self.hidden2tag = nn.Linear(self.hidden_dim, tagset_size)

    def forward(self, batch_in, lengths):
        embeds = self.word_embeddings(batch_in)
        packed = nn.utils.rnn.pack_padded_sequence(embeds, lengths)
        lstm_out, _ = self.lstm(packed)
        outputs, _ = nn.utils.rnn.pad_packed_sequence(lstm_out)
        tag_space = self.hidden2tag(outputs)
        tag_scores = F.log_softmax(tag_space, dim=0)
        return tag_scores[-1]

Thanks!

For anyone else with a similar issue, I got it to work. I removed the log_softmax calculation, so this:

tag_space = self.hidden2tag(outputs)
tag_scores = F.log_softmax(tag_space, dim=0)
return tag_scores[-1]

becomes this:

tag_space = self.hidden2tag(outputs)
return tag_space[-1]

I also changed NLLLoss to CrossEntropyLoss, (not shown above), and initialized CrossEntropyLoss with no parameters (aka no ignore_index).

I am not certain why these changes were necessary (the docs even say that NLLLoss should be run after a log_softmax layer), but they got my model working and brought my loss back to a reasonable range (~0.5).