g_w # this way we include w in the computation of M

    M = x.max(dim=dim, keepdim=True).values
    x = torch.log(torch.exp(x - M).sum(dim=dim, keepdim=True)) + M
    
    if not keepdim:
        x = x.squeeze(dim=dim)

    return x


def log_mean_exp_trick(x, dim=-1, keepdim=False):
    &#34;&#34;&#34;Computes log(mean(exp(x), dim=dim, keepdim=keepdim)) safely.

    Uses the logsumexp trick for the computation of this quantity.
    &#34;&#34;&#34;
    N = x.size(dim)

    return log_sum_exp_trick(x, dim=d