import torch


def reverse_sentences(batch, lengths):
    """
    Reverse sentences inside a batch.
    """
    bs = lengths.size(0)
    assert batch.size(1) == bs
    new_batch = batch.clone()
    inv_idx = torch.arange(lengths.max() - 1, -1, -1)
    for i in range(bs):
        new_batch[:lengths[i], i].copy_(new_batch[:, i][inv_idx[-lengths[i]:]])
    return new_batch