def broadcast(t, outsize, dim):
    """
    General function that broadcasts a tensor (copying the data) along
    a given dimension `dim` to a desired size `outsize`, if the current
    size of that dimension is a divisor of the desired size `outsize`.

    >>> x = broadcast(torch.randn(5, 2, 6), 6, 1)
    >>> y = broadcast(torch.randn(5, 6, 6), 6, 1)
    >>> x.size(1)
    6
    >>> y.size(1)
    6
    """
    tsize = t.size(dim)
    # do we need to broadcast?
    if tsize != outsize:
        div, mod = divmod(outsize, tsize)
        if mod != 0:
            raise ValueError(
                "Cannot broadcast {} -> {}".format(outsize, tsize))
        size = [1 if d != dim else div for d in range(len(t.size()))]
        return t.repeat(*size)
    return t