import torch


def aggregate_words_by_mean(phrase_embedding_t, *_args, dim, **_kwargs):
    """
    Return the averaged embedding of words in a phrase, for each phrase.

    :param phrase_embedding_t: A ([*, d1], [*, 1]) tuple of tensors
    :param dim: The dimension to reduce
    :return: A [*] tensor
    """
    (phrase_embedding, phrase_embedding_mask) = phrase_embedding_t

    # inhibit contributions of padded words
    phrase_embedding = torch.masked_fill(phrase_embedding, mask=phrase_embedding_mask == 0, value=0)

    return phrase_embedding.sum(dim=dim) / phrase_embedding_mask.sum(dim=dim)