import torch


def tri_to_vec(tri):
    """
    returns lower triangle of a square matrix, as a vector, excluding the diagonal

    eg given

    1 3 9
    4 3 7
    2 1 5

    returns:

    4 2 1
    """
    assert len(tri.size()) == 2
    assert tri.size(0) == tri.size(1)
    K = tri.size(0)
    res_size = (K - 1) * K // 2
    tri_cpu = tri.cpu()
    res = torch.zeros(res_size, dtype=tri.dtype)
    pos = 0
    for k in range(K - 1):
        res[pos:pos + (K - k - 1)] = tri[k + 1:, k]
        pos += (K - k - 1)
    return res