def _check_and_reduce_gradients(variable: Variable, backward_engine: EngineLM) -> Set[Variable]:
    """
    Check and reduce gradients for a given variable.

    This function checks if the gradients of the variable need to be reduced based on the reduction groups
    specified in the variable's metadata. If reduction is required, it performs the reduction operation
    for each reduction group and returns the reduced gradients.
    
    For example, we do things like averaging the gradients using this functionality.

    :param variable: The variable for which gradients need to be checked and reduced.
    :type variable: Variable
    :param backward_engine: The backward engine used for gradient computation.
    :type backward_engine: EngineLM

    :return: The reduced gradients for the variable.
    :rtype: Set[Variable]
    """
    if variable._reduce_meta == []:
        return variable.gradients
    if variable.get_gradient_text() == "":
        return variable.gradients
    
    if len(variable.gradients) == 1:
        return variable.gradients
    
    id_to_gradient_set = defaultdict(set)
    id_to_op = {} # Note: there must be a way to ensure that the op is the same for all the variables with the same id
    
    # Go through each gradient, group them by their reduction groups
    for gradient in variable.gradients:
        for reduce_item in gradient._reduce_meta:
            id_to_gradient_set[reduce_item["id"]].add(gradient)
            id_to_op[reduce_item["id"]] = reduce_item["op"]
    # For each reduction group, perform the reduction operation
    new_gradients = set()
    for group_id, gradients in id_to_gradient_set.items():
        logger.info(f"Reducing gradients for group {group_id}", extra={"gradients": gradients})
        new_gradients.add(id_to_op[group_id](gradients, backward_engine))
    
    return new_gradients

    Check and reduce gradients for a given variable.

    This function checks if the gradients of the variable need to be reduced based on the reduction groups
    specified in the variable's metadata. If reduction is required, it performs the reduction operation
    for each reduction group and returns the reduced gradients.
    
    For example, we do things like averaging the gradients using this functionality.

    :param variable: The variable for which gradients need to be checked and reduced.
    :type variable: Variable
    :param backward_engine: The backward engine used for gradient computation.
    :type backward_engine: EngineLM

    :return: The reduced gradients for the variable.
    :rtype: Set[Variable]
    
textgrad/variable.py