def detection_collate_mbatches_fn(
    mbatches: Sequence[DetectionBatchT],
) -> DetectionBatchT:
    """
    Collate function used when loading detection datasets using a DataLoader.

    This will merge multiple batches to create a concatenated batch.

    Beware that merging multiple batches is different from creating a batch
    from single dataset elements: Batches can be created from a
    list of single dataset elements by using :func:`detection_collate_fn`.
    """

    # The code used here is equivalent to the following one:
    # images: List[Tuple[Tensor, ...]] = []
    # targets: List[Tuple[Dict, ...]] = []
    # task_labels: List[Tuple[int, ...]] = []

    # for mb in mbatches:
    #     images.append(mb[0])
    #     targets.append(mb[1])
    #     task_labels.append(mb[2])

    # batched_images = tuple(itertools.chain.from_iterable(images))
    # batched_targets = tuple(itertools.chain.from_iterable(targets))
    # batched_task_labels = tuple(itertools.chain.from_iterable(task_labels))

    # return batched_images, batched_targets, batched_task_labels

    lists_dict: Dict[int, List] = defaultdict(list)
    for mb in mbatches:
        for mb_elem_idx, mb_elem in enumerate(mb):
            lists_dict[mb_elem_idx].append(mb_elem)

    batch_elements = []
    for mb_elem_idx in range(max(lists_dict.keys()) + 1):
        batch_elements.append(
            tuple(itertools.chain.from_iterable(lists_dict[mb_elem_idx]))
        )

    return tuple(batch_elements)  # type: ignore

    Collate function used when loading detection datasets using a DataLoader.

    This will merge multiple batches to create a concatenated batch.

    Beware that merging multiple batches is different from creating a batch
    from single dataset elements: Batches can be created from a
    list of single dataset elements by using :func:`detection_collate_fn`.
    
avalanche/benchmarks/utils/collate_functions.py