import torch


def flat_reduce(tensor, reduce_type='sum', final_reduce='mean'):
    """Flattens the tensor and reduces it."""

    def _reduce(tensor, how, *args):
        return getattr(torch, how)(tensor, *args)  # pylint:disable=not-callable

    tensor = tensor.reshape(tensor.shape[0], -1)
    tensor = _reduce(tensor, reduce_type, -1)
    if final_reduce is not None:
        tensor = _reduce(tensor, final_reduce)

    return tensor