Parallel map, but with backpressure. If the caller doesn't call `next` fast enough, this will stop calling `func` at some point rather than letting results pile up in memory. Specifically, there is a max of one output value buffered per thread.
(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int, max_workers: int | None = None, use_processpool_executor: bool = False)
| 784 | Out = TypeVar('Out') |
| 785 | |
| 786 | def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int, max_workers: int | None = None, use_processpool_executor: bool = False) -> Iterable[Out]: |
| 787 | '''Parallel map, but with backpressure. If the caller doesn't call `next` |
| 788 | fast enough, this will stop calling `func` at some point rather than |
| 789 | letting results pile up in memory. Specifically, there is a max of one |
| 790 | output value buffered per thread.''' |
| 791 | if concurrency < 2: |
| 792 | yield from map(func, iterable) |
| 793 | # Not reached. |
| 794 | iterable = iter(iterable) |
| 795 | executor_class: type[ThreadPoolExecutor] | type[ProcessPoolExecutor] |
| 796 | if use_processpool_executor: |
| 797 | executor_class = ProcessPoolExecutor |
| 798 | else: |
| 799 | executor_class = ThreadPoolExecutor |
| 800 | with executor_class(max_workers = max_workers) as executor: |
| 801 | futures: list[concurrent.futures.Future[Out]] = [] |
| 802 | done = False |
| 803 | for _ in range(concurrency): |
| 804 | try: |
| 805 | futures.append(executor.submit(func, next(iterable))) |
| 806 | except StopIteration: |
| 807 | done = True |
| 808 | break |
| 809 | |
| 810 | while futures: |
| 811 | result = futures.pop(0).result() |
| 812 | while not done and len(futures) < concurrency: |
| 813 | try: |
| 814 | futures.append(executor.submit(func, next(iterable))) |
| 815 | except StopIteration: |
| 816 | done = True |
| 817 | break |
| 818 | yield result |
| 819 | |
| 820 | def check_vocab_size(params: Params, vocab: Vocab) -> None: |
| 821 | if params.n_vocab != vocab.vocab_size: |