import torch


def zero_pad(tensor, target_len, dim):
    """
    Add zeros to a tensor alonng the specified dimension to reach the target length in that dimension.
    """
    tensor_size = list(tensor.size())
    assert dim <= len(tensor_size), "The specified dimension is larger than the tensor rank"
    pad_size = tensor_size
    pad_size[dim] = target_len - tensor_size[dim]
    pad = torch.zeros(pad_size)
    pad_tensor = torch.cat([tensor, pad], dim=dim)
    return pad_tensor