-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ConcurrentMappingIterable: introduce futuretools.FutureResultCollection to optimize FDFO concurrent mapping (closes #20) #21
Merged
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
import asyncio | ||
from abc import ABC, abstractmethod | ||
from asyncio import AbstractEventLoop | ||
from collections import deque | ||
from concurrent.futures import Future | ||
from multiprocessing import Queue | ||
from typing import Deque, Iterator, Sized, TypeVar | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
class FutureResultCollection(Iterator[T], Sized, ABC): | ||
""" | ||
Iterator over added futures' results. Supports adding new futures after iteration started. | ||
""" | ||
|
||
@abstractmethod | ||
def add_future(self, future: "Future[T]") -> None: ... | ||
|
||
|
||
class DequeFutureResultCollection(FutureResultCollection[T]): | ||
def __init__(self) -> None: | ||
self._futures: Deque["Future[T]"] = deque() | ||
|
||
def __len__(self) -> int: | ||
return len(self._futures) | ||
|
||
def add_future(self, future: "Future[T]") -> None: | ||
return self._futures.append(future) | ||
|
||
|
||
class CounterFutureResultCollection(FutureResultCollection[T]): | ||
def __init__(self) -> None: | ||
self._n_futures = 0 | ||
|
||
def __len__(self) -> int: | ||
return self._n_futures | ||
|
||
def add_future(self, future: "Future[T]") -> None: | ||
self._n_futures += 1 | ||
|
||
|
||
class FIFOThreadFutureResultCollection(DequeFutureResultCollection[T]): | ||
""" | ||
First In First Out | ||
""" | ||
|
||
def __next__(self) -> T: | ||
return self._futures.popleft().result() | ||
|
||
|
||
class FDFOThreadFutureResultCollection(CounterFutureResultCollection[T]): | ||
""" | ||
First Done First Out | ||
""" | ||
|
||
def __init__(self) -> None: | ||
super().__init__() | ||
self._results: "Queue[T]" = Queue() | ||
|
||
def _done_callback(self, future: "Future[T]") -> None: | ||
self._results.put(future.result()) | ||
|
||
def add_future(self, future: "Future[T]") -> None: | ||
future.add_done_callback(lambda f: self._done_callback(f)) | ||
super().add_future(future) | ||
|
||
def __next__(self) -> T: | ||
self._n_futures -= 1 | ||
return self._results.get() | ||
|
||
|
||
class FIFOAsyncFutureResultCollection(DequeFutureResultCollection[T]): | ||
""" | ||
First In First Out | ||
""" | ||
|
||
def __init__(self, loop: AbstractEventLoop) -> None: | ||
super().__init__() | ||
self._loop = loop | ||
|
||
def __next__(self) -> T: | ||
return self._loop.run_until_complete(self._futures.popleft()) # type: ignore | ||
|
||
|
||
class FDFOAsyncFutureResultCollection(CounterFutureResultCollection[T]): | ||
""" | ||
First Done First Out | ||
""" | ||
|
||
def __init__(self, loop: AbstractEventLoop) -> None: | ||
super().__init__() | ||
self._loop = loop | ||
self._waiter: asyncio.futures.Future[T] = self._loop.create_future() | ||
|
||
def add_future(self, future: "Future[T]") -> None: | ||
future.add_done_callback(lambda f: self._waiter.set_result(f.result())) | ||
super().add_future(future) | ||
|
||
def __next__(self) -> T: | ||
self._n_futures -= 1 | ||
result = self._loop.run_until_complete(self._waiter) | ||
self._waiter = self._loop.create_future() | ||
return result |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,8 @@ | ||
import asyncio | ||
import time | ||
from abc import ABC, abstractmethod | ||
from asyncio import AbstractEventLoop, get_event_loop | ||
from collections import defaultdict, deque | ||
from concurrent.futures import ( | ||
FIRST_COMPLETED, | ||
Executor, | ||
Future, | ||
ThreadPoolExecutor, | ||
wait, | ||
) | ||
from concurrent.futures import Executor, Future, ThreadPoolExecutor | ||
from contextlib import contextmanager | ||
from datetime import datetime | ||
from math import ceil | ||
|
@@ -36,6 +29,13 @@ | |
T = TypeVar("T") | ||
U = TypeVar("U") | ||
|
||
from streamable.futuretools import ( | ||
FDFOAsyncFutureResultCollection, | ||
FDFOThreadFutureResultCollection, | ||
FIFOAsyncFutureResultCollection, | ||
FIFOThreadFutureResultCollection, | ||
FutureResultCollection, | ||
) | ||
from streamable.util import NO_REPLACEMENT, NoopStopIteration, get_logger, reraise_as | ||
|
||
|
||
|
@@ -342,7 +342,7 @@ class ConcurrentMappingIterable( | |
""" | ||
Template Method Pattern: | ||
This abstract class's `__iter__` is a skeleton for a queue-based concurrent mapping algorithm | ||
that relies on abstract helper methods (`_context_manager`, `_launch_future`, `_get_future_result`) | ||
that relies on abstract helper methods (`_context_manager`, `_create_future`, `_future_result_collection`) | ||
that must be implemented by concrete subclasses. | ||
""" | ||
|
||
|
@@ -360,40 +360,36 @@ def __init__( | |
def _context_manager(self) -> ContextManager: ... | ||
|
||
@abstractmethod | ||
def _launch_future( | ||
def _create_future( | ||
self, elem: T | ||
) -> "Future[Union[U, RaisingIterator.ExceptionContainer]]": ... | ||
|
||
# factory method | ||
@abstractmethod | ||
def _next_yield( | ||
self, futures: "Deque[Future[Union[U, RaisingIterator.ExceptionContainer]]]" | ||
) -> Union[U, RaisingIterator.ExceptionContainer]: ... | ||
def _future_result_collection( | ||
self, | ||
) -> FutureResultCollection[Union[U, RaisingIterator.ExceptionContainer]]: ... | ||
|
||
def __iter__(self) -> Iterator[Union[U, RaisingIterator.ExceptionContainer]]: | ||
with self._context_manager(): | ||
futures: Deque["Future[Union[U, RaisingIterator.ExceptionContainer]]"] = ( | ||
deque() | ||
) | ||
to_yield: Deque[Union[U, RaisingIterator.ExceptionContainer]] = deque( | ||
maxlen=1 | ||
) | ||
# wait, queue, yield (FIFO) | ||
while True: | ||
if futures: | ||
to_yield.append(self._next_yield(futures)) | ||
# queue tasks up to buffer_size | ||
while len(futures) < self.buffer_size: | ||
try: | ||
elem = next(self.iterator) | ||
except StopIteration: | ||
# the upstream iterator is exhausted | ||
break | ||
futures.append(self._launch_future(elem)) | ||
if to_yield: | ||
yield to_yield.pop() | ||
if not futures: | ||
future_results = self._future_result_collection() | ||
|
||
# queue tasks up to buffer_size | ||
while len(future_results) < self.buffer_size: | ||
try: | ||
future_results.add_future(self._create_future(next(self.iterator))) | ||
except StopIteration: | ||
break | ||
|
||
# wait, queue, yield | ||
while future_results: | ||
result = next(future_results) | ||
try: | ||
future_results.add_future(self._create_future(next(self.iterator))) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Might be a little bit cleaner with Also applies to the except above, by putting it outside the while. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh great! |
||
except StopIteration: | ||
pass | ||
yield result | ||
|
||
|
||
class ThreadConcurrentMappingIterable(ConcurrentMappingIterable[T, U]): | ||
def __init__( | ||
|
@@ -421,21 +417,18 @@ def _safe_transformation( | |
except Exception as e: | ||
return RaisingIterator.ExceptionContainer(e) | ||
|
||
def _launch_future( | ||
def _create_future( | ||
self, elem: T | ||
) -> "Future[Union[U, RaisingIterator.ExceptionContainer]]": | ||
return self.executor.submit(self._safe_transformation, elem) | ||
|
||
def _next_yield( | ||
self, futures: "Deque[Future[Union[U, RaisingIterator.ExceptionContainer]]]" | ||
) -> Union[U, RaisingIterator.ExceptionContainer]: | ||
def _future_result_collection( | ||
self, | ||
) -> FutureResultCollection[Union[U, RaisingIterator.ExceptionContainer]]: | ||
if self.ordered: | ||
return futures.popleft().result() | ||
return FIFOThreadFutureResultCollection() | ||
else: | ||
done_futures, _ = wait(futures, return_when=FIRST_COMPLETED) | ||
done_future = next(iter(done_futures)) | ||
futures.remove(done_future) | ||
return done_future.result() | ||
return FDFOThreadFutureResultCollection() | ||
|
||
|
||
class AsyncConcurrentMappingIterable(ConcurrentMappingIterable[T, U]): | ||
|
@@ -448,11 +441,11 @@ def __init__( | |
) -> None: | ||
super().__init__(iterator, buffer_size, ordered) | ||
self.transformation = transformation | ||
self.loop: AbstractEventLoop | ||
self._loop: AbstractEventLoop | ||
|
||
@contextmanager | ||
def _context_manager(self): | ||
self.loop = get_event_loop() | ||
self._loop = get_event_loop() | ||
yield | ||
|
||
async def _safe_transformation( | ||
|
@@ -468,26 +461,21 @@ async def _safe_transformation( | |
except Exception as e: | ||
return RaisingIterator.ExceptionContainer(e) | ||
|
||
def _launch_future( | ||
def _create_future( | ||
self, elem: T | ||
) -> "Future[Union[U, RaisingIterator.ExceptionContainer]]": | ||
return cast( | ||
"Future[Union[U, RaisingIterator.ExceptionContainer]]", | ||
self.loop.create_task(self._safe_transformation(elem)), | ||
self._loop.create_task(self._safe_transformation(elem)), | ||
) | ||
|
||
def _next_yield( | ||
self, futures: "Deque[Future[Union[U, RaisingIterator.ExceptionContainer]]]" | ||
) -> Union[U, RaisingIterator.ExceptionContainer]: | ||
def _future_result_collection( | ||
self, | ||
) -> FutureResultCollection[Union[U, RaisingIterator.ExceptionContainer]]: | ||
if self.ordered: | ||
return self.loop.run_until_complete(futures.popleft()) # type: ignore | ||
return FIFOAsyncFutureResultCollection(self._loop) | ||
else: | ||
done_futures, _ = self.loop.run_until_complete( | ||
asyncio.wait(futures, return_when=asyncio.FIRST_COMPLETED) # type: ignore | ||
) | ||
done_future = next(iter(done_futures)) | ||
futures.remove(done_future) | ||
return done_future.result() | ||
return FDFOAsyncFutureResultCollection(self._loop) | ||
|
||
|
||
class ConcurrentFlatteningIterable( | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why not just:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nice catch! (no reason, I dragged this lambda from previous iterations 🤦🏻)