def _execute_sample_2q_xeb_tasks_in_batches(
    tasks: list[_Sample2qXEBTask],
    sampler: cirq.Sampler,
    combinations_by_layer: list[CircuitLibraryCombination],
    repetitions: int,
    batch_size: int,
    progress_bar: Callable[..., ContextManager],
    dataset_directory: str | None = None,
) -> list[dict[str, Any]]:
    """Helper function used in `sample_2q_xeb_circuits` to batch and execute sampling tasks."""
    n_tasks = len(tasks)
    batched_tasks = [tasks[i : i + batch_size] for i in range(0, n_tasks, batch_size)]

    run_batch = _SampleInBatches(
        sampler=sampler, repetitions=repetitions, combinations_by_layer=combinations_by_layer
    )

    records = []
    with progress_bar(total=len(batched_tasks) * batch_size) as progress:
        for task in batched_tasks:
            new_records = run_batch(task)
            if dataset_directory is not None:
                os.makedirs(f'{dataset_directory}', exist_ok=True)
                protocols.to_json(new_records, f'{dataset_directory}/xeb.{uuid.uuid4()}.json')
            records.extend(new_records)
            progress.update(batch_size)
    return records
Helper function used in `sample_2q_xeb_circuits` to batch and execute sampling tasks.
cirq-core/cirq/experiments/xeb_sampling.py