def padshape(x, target_dim, dim=-1):
    """
    Insert singleton dimensions in position `dim` until the tensor as
    dimensionality `target_dim`.
    """
    pad_dim = max(0, target_dim - x.dim())
    old_shape = list(x.shape)
    new_shape = old_shape[:dim] + [1] * pad_dim + old_shape[dim:]
    x = x.reshape(new_shape)
    return x