Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/executorlib/backend/executor_nested.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
from concurrent.futures import Future
from typing import Callable, Optional

from executorlib.standalone.interactive.arguments import (
get_future_objects_from_input,
)


class BackendExecutor:
def __init__(self):
self._tasks_dict = {}
self._future_dict = {}

@property
def tasks(self):
return self._tasks_dict

def batched(
self,
iterable: list[Future],
n: int,
) -> list[Future]:
"""
Batch futures from the iterable into tuples of length n. The last batch may be shorter than n.

Args:
iterable (list): list of future objects to batch based on which future objects finish first
n (int): badge size

Returns:
list[Future]: list of future objects one for each batch
"""
raise NotImplementedError("The batched method is not implemented.")

def map(
self,
fn: Callable,
*iterables,
timeout: Optional[float] = None,
chunksize: int = 1,
):
"""Returns an iterator equivalent to map(fn, iter).

Args:
fn: A callable that will take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
chunksize: The size of the chunks the iterable will be broken into
before being passed to a child process. This argument is only
used by ProcessPoolExecutor; it is ignored by
ThreadPoolExecutor.

Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.

Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values.
"""
raise NotImplementedError("The map method is not implemented.")

def submit( # type: ignore
self,
fn: Callable,
/,
*args,
resource_dict: Optional[dict] = None,
**kwargs,
) -> Future:
"""
Submits a callable to be executed with the given arguments.

Schedules the callable to be executed as fn(*args, **kwargs) and returns
a Future instance representing the execution of the callable.

Args:
fn (callable): function to submit for execution
args: arguments for the submitted function
kwargs: keyword arguments for the submitted function
resource_dict (dict): A dictionary of resources required by the task. With the following keys:
- cores (int): number of MPI cores to be used for each function call
- threads_per_core (int): number of OpenMP threads to be used for each function call
- gpus_per_core (int): number of GPUs per worker - defaults to 0
- cwd (str/None): current working directory where the parallel python task is executed
- openmpi_oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI and
SLURM only) - default False
- slurm_cmd_args (list): Additional command line arguments for the srun call (SLURM only)
- error_log_file (str): Name of the error log file to use for storing exceptions raised
by the Python functions submitted to the Executor.

Returns:
Future: A Future representing the given call.
"""
if resource_dict is None:
resource_dict = {}
f: Future = Future()
self._future_dict[f] = id(f)
self._tasks_dict[id(f)] = {
"fn": fn,
"args": args, # at the momemt the future objects are not removed from the args
"kwargs": kwargs, # at the momemt the future objects are not removed from the kwargs
"resource_dict": resource_dict,
"dependencies": [
self._future_dict[future_dependency]
for future_dependency in get_future_objects_from_input(
args=args, kwargs=kwargs
)
],
}
return f
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_parallel.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
import cloudpickle
import zmq

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -43,7 +44,11 @@ def main() -> None:
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -90,7 +95,13 @@ def main() -> None:
else:
# Send output
if mpi_rank_zero:
interface_send(socket=socket, result_dict={"result": output_reply})
interface_send(
socket=socket,
result_dict={
"result": output_reply,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_serial.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
from os.path import abspath
from typing import Optional

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -29,7 +30,11 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -65,7 +70,13 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
)
else:
# Send output
interface_send(socket=socket, result_dict={"result": output})
interface_send(
socket=socket,
result_dict={
"result": output,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 15 additions & 0 deletions src/executorlib/task_scheduler/base.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ def __init__(
self._process_kwargs: dict = {}
self._max_cores = max_cores
self._future_queue: Optional[queue.Queue] = queue.Queue()
self._return_queue: Optional[queue.Queue] = queue.Queue()
self._process: Optional[Union[Thread, list[Thread]]] = None
self._validator = validator

Expand DownExpand Up@@ -84,6 +85,8 @@ def info(self) -> Optional[dict]:
meta_data_dict = self._process_kwargs.copy()
if "future_queue" in meta_data_dict:
del meta_data_dict["future_queue"]
if "return_queue" in meta_data_dict:
del meta_data_dict["return_queue"]
if self._process is not None and isinstance(self._process, list):
meta_data_dict["max_workers"] = len(self._process)
return meta_data_dict
Expand All@@ -102,6 +105,16 @@ def future_queue(self) -> Optional[queue.Queue]:
"""
return self._future_queue

@property
def return_queue(self) -> Optional[queue.Queue]:
"""
Get the return queue.

Returns:
queue.Queue: The return queue.
"""
return self._return_queue

def batched(
self,
iterable: list[Future],
Expand DownExpand Up@@ -238,8 +251,10 @@ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False):
if isinstance(self._process, Thread):
self._process.join()
self._future_queue.join()
self._return_queue.join()
self._process = None
self._future_queue = None
self._return_queue = None

def _set_process(self, process: Thread):
"""
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -75,6 +75,7 @@ def __init__(
max_cores=executor_kwargs.get("max_cores"), validator=validator
)
executor_kwargs["future_queue"] = self._future_queue
executor_kwargs["return_queue"] = self._return_queue
executor_kwargs["spawner"] = spawner
executor_kwargs["queue_join_on_shutdown"] = False
executor_kwargs["restart_limit"] = restart_limit
Expand DownExpand Up@@ -217,6 +218,7 @@ def _set_process(self, process: list[Thread]): # type: ignore

def _execute_multiple_tasks(
future_queue: queue.Queue,
return_queue: queue.Queue,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
hostname_localhost: Optional[bool] = None,
Expand All@@ -240,6 +242,7 @@ def _execute_multiple_tasks(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
cores (int): defines the total number of MPI ranks to use
spawner (BaseSpawner): Spawner to start process on selected compute resources
hostname_localhost (boolean): use localhost instead of the hostname to establish the zmq connection. In the
Expand DownExpand Up@@ -317,7 +320,7 @@ def _execute_multiple_tasks(
f.set_exception(exception=interface_initialization_exception)
else:
# The interface failed during the execution
interface.status = execute_task_dict(
interface.status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=f,
interface=interface,
Expand All@@ -329,6 +332,8 @@ def _execute_multiple_tasks(
reset_task_dict(
future_obj=f, future_queue=future_queue, task_dict=task_dict
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
task_done(future_queue=future_queue)


Expand Down
14 changes: 14 additions & 0 deletions src/executorlib/task_scheduler/interactive/dependency.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -257,6 +257,10 @@ def _execute_tasks_with_dependencies(
task_dict = future_queue.get_nowait()
except queue.Empty:
task_dict = None
try:
task_return_dict = executor.return_queue.get_nowait()
except (queue.Empty, AttributeError):
task_return_dict = None
if ( # shutdown the executor
task_dict is not None and "shutdown" in task_dict and task_dict["shutdown"]
):
Expand DownExpand Up@@ -324,6 +328,16 @@ def _execute_tasks_with_dependencies(
executor_queue=executor_queue,
refresh_rate=refresh_rate,
)
elif task_return_dict is not None:
# we need this future dict later on to resolve the dependencies
future_lookup_dict = {}
for k, v in task_return_dict.items():
future_lookup_dict[k] = executor.submit(
fn=v["fn"],
*v["args"],
**v["kwargs"],
resource_dict=v["resource_dict"],
)
else:
# If there is nothing else to do, sleep for a moment
sleep(refresh_rate)
Expand Down
14 changes: 12 additions & 2 deletions src/executorlib/task_scheduler/interactive/onetoone.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -61,6 +61,7 @@ def __init__(
executor_kwargs.update(
{
"future_queue": self._future_queue,
"return_queue": self._return_queue,
"spawner": spawner,
"max_cores": max_cores,
"max_workers": max_workers,
Expand All@@ -77,6 +78,7 @@ def __init__(

def _execute_single_task(
future_queue: queue.Queue,
return_queue: queue.Queue,
spawner: type[BaseSpawner] = MpiExecSpawner,
max_cores: Optional[int] = None,
max_workers: Optional[int] = None,
Expand All@@ -88,6 +90,7 @@ def _execute_single_task(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
spawner (BaseSpawner): Interface to start process on selected compute resources
max_cores (int): defines the number cores which can be used in parallel
max_workers (int): for backwards compatibility with the standard library, max_workers also defines the number of
Expand DownExpand Up@@ -116,6 +119,7 @@ def _execute_single_task(
elif "fn" in task_dict and "future" in task_dict:
process, active_task_dict = _wrap_execute_task_in_separate_process(
task_dict=task_dict,
return_queue=return_queue,
active_task_dict=active_task_dict,
spawner=spawner,
executor_kwargs=kwargs,
Expand DownExpand Up@@ -162,6 +166,7 @@ def _wait_for_free_slots(

def _wrap_execute_task_in_separate_process(
task_dict: dict,
return_queue: queue.Queue,
active_task_dict: dict,
spawner: type[BaseSpawner],
executor_kwargs: dict,
Expand DownExpand Up@@ -211,6 +216,7 @@ def _wrap_execute_task_in_separate_process(
task_kwargs.update(
{
"task_dict": task_dict,
"return_queue": return_queue,
"spawner": spawner,
"hostname_localhost": hostname_localhost,
"future_obj": f,
Expand All@@ -226,6 +232,7 @@ def _wrap_execute_task_in_separate_process(

def _execute_task_in_thread(
task_dict: dict,
return_queue: queue.Queue,
future_obj: Future,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
Expand DownExpand Up@@ -262,7 +269,7 @@ def _execute_task_in_thread(
worker_id (int): Communicate the worker which ID was assigned to it for future reference and resource
distribution.
"""
if not execute_task_dict(
status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=future_obj,
interface=interface_bootup(
Expand All@@ -277,7 +284,10 @@ def _execute_task_in_thread(
cache_directory=cache_directory,
cache_key=cache_key,
error_log_file=error_log_file,
):
)
if status is False:
future_obj.set_exception(
ExecutorlibSocketError("SocketInterface crashed during execution.")
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/executorlib/backend/executor_nested.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
from concurrent.futures import Future
from typing import Callable, Optional

from executorlib.standalone.interactive.arguments import (
get_future_objects_from_input,
)


class BackendExecutor:
def __init__(self):
self._tasks_dict = {}
self._future_dict = {}

@property
def tasks(self):
return self._tasks_dict

def batched(
self,
iterable: list[Future],
n: int,
) -> list[Future]:
"""
Batch futures from the iterable into tuples of length n. The last batch may be shorter than n.

Args:
iterable (list): list of future objects to batch based on which future objects finish first
n (int): badge size

Returns:
list[Future]: list of future objects one for each batch
"""
raise NotImplementedError("The batched method is not implemented.")

def map(
self,
fn: Callable,
*iterables,
timeout: Optional[float] = None,
chunksize: int = 1,
):
"""Returns an iterator equivalent to map(fn, iter).

Args:
fn: A callable that will take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
chunksize: The size of the chunks the iterable will be broken into
before being passed to a child process. This argument is only
used by ProcessPoolExecutor; it is ignored by
ThreadPoolExecutor.

Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.

Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values.
"""
raise NotImplementedError("The map method is not implemented.")

def submit( # type: ignore
self,
fn: Callable,
/,
*args,
resource_dict: Optional[dict] = None,
**kwargs,
) -> Future:
"""
Submits a callable to be executed with the given arguments.

Schedules the callable to be executed as fn(*args, **kwargs) and returns
a Future instance representing the execution of the callable.

Args:
fn (callable): function to submit for execution
args: arguments for the submitted function
kwargs: keyword arguments for the submitted function
resource_dict (dict): A dictionary of resources required by the task. With the following keys:
- cores (int): number of MPI cores to be used for each function call
- threads_per_core (int): number of OpenMP threads to be used for each function call
- gpus_per_core (int): number of GPUs per worker - defaults to 0
- cwd (str/None): current working directory where the parallel python task is executed
- openmpi_oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI and
SLURM only) - default False
- slurm_cmd_args (list): Additional command line arguments for the srun call (SLURM only)
- error_log_file (str): Name of the error log file to use for storing exceptions raised
by the Python functions submitted to the Executor.

Returns:
Future: A Future representing the given call.
"""
if resource_dict is None:
resource_dict = {}
f: Future = Future()
self._future_dict[f] = id(f)
self._tasks_dict[id(f)] = {
"fn": fn,
"args": args, # at the momemt the future objects are not removed from the args
"kwargs": kwargs, # at the momemt the future objects are not removed from the kwargs
"resource_dict": resource_dict,
"dependencies": [
self._future_dict[future_dependency]
for future_dependency in get_future_objects_from_input(
args=args, kwargs=kwargs
)
],
}
return f
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_parallel.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
import cloudpickle
import zmq

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -43,7 +44,11 @@ def main() -> None:
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -90,7 +95,13 @@ def main() -> None:
else:
# Send output
if mpi_rank_zero:
interface_send(socket=socket, result_dict={"result": output_reply})
interface_send(
socket=socket,
result_dict={
"result": output_reply,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_serial.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
from os.path import abspath
from typing import Optional

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -29,7 +30,11 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -65,7 +70,13 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
)
else:
# Send output
interface_send(socket=socket, result_dict={"result": output})
interface_send(
socket=socket,
result_dict={
"result": output,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 15 additions & 0 deletions src/executorlib/task_scheduler/base.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ def __init__(
self._process_kwargs: dict = {}
self._max_cores = max_cores
self._future_queue: Optional[queue.Queue] = queue.Queue()
self._return_queue: Optional[queue.Queue] = queue.Queue()
self._process: Optional[Union[Thread, list[Thread]]] = None
self._validator = validator

Expand DownExpand Up@@ -84,6 +85,8 @@ def info(self) -> Optional[dict]:
meta_data_dict = self._process_kwargs.copy()
if "future_queue" in meta_data_dict:
del meta_data_dict["future_queue"]
if "return_queue" in meta_data_dict:
del meta_data_dict["return_queue"]
if self._process is not None and isinstance(self._process, list):
meta_data_dict["max_workers"] = len(self._process)
return meta_data_dict
Expand All@@ -102,6 +105,16 @@ def future_queue(self) -> Optional[queue.Queue]:
"""
return self._future_queue

@property
def return_queue(self) -> Optional[queue.Queue]:
"""
Get the return queue.

Returns:
queue.Queue: The return queue.
"""
return self._return_queue

def batched(
self,
iterable: list[Future],
Expand DownExpand Up@@ -238,8 +251,10 @@ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False):
if isinstance(self._process, Thread):
self._process.join()
self._future_queue.join()
self._return_queue.join()
self._process = None
self._future_queue = None
self._return_queue = None

def _set_process(self, process: Thread):
"""
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -75,6 +75,7 @@ def __init__(
max_cores=executor_kwargs.get("max_cores"), validator=validator
)
executor_kwargs["future_queue"] = self._future_queue
executor_kwargs["return_queue"] = self._return_queue
executor_kwargs["spawner"] = spawner
executor_kwargs["queue_join_on_shutdown"] = False
executor_kwargs["restart_limit"] = restart_limit
Expand DownExpand Up@@ -217,6 +218,7 @@ def _set_process(self, process: list[Thread]): # type: ignore

def _execute_multiple_tasks(
future_queue: queue.Queue,
return_queue: queue.Queue,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
hostname_localhost: Optional[bool] = None,
Expand All@@ -240,6 +242,7 @@ def _execute_multiple_tasks(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
cores (int): defines the total number of MPI ranks to use
spawner (BaseSpawner): Spawner to start process on selected compute resources
hostname_localhost (boolean): use localhost instead of the hostname to establish the zmq connection. In the
Expand DownExpand Up@@ -317,7 +320,7 @@ def _execute_multiple_tasks(
f.set_exception(exception=interface_initialization_exception)
else:
# The interface failed during the execution
interface.status = execute_task_dict(
interface.status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=f,
interface=interface,
Expand All@@ -329,6 +332,8 @@ def _execute_multiple_tasks(
reset_task_dict(
future_obj=f, future_queue=future_queue, task_dict=task_dict
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
task_done(future_queue=future_queue)


Expand Down
14 changes: 14 additions & 0 deletions src/executorlib/task_scheduler/interactive/dependency.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -257,6 +257,10 @@ def _execute_tasks_with_dependencies(
task_dict = future_queue.get_nowait()
except queue.Empty:
task_dict = None
try:
task_return_dict = executor.return_queue.get_nowait()
except (queue.Empty, AttributeError):
task_return_dict = None
if ( # shutdown the executor
task_dict is not None and "shutdown" in task_dict and task_dict["shutdown"]
):
Expand DownExpand Up@@ -324,6 +328,16 @@ def _execute_tasks_with_dependencies(
executor_queue=executor_queue,
refresh_rate=refresh_rate,
)
elif task_return_dict is not None:
# we need this future dict later on to resolve the dependencies
future_lookup_dict = {}
for k, v in task_return_dict.items():
future_lookup_dict[k] = executor.submit(
fn=v["fn"],
*v["args"],
**v["kwargs"],
resource_dict=v["resource_dict"],
)
else:
# If there is nothing else to do, sleep for a moment
sleep(refresh_rate)
Expand Down
14 changes: 12 additions & 2 deletions src/executorlib/task_scheduler/interactive/onetoone.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -61,6 +61,7 @@ def __init__(
executor_kwargs.update(
{
"future_queue": self._future_queue,
"return_queue": self._return_queue,
"spawner": spawner,
"max_cores": max_cores,
"max_workers": max_workers,
Expand All@@ -77,6 +78,7 @@ def __init__(

def _execute_single_task(
future_queue: queue.Queue,
return_queue: queue.Queue,
spawner: type[BaseSpawner] = MpiExecSpawner,
max_cores: Optional[int] = None,
max_workers: Optional[int] = None,
Expand All@@ -88,6 +90,7 @@ def _execute_single_task(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
spawner (BaseSpawner): Interface to start process on selected compute resources
max_cores (int): defines the number cores which can be used in parallel
max_workers (int): for backwards compatibility with the standard library, max_workers also defines the number of
Expand DownExpand Up@@ -116,6 +119,7 @@ def _execute_single_task(
elif "fn" in task_dict and "future" in task_dict:
process, active_task_dict = _wrap_execute_task_in_separate_process(
task_dict=task_dict,
return_queue=return_queue,
active_task_dict=active_task_dict,
spawner=spawner,
executor_kwargs=kwargs,
Expand DownExpand Up@@ -162,6 +166,7 @@ def _wait_for_free_slots(

def _wrap_execute_task_in_separate_process(
task_dict: dict,
return_queue: queue.Queue,
active_task_dict: dict,
spawner: type[BaseSpawner],
executor_kwargs: dict,
Expand DownExpand Up@@ -211,6 +216,7 @@ def _wrap_execute_task_in_separate_process(
task_kwargs.update(
{
"task_dict": task_dict,
"return_queue": return_queue,
"spawner": spawner,
"hostname_localhost": hostname_localhost,
"future_obj": f,
Expand All@@ -226,6 +232,7 @@ def _wrap_execute_task_in_separate_process(

def _execute_task_in_thread(
task_dict: dict,
return_queue: queue.Queue,
future_obj: Future,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
Expand DownExpand Up@@ -262,7 +269,7 @@ def _execute_task_in_thread(
worker_id (int): Communicate the worker which ID was assigned to it for future reference and resource
distribution.
"""
if not execute_task_dict(
status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=future_obj,
interface=interface_bootup(
Expand All@@ -277,7 +284,10 @@ def _execute_task_in_thread(
cache_directory=cache_directory,
cache_key=cache_key,
error_log_file=error_log_file,
):
)
if status is False:
future_obj.set_exception(
ExecutorlibSocketError("SocketInterface crashed during execution.")
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/executorlib/backend/executor_nested.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
from concurrent.futures import Future
from typing import Callable, Optional

from executorlib.standalone.interactive.arguments import (
get_future_objects_from_input,
)


class BackendExecutor:
def __init__(self):
self._tasks_dict = {}
self._future_dict = {}

@property
def tasks(self):
return self._tasks_dict

def batched(
self,
iterable: list[Future],
n: int,
) -> list[Future]:
"""
Batch futures from the iterable into tuples of length n. The last batch may be shorter than n.

Args:
iterable (list): list of future objects to batch based on which future objects finish first
n (int): badge size

Returns:
list[Future]: list of future objects one for each batch
"""
raise NotImplementedError("The batched method is not implemented.")

def map(
self,
fn: Callable,
*iterables,
timeout: Optional[float] = None,
chunksize: int = 1,
):
"""Returns an iterator equivalent to map(fn, iter).

Args:
fn: A callable that will take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
chunksize: The size of the chunks the iterable will be broken into
before being passed to a child process. This argument is only
used by ProcessPoolExecutor; it is ignored by
ThreadPoolExecutor.

Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.

Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values.
"""
raise NotImplementedError("The map method is not implemented.")

def submit( # type: ignore
self,
fn: Callable,
/,
*args,
resource_dict: Optional[dict] = None,
**kwargs,
) -> Future:
"""
Submits a callable to be executed with the given arguments.

Schedules the callable to be executed as fn(*args, **kwargs) and returns
a Future instance representing the execution of the callable.

Args:
fn (callable): function to submit for execution
args: arguments for the submitted function
kwargs: keyword arguments for the submitted function
resource_dict (dict): A dictionary of resources required by the task. With the following keys:
- cores (int): number of MPI cores to be used for each function call
- threads_per_core (int): number of OpenMP threads to be used for each function call
- gpus_per_core (int): number of GPUs per worker - defaults to 0
- cwd (str/None): current working directory where the parallel python task is executed
- openmpi_oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI and
SLURM only) - default False
- slurm_cmd_args (list): Additional command line arguments for the srun call (SLURM only)
- error_log_file (str): Name of the error log file to use for storing exceptions raised
by the Python functions submitted to the Executor.

Returns:
Future: A Future representing the given call.
"""
if resource_dict is None:
resource_dict = {}
f: Future = Future()
self._future_dict[f] = id(f)
self._tasks_dict[id(f)] = {
"fn": fn,
"args": args, # at the momemt the future objects are not removed from the args
"kwargs": kwargs, # at the momemt the future objects are not removed from the kwargs
"resource_dict": resource_dict,
"dependencies": [
self._future_dict[future_dependency]
for future_dependency in get_future_objects_from_input(
args=args, kwargs=kwargs
)
],
}
return f
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_parallel.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
import cloudpickle
import zmq

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -43,7 +44,11 @@ def main() -> None:
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -90,7 +95,13 @@ def main() -> None:
else:
# Send output
if mpi_rank_zero:
interface_send(socket=socket, result_dict={"result": output_reply})
interface_send(
socket=socket,
result_dict={
"result": output_reply,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_serial.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
from os.path import abspath
from typing import Optional

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -29,7 +30,11 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -65,7 +70,13 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
)
else:
# Send output
interface_send(socket=socket, result_dict={"result": output})
interface_send(
socket=socket,
result_dict={
"result": output,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 15 additions & 0 deletions src/executorlib/task_scheduler/base.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ def __init__(
self._process_kwargs: dict = {}
self._max_cores = max_cores
self._future_queue: Optional[queue.Queue] = queue.Queue()
self._return_queue: Optional[queue.Queue] = queue.Queue()
self._process: Optional[Union[Thread, list[Thread]]] = None
self._validator = validator

Expand DownExpand Up@@ -84,6 +85,8 @@ def info(self) -> Optional[dict]:
meta_data_dict = self._process_kwargs.copy()
if "future_queue" in meta_data_dict:
del meta_data_dict["future_queue"]
if "return_queue" in meta_data_dict:
del meta_data_dict["return_queue"]
if self._process is not None and isinstance(self._process, list):
meta_data_dict["max_workers"] = len(self._process)
return meta_data_dict
Expand All@@ -102,6 +105,16 @@ def future_queue(self) -> Optional[queue.Queue]:
"""
return self._future_queue

@property
def return_queue(self) -> Optional[queue.Queue]:
"""
Get the return queue.

Returns:
queue.Queue: The return queue.
"""
return self._return_queue

def batched(
self,
iterable: list[Future],
Expand DownExpand Up@@ -238,8 +251,10 @@ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False):
if isinstance(self._process, Thread):
self._process.join()
self._future_queue.join()
self._return_queue.join()
self._process = None
self._future_queue = None
self._return_queue = None

def _set_process(self, process: Thread):
"""
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -75,6 +75,7 @@ def __init__(
max_cores=executor_kwargs.get("max_cores"), validator=validator
)
executor_kwargs["future_queue"] = self._future_queue
executor_kwargs["return_queue"] = self._return_queue
executor_kwargs["spawner"] = spawner
executor_kwargs["queue_join_on_shutdown"] = False
executor_kwargs["restart_limit"] = restart_limit
Expand DownExpand Up@@ -217,6 +218,7 @@ def _set_process(self, process: list[Thread]): # type: ignore

def _execute_multiple_tasks(
future_queue: queue.Queue,
return_queue: queue.Queue,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
hostname_localhost: Optional[bool] = None,
Expand All@@ -240,6 +242,7 @@ def _execute_multiple_tasks(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
cores (int): defines the total number of MPI ranks to use
spawner (BaseSpawner): Spawner to start process on selected compute resources
hostname_localhost (boolean): use localhost instead of the hostname to establish the zmq connection. In the
Expand DownExpand Up@@ -317,7 +320,7 @@ def _execute_multiple_tasks(
f.set_exception(exception=interface_initialization_exception)
else:
# The interface failed during the execution
interface.status = execute_task_dict(
interface.status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=f,
interface=interface,
Expand All@@ -329,6 +332,8 @@ def _execute_multiple_tasks(
reset_task_dict(
future_obj=f, future_queue=future_queue, task_dict=task_dict
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
task_done(future_queue=future_queue)


Expand Down
14 changes: 14 additions & 0 deletions src/executorlib/task_scheduler/interactive/dependency.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -257,6 +257,10 @@ def _execute_tasks_with_dependencies(
task_dict = future_queue.get_nowait()
except queue.Empty:
task_dict = None
try:
task_return_dict = executor.return_queue.get_nowait()
except (queue.Empty, AttributeError):
task_return_dict = None
if ( # shutdown the executor
task_dict is not None and "shutdown" in task_dict and task_dict["shutdown"]
):
Expand DownExpand Up@@ -324,6 +328,16 @@ def _execute_tasks_with_dependencies(
executor_queue=executor_queue,
refresh_rate=refresh_rate,
)
elif task_return_dict is not None:
# we need this future dict later on to resolve the dependencies
future_lookup_dict = {}
for k, v in task_return_dict.items():
future_lookup_dict[k] = executor.submit(
fn=v["fn"],
*v["args"],
**v["kwargs"],
resource_dict=v["resource_dict"],
)
else:
# If there is nothing else to do, sleep for a moment
sleep(refresh_rate)
Expand Down
14 changes: 12 additions & 2 deletions src/executorlib/task_scheduler/interactive/onetoone.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -61,6 +61,7 @@ def __init__(
executor_kwargs.update(
{
"future_queue": self._future_queue,
"return_queue": self._return_queue,
"spawner": spawner,
"max_cores": max_cores,
"max_workers": max_workers,
Expand All@@ -77,6 +78,7 @@ def __init__(

def _execute_single_task(
future_queue: queue.Queue,
return_queue: queue.Queue,
spawner: type[BaseSpawner] = MpiExecSpawner,
max_cores: Optional[int] = None,
max_workers: Optional[int] = None,
Expand All@@ -88,6 +90,7 @@ def _execute_single_task(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
spawner (BaseSpawner): Interface to start process on selected compute resources
max_cores (int): defines the number cores which can be used in parallel
max_workers (int): for backwards compatibility with the standard library, max_workers also defines the number of
Expand DownExpand Up@@ -116,6 +119,7 @@ def _execute_single_task(
elif "fn" in task_dict and "future" in task_dict:
process, active_task_dict = _wrap_execute_task_in_separate_process(
task_dict=task_dict,
return_queue=return_queue,
active_task_dict=active_task_dict,
spawner=spawner,
executor_kwargs=kwargs,
Expand DownExpand Up@@ -162,6 +166,7 @@ def _wait_for_free_slots(

def _wrap_execute_task_in_separate_process(
task_dict: dict,
return_queue: queue.Queue,
active_task_dict: dict,
spawner: type[BaseSpawner],
executor_kwargs: dict,
Expand DownExpand Up@@ -211,6 +216,7 @@ def _wrap_execute_task_in_separate_process(
task_kwargs.update(
{
"task_dict": task_dict,
"return_queue": return_queue,
"spawner": spawner,
"hostname_localhost": hostname_localhost,
"future_obj": f,
Expand All@@ -226,6 +232,7 @@ def _wrap_execute_task_in_separate_process(

def _execute_task_in_thread(
task_dict: dict,
return_queue: queue.Queue,
future_obj: Future,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
Expand DownExpand Up@@ -262,7 +269,7 @@ def _execute_task_in_thread(
worker_id (int): Communicate the worker which ID was assigned to it for future reference and resource
distribution.
"""
if not execute_task_dict(
status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=future_obj,
interface=interface_bootup(
Expand All@@ -277,7 +284,10 @@ def _execute_task_in_thread(
cache_directory=cache_directory,
cache_key=cache_key,
error_log_file=error_log_file,
):
)
if status is False:
future_obj.set_exception(
ExecutorlibSocketError("SocketInterface crashed during execution.")
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/executorlib/backend/executor_nested.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
from concurrent.futures import Future
from typing import Callable, Optional

from executorlib.standalone.interactive.arguments import (
get_future_objects_from_input,
)


class BackendExecutor:
def __init__(self):
self._tasks_dict = {}
self._future_dict = {}

@property
def tasks(self):
return self._tasks_dict

def batched(
self,
iterable: list[Future],
n: int,
) -> list[Future]:
"""
Batch futures from the iterable into tuples of length n. The last batch may be shorter than n.

Args:
iterable (list): list of future objects to batch based on which future objects finish first
n (int): badge size

Returns:
list[Future]: list of future objects one for each batch
"""
raise NotImplementedError("The batched method is not implemented.")

def map(
self,
fn: Callable,
*iterables,
timeout: Optional[float] = None,
chunksize: int = 1,
):
"""Returns an iterator equivalent to map(fn, iter).

Args:
fn: A callable that will take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
chunksize: The size of the chunks the iterable will be broken into
before being passed to a child process. This argument is only
used by ProcessPoolExecutor; it is ignored by
ThreadPoolExecutor.

Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.

Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values.
"""
raise NotImplementedError("The map method is not implemented.")

def submit( # type: ignore
self,
fn: Callable,
/,
*args,
resource_dict: Optional[dict] = None,
**kwargs,
) -> Future:
"""
Submits a callable to be executed with the given arguments.

Schedules the callable to be executed as fn(*args, **kwargs) and returns
a Future instance representing the execution of the callable.

Args:
fn (callable): function to submit for execution
args: arguments for the submitted function
kwargs: keyword arguments for the submitted function
resource_dict (dict): A dictionary of resources required by the task. With the following keys:
- cores (int): number of MPI cores to be used for each function call
- threads_per_core (int): number of OpenMP threads to be used for each function call
- gpus_per_core (int): number of GPUs per worker - defaults to 0
- cwd (str/None): current working directory where the parallel python task is executed
- openmpi_oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI and
SLURM only) - default False
- slurm_cmd_args (list): Additional command line arguments for the srun call (SLURM only)
- error_log_file (str): Name of the error log file to use for storing exceptions raised
by the Python functions submitted to the Executor.

Returns:
Future: A Future representing the given call.
"""
if resource_dict is None:
resource_dict = {}
f: Future = Future()
self._future_dict[f] = id(f)
self._tasks_dict[id(f)] = {
"fn": fn,
"args": args, # at the momemt the future objects are not removed from the args
"kwargs": kwargs, # at the momemt the future objects are not removed from the kwargs
"resource_dict": resource_dict,
"dependencies": [
self._future_dict[future_dependency]
for future_dependency in get_future_objects_from_input(
args=args, kwargs=kwargs
)
],
}
return f
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_parallel.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
import cloudpickle
import zmq

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -43,7 +44,11 @@ def main() -> None:
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -90,7 +95,13 @@ def main() -> None:
else:
# Send output
if mpi_rank_zero:
interface_send(socket=socket, result_dict={"result": output_reply})
interface_send(
socket=socket,
result_dict={
"result": output_reply,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_serial.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
from os.path import abspath
from typing import Optional

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -29,7 +30,11 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -65,7 +70,13 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
)
else:
# Send output
interface_send(socket=socket, result_dict={"result": output})
interface_send(
socket=socket,
result_dict={
"result": output,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 15 additions & 0 deletions src/executorlib/task_scheduler/base.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ def __init__(
self._process_kwargs: dict = {}
self._max_cores = max_cores
self._future_queue: Optional[queue.Queue] = queue.Queue()
self._return_queue: Optional[queue.Queue] = queue.Queue()
self._process: Optional[Union[Thread, list[Thread]]] = None
self._validator = validator

Expand DownExpand Up@@ -84,6 +85,8 @@ def info(self) -> Optional[dict]:
meta_data_dict = self._process_kwargs.copy()
if "future_queue" in meta_data_dict:
del meta_data_dict["future_queue"]
if "return_queue" in meta_data_dict:
del meta_data_dict["return_queue"]
if self._process is not None and isinstance(self._process, list):
meta_data_dict["max_workers"] = len(self._process)
return meta_data_dict
Expand All@@ -102,6 +105,16 @@ def future_queue(self) -> Optional[queue.Queue]:
"""
return self._future_queue

@property
def return_queue(self) -> Optional[queue.Queue]:
"""
Get the return queue.

Returns:
queue.Queue: The return queue.
"""
return self._return_queue

def batched(
self,
iterable: list[Future],
Expand DownExpand Up@@ -238,8 +251,10 @@ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False):
if isinstance(self._process, Thread):
self._process.join()
self._future_queue.join()
self._return_queue.join()
self._process = None
self._future_queue = None
self._return_queue = None

def _set_process(self, process: Thread):
"""
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -75,6 +75,7 @@ def __init__(
max_cores=executor_kwargs.get("max_cores"), validator=validator
)
executor_kwargs["future_queue"] = self._future_queue
executor_kwargs["return_queue"] = self._return_queue
executor_kwargs["spawner"] = spawner
executor_kwargs["queue_join_on_shutdown"] = False
executor_kwargs["restart_limit"] = restart_limit
Expand DownExpand Up@@ -217,6 +218,7 @@ def _set_process(self, process: list[Thread]): # type: ignore

def _execute_multiple_tasks(
future_queue: queue.Queue,
return_queue: queue.Queue,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
hostname_localhost: Optional[bool] = None,
Expand All@@ -240,6 +242,7 @@ def _execute_multiple_tasks(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
cores (int): defines the total number of MPI ranks to use
spawner (BaseSpawner): Spawner to start process on selected compute resources
hostname_localhost (boolean): use localhost instead of the hostname to establish the zmq connection. In the
Expand DownExpand Up@@ -317,7 +320,7 @@ def _execute_multiple_tasks(
f.set_exception(exception=interface_initialization_exception)
else:
# The interface failed during the execution
interface.status = execute_task_dict(
interface.status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=f,
interface=interface,
Expand All@@ -329,6 +332,8 @@ def _execute_multiple_tasks(
reset_task_dict(
future_obj=f, future_queue=future_queue, task_dict=task_dict
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
task_done(future_queue=future_queue)


Expand Down
14 changes: 14 additions & 0 deletions src/executorlib/task_scheduler/interactive/dependency.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -257,6 +257,10 @@ def _execute_tasks_with_dependencies(
task_dict = future_queue.get_nowait()
except queue.Empty:
task_dict = None
try:
task_return_dict = executor.return_queue.get_nowait()
except (queue.Empty, AttributeError):
task_return_dict = None
if ( # shutdown the executor
task_dict is not None and "shutdown" in task_dict and task_dict["shutdown"]
):
Expand DownExpand Up@@ -324,6 +328,16 @@ def _execute_tasks_with_dependencies(
executor_queue=executor_queue,
refresh_rate=refresh_rate,
)
elif task_return_dict is not None:
# we need this future dict later on to resolve the dependencies
future_lookup_dict = {}
for k, v in task_return_dict.items():
future_lookup_dict[k] = executor.submit(
fn=v["fn"],
*v["args"],
**v["kwargs"],
resource_dict=v["resource_dict"],
)
else:
# If there is nothing else to do, sleep for a moment
sleep(refresh_rate)
Expand Down
14 changes: 12 additions & 2 deletions src/executorlib/task_scheduler/interactive/onetoone.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -61,6 +61,7 @@ def __init__(
executor_kwargs.update(
{
"future_queue": self._future_queue,
"return_queue": self._return_queue,
"spawner": spawner,
"max_cores": max_cores,
"max_workers": max_workers,
Expand All@@ -77,6 +78,7 @@ def __init__(

def _execute_single_task(
future_queue: queue.Queue,
return_queue: queue.Queue,
spawner: type[BaseSpawner] = MpiExecSpawner,
max_cores: Optional[int] = None,
max_workers: Optional[int] = None,
Expand All@@ -88,6 +90,7 @@ def _execute_single_task(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
spawner (BaseSpawner): Interface to start process on selected compute resources
max_cores (int): defines the number cores which can be used in parallel
max_workers (int): for backwards compatibility with the standard library, max_workers also defines the number of
Expand DownExpand Up@@ -116,6 +119,7 @@ def _execute_single_task(
elif "fn" in task_dict and "future" in task_dict:
process, active_task_dict = _wrap_execute_task_in_separate_process(
task_dict=task_dict,
return_queue=return_queue,
active_task_dict=active_task_dict,
spawner=spawner,
executor_kwargs=kwargs,
Expand DownExpand Up@@ -162,6 +166,7 @@ def _wait_for_free_slots(

def _wrap_execute_task_in_separate_process(
task_dict: dict,
return_queue: queue.Queue,
active_task_dict: dict,
spawner: type[BaseSpawner],
executor_kwargs: dict,
Expand DownExpand Up@@ -211,6 +216,7 @@ def _wrap_execute_task_in_separate_process(
task_kwargs.update(
{
"task_dict": task_dict,
"return_queue": return_queue,
"spawner": spawner,
"hostname_localhost": hostname_localhost,
"future_obj": f,
Expand All@@ -226,6 +232,7 @@ def _wrap_execute_task_in_separate_process(

def _execute_task_in_thread(
task_dict: dict,
return_queue: queue.Queue,
future_obj: Future,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
Expand DownExpand Up@@ -262,7 +269,7 @@ def _execute_task_in_thread(
worker_id (int): Communicate the worker which ID was assigned to it for future reference and resource
distribution.
"""
if not execute_task_dict(
status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=future_obj,
interface=interface_bootup(
Expand All@@ -277,7 +284,10 @@ def _execute_task_in_thread(
cache_directory=cache_directory,
cache_key=cache_key,
error_log_file=error_log_file,
):
)
if status is False:
future_obj.set_exception(
ExecutorlibSocketError("SocketInterface crashed during execution.")
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/executorlib/backend/executor_nested.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
from concurrent.futures import Future
from typing import Callable, Optional

from executorlib.standalone.interactive.arguments import (
get_future_objects_from_input,
)


class BackendExecutor:
def __init__(self):
self._tasks_dict = {}
self._future_dict = {}

@property
def tasks(self):
return self._tasks_dict

def batched(
self,
iterable: list[Future],
n: int,
) -> list[Future]:
"""
Batch futures from the iterable into tuples of length n. The last batch may be shorter than n.

Args:
iterable (list): list of future objects to batch based on which future objects finish first
n (int): badge size

Returns:
list[Future]: list of future objects one for each batch
"""
raise NotImplementedError("The batched method is not implemented.")

def map(
self,
fn: Callable,
*iterables,
timeout: Optional[float] = None,
chunksize: int = 1,
):
"""Returns an iterator equivalent to map(fn, iter).

Args:
fn: A callable that will take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
chunksize: The size of the chunks the iterable will be broken into
before being passed to a child process. This argument is only
used by ProcessPoolExecutor; it is ignored by
ThreadPoolExecutor.

Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.

Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values.
"""
raise NotImplementedError("The map method is not implemented.")

def submit( # type: ignore
self,
fn: Callable,
/,
*args,
resource_dict: Optional[dict] = None,
**kwargs,
) -> Future:
"""
Submits a callable to be executed with the given arguments.

Schedules the callable to be executed as fn(*args, **kwargs) and returns
a Future instance representing the execution of the callable.

Args:
fn (callable): function to submit for execution
args: arguments for the submitted function
kwargs: keyword arguments for the submitted function
resource_dict (dict): A dictionary of resources required by the task. With the following keys:
- cores (int): number of MPI cores to be used for each function call
- threads_per_core (int): number of OpenMP threads to be used for each function call
- gpus_per_core (int): number of GPUs per worker - defaults to 0
- cwd (str/None): current working directory where the parallel python task is executed
- openmpi_oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI and
SLURM only) - default False
- slurm_cmd_args (list): Additional command line arguments for the srun call (SLURM only)
- error_log_file (str): Name of the error log file to use for storing exceptions raised
by the Python functions submitted to the Executor.

Returns:
Future: A Future representing the given call.
"""
if resource_dict is None:
resource_dict = {}
f: Future = Future()
self._future_dict[f] = id(f)
self._tasks_dict[id(f)] = {
"fn": fn,
"args": args, # at the momemt the future objects are not removed from the args
"kwargs": kwargs, # at the momemt the future objects are not removed from the kwargs
"resource_dict": resource_dict,
"dependencies": [
self._future_dict[future_dependency]
for future_dependency in get_future_objects_from_input(
args=args, kwargs=kwargs
)
],
}
return f
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_parallel.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
import cloudpickle
import zmq

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -43,7 +44,11 @@ def main() -> None:
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -90,7 +95,13 @@ def main() -> None:
else:
# Send output
if mpi_rank_zero:
interface_send(socket=socket, result_dict={"result": output_reply})
interface_send(
socket=socket,
result_dict={
"result": output_reply,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_serial.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
from os.path import abspath
from typing import Optional

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -29,7 +30,11 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -65,7 +70,13 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
)
else:
# Send output
interface_send(socket=socket, result_dict={"result": output})
interface_send(
socket=socket,
result_dict={
"result": output,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 15 additions & 0 deletions src/executorlib/task_scheduler/base.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ def __init__(
self._process_kwargs: dict = {}
self._max_cores = max_cores
self._future_queue: Optional[queue.Queue] = queue.Queue()
self._return_queue: Optional[queue.Queue] = queue.Queue()
self._process: Optional[Union[Thread, list[Thread]]] = None
self._validator = validator

Expand DownExpand Up@@ -84,6 +85,8 @@ def info(self) -> Optional[dict]:
meta_data_dict = self._process_kwargs.copy()
if "future_queue" in meta_data_dict:
del meta_data_dict["future_queue"]
if "return_queue" in meta_data_dict:
del meta_data_dict["return_queue"]
if self._process is not None and isinstance(self._process, list):
meta_data_dict["max_workers"] = len(self._process)
return meta_data_dict
Expand All@@ -102,6 +105,16 @@ def future_queue(self) -> Optional[queue.Queue]:
"""
return self._future_queue

@property
def return_queue(self) -> Optional[queue.Queue]:
"""
Get the return queue.

Returns:
queue.Queue: The return queue.
"""
return self._return_queue

def batched(
self,
iterable: list[Future],
Expand DownExpand Up@@ -238,8 +251,10 @@ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False):
if isinstance(self._process, Thread):
self._process.join()
self._future_queue.join()
self._return_queue.join()
self._process = None
self._future_queue = None
self._return_queue = None

def _set_process(self, process: Thread):
"""
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -75,6 +75,7 @@ def __init__(
max_cores=executor_kwargs.get("max_cores"), validator=validator
)
executor_kwargs["future_queue"] = self._future_queue
executor_kwargs["return_queue"] = self._return_queue
executor_kwargs["spawner"] = spawner
executor_kwargs["queue_join_on_shutdown"] = False
executor_kwargs["restart_limit"] = restart_limit
Expand DownExpand Up@@ -217,6 +218,7 @@ def _set_process(self, process: list[Thread]): # type: ignore

def _execute_multiple_tasks(
future_queue: queue.Queue,
return_queue: queue.Queue,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
hostname_localhost: Optional[bool] = None,
Expand All@@ -240,6 +242,7 @@ def _execute_multiple_tasks(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
cores (int): defines the total number of MPI ranks to use
spawner (BaseSpawner): Spawner to start process on selected compute resources
hostname_localhost (boolean): use localhost instead of the hostname to establish the zmq connection. In the
Expand DownExpand Up@@ -317,7 +320,7 @@ def _execute_multiple_tasks(
f.set_exception(exception=interface_initialization_exception)
else:
# The interface failed during the execution
interface.status = execute_task_dict(
interface.status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=f,
interface=interface,
Expand All@@ -329,6 +332,8 @@ def _execute_multiple_tasks(
reset_task_dict(
future_obj=f, future_queue=future_queue, task_dict=task_dict
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
task_done(future_queue=future_queue)


Expand Down
14 changes: 14 additions & 0 deletions src/executorlib/task_scheduler/interactive/dependency.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -257,6 +257,10 @@ def _execute_tasks_with_dependencies(
task_dict = future_queue.get_nowait()
except queue.Empty:
task_dict = None
try:
task_return_dict = executor.return_queue.get_nowait()
except (queue.Empty, AttributeError):
task_return_dict = None
if ( # shutdown the executor
task_dict is not None and "shutdown" in task_dict and task_dict["shutdown"]
):
Expand DownExpand Up@@ -324,6 +328,16 @@ def _execute_tasks_with_dependencies(
executor_queue=executor_queue,
refresh_rate=refresh_rate,
)
elif task_return_dict is not None:
# we need this future dict later on to resolve the dependencies
future_lookup_dict = {}
for k, v in task_return_dict.items():
future_lookup_dict[k] = executor.submit(
fn=v["fn"],
*v["args"],
**v["kwargs"],
resource_dict=v["resource_dict"],
)
else:
# If there is nothing else to do, sleep for a moment
sleep(refresh_rate)
Expand Down
14 changes: 12 additions & 2 deletions src/executorlib/task_scheduler/interactive/onetoone.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -61,6 +61,7 @@ def __init__(
executor_kwargs.update(
{
"future_queue": self._future_queue,
"return_queue": self._return_queue,
"spawner": spawner,
"max_cores": max_cores,
"max_workers": max_workers,
Expand All@@ -77,6 +78,7 @@ def __init__(

def _execute_single_task(
future_queue: queue.Queue,
return_queue: queue.Queue,
spawner: type[BaseSpawner] = MpiExecSpawner,
max_cores: Optional[int] = None,
max_workers: Optional[int] = None,
Expand All@@ -88,6 +90,7 @@ def _execute_single_task(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
spawner (BaseSpawner): Interface to start process on selected compute resources
max_cores (int): defines the number cores which can be used in parallel
max_workers (int): for backwards compatibility with the standard library, max_workers also defines the number of
Expand DownExpand Up@@ -116,6 +119,7 @@ def _execute_single_task(
elif "fn" in task_dict and "future" in task_dict:
process, active_task_dict = _wrap_execute_task_in_separate_process(
task_dict=task_dict,
return_queue=return_queue,
active_task_dict=active_task_dict,
spawner=spawner,
executor_kwargs=kwargs,
Expand DownExpand Up@@ -162,6 +166,7 @@ def _wait_for_free_slots(

def _wrap_execute_task_in_separate_process(
task_dict: dict,
return_queue: queue.Queue,
active_task_dict: dict,
spawner: type[BaseSpawner],
executor_kwargs: dict,
Expand DownExpand Up@@ -211,6 +216,7 @@ def _wrap_execute_task_in_separate_process(
task_kwargs.update(
{
"task_dict": task_dict,
"return_queue": return_queue,
"spawner": spawner,
"hostname_localhost": hostname_localhost,
"future_obj": f,
Expand All@@ -226,6 +232,7 @@ def _wrap_execute_task_in_separate_process(

def _execute_task_in_thread(
task_dict: dict,
return_queue: queue.Queue,
future_obj: Future,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
Expand DownExpand Up@@ -262,7 +269,7 @@ def _execute_task_in_thread(
worker_id (int): Communicate the worker which ID was assigned to it for future reference and resource
distribution.
"""
if not execute_task_dict(
status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=future_obj,
interface=interface_bootup(
Expand All@@ -277,7 +284,10 @@ def _execute_task_in_thread(
cache_directory=cache_directory,
cache_key=cache_key,
error_log_file=error_log_file,
):
)
if status is False:
future_obj.set_exception(
ExecutorlibSocketError("SocketInterface crashed during execution.")
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/executorlib/backend/executor_nested.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
from concurrent.futures import Future
from typing import Callable, Optional

from executorlib.standalone.interactive.arguments import (
get_future_objects_from_input,
)


class BackendExecutor:
def __init__(self):
self._tasks_dict = {}
self._future_dict = {}

@property
def tasks(self):
return self._tasks_dict

def batched(
self,
iterable: list[Future],
n: int,
) -> list[Future]:
"""
Batch futures from the iterable into tuples of length n. The last batch may be shorter than n.

Args:
iterable (list): list of future objects to batch based on which future objects finish first
n (int): badge size

Returns:
list[Future]: list of future objects one for each batch
"""
raise NotImplementedError("The batched method is not implemented.")

def map(
self,
fn: Callable,
*iterables,
timeout: Optional[float] = None,
chunksize: int = 1,
):
"""Returns an iterator equivalent to map(fn, iter).

Args:
fn: A callable that will take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
chunksize: The size of the chunks the iterable will be broken into
before being passed to a child process. This argument is only
used by ProcessPoolExecutor; it is ignored by
ThreadPoolExecutor.

Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.

Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values.
"""
raise NotImplementedError("The map method is not implemented.")

def submit( # type: ignore
self,
fn: Callable,
/,
*args,
resource_dict: Optional[dict] = None,
**kwargs,
) -> Future:
"""
Submits a callable to be executed with the given arguments.

Schedules the callable to be executed as fn(*args, **kwargs) and returns
a Future instance representing the execution of the callable.

Args:
fn (callable): function to submit for execution
args: arguments for the submitted function
kwargs: keyword arguments for the submitted function
resource_dict (dict): A dictionary of resources required by the task. With the following keys:
- cores (int): number of MPI cores to be used for each function call
- threads_per_core (int): number of OpenMP threads to be used for each function call
- gpus_per_core (int): number of GPUs per worker - defaults to 0
- cwd (str/None): current working directory where the parallel python task is executed
- openmpi_oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI and
SLURM only) - default False
- slurm_cmd_args (list): Additional command line arguments for the srun call (SLURM only)
- error_log_file (str): Name of the error log file to use for storing exceptions raised
by the Python functions submitted to the Executor.

Returns:
Future: A Future representing the given call.
"""
if resource_dict is None:
resource_dict = {}
f: Future = Future()
self._future_dict[f] = id(f)
self._tasks_dict[id(f)] = {
"fn": fn,
"args": args, # at the momemt the future objects are not removed from the args
"kwargs": kwargs, # at the momemt the future objects are not removed from the kwargs
"resource_dict": resource_dict,
"dependencies": [
self._future_dict[future_dependency]
for future_dependency in get_future_objects_from_input(
args=args, kwargs=kwargs
)
],
}
return f
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_parallel.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
import cloudpickle
import zmq

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -43,7 +44,11 @@ def main() -> None:
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -90,7 +95,13 @@ def main() -> None:
else:
# Send output
if mpi_rank_zero:
interface_send(socket=socket, result_dict={"result": output_reply})
interface_send(
socket=socket,
result_dict={
"result": output_reply,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_serial.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
from os.path import abspath
from typing import Optional

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -29,7 +30,11 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -65,7 +70,13 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
)
else:
# Send output
interface_send(socket=socket, result_dict={"result": output})
interface_send(
socket=socket,
result_dict={
"result": output,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 15 additions & 0 deletions src/executorlib/task_scheduler/base.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ def __init__(
self._process_kwargs: dict = {}
self._max_cores = max_cores
self._future_queue: Optional[queue.Queue] = queue.Queue()
self._return_queue: Optional[queue.Queue] = queue.Queue()
self._process: Optional[Union[Thread, list[Thread]]] = None
self._validator = validator

Expand DownExpand Up@@ -84,6 +85,8 @@ def info(self) -> Optional[dict]:
meta_data_dict = self._process_kwargs.copy()
if "future_queue" in meta_data_dict:
del meta_data_dict["future_queue"]
if "return_queue" in meta_data_dict:
del meta_data_dict["return_queue"]
if self._process is not None and isinstance(self._process, list):
meta_data_dict["max_workers"] = len(self._process)
return meta_data_dict
Expand All@@ -102,6 +105,16 @@ def future_queue(self) -> Optional[queue.Queue]:
"""
return self._future_queue

@property
def return_queue(self) -> Optional[queue.Queue]:
"""
Get the return queue.

Returns:
queue.Queue: The return queue.
"""
return self._return_queue

def batched(
self,
iterable: list[Future],
Expand DownExpand Up@@ -238,8 +251,10 @@ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False):
if isinstance(self._process, Thread):
self._process.join()
self._future_queue.join()
self._return_queue.join()
self._process = None
self._future_queue = None
self._return_queue = None

def _set_process(self, process: Thread):
"""
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -75,6 +75,7 @@ def __init__(
max_cores=executor_kwargs.get("max_cores"), validator=validator
)
executor_kwargs["future_queue"] = self._future_queue
executor_kwargs["return_queue"] = self._return_queue
executor_kwargs["spawner"] = spawner
executor_kwargs["queue_join_on_shutdown"] = False
executor_kwargs["restart_limit"] = restart_limit
Expand DownExpand Up@@ -217,6 +218,7 @@ def _set_process(self, process: list[Thread]): # type: ignore

def _execute_multiple_tasks(
future_queue: queue.Queue,
return_queue: queue.Queue,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
hostname_localhost: Optional[bool] = None,
Expand All@@ -240,6 +242,7 @@ def _execute_multiple_tasks(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
cores (int): defines the total number of MPI ranks to use
spawner (BaseSpawner): Spawner to start process on selected compute resources
hostname_localhost (boolean): use localhost instead of the hostname to establish the zmq connection. In the
Expand DownExpand Up@@ -317,7 +320,7 @@ def _execute_multiple_tasks(
f.set_exception(exception=interface_initialization_exception)
else:
# The interface failed during the execution
interface.status = execute_task_dict(
interface.status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=f,
interface=interface,
Expand All@@ -329,6 +332,8 @@ def _execute_multiple_tasks(
reset_task_dict(
future_obj=f, future_queue=future_queue, task_dict=task_dict
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
task_done(future_queue=future_queue)


Expand Down
14 changes: 14 additions & 0 deletions src/executorlib/task_scheduler/interactive/dependency.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -257,6 +257,10 @@ def _execute_tasks_with_dependencies(
task_dict = future_queue.get_nowait()
except queue.Empty:
task_dict = None
try:
task_return_dict = executor.return_queue.get_nowait()
except (queue.Empty, AttributeError):
task_return_dict = None
if ( # shutdown the executor
task_dict is not None and "shutdown" in task_dict and task_dict["shutdown"]
):
Expand DownExpand Up@@ -324,6 +328,16 @@ def _execute_tasks_with_dependencies(
executor_queue=executor_queue,
refresh_rate=refresh_rate,
)
elif task_return_dict is not None:
# we need this future dict later on to resolve the dependencies
future_lookup_dict = {}
for k, v in task_return_dict.items():
future_lookup_dict[k] = executor.submit(
fn=v["fn"],
*v["args"],
**v["kwargs"],
resource_dict=v["resource_dict"],
)
else:
# If there is nothing else to do, sleep for a moment
sleep(refresh_rate)
Expand Down
14 changes: 12 additions & 2 deletions src/executorlib/task_scheduler/interactive/onetoone.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -61,6 +61,7 @@ def __init__(
executor_kwargs.update(
{
"future_queue": self._future_queue,
"return_queue": self._return_queue,
"spawner": spawner,
"max_cores": max_cores,
"max_workers": max_workers,
Expand All@@ -77,6 +78,7 @@ def __init__(

def _execute_single_task(
future_queue: queue.Queue,
return_queue: queue.Queue,
spawner: type[BaseSpawner] = MpiExecSpawner,
max_cores: Optional[int] = None,
max_workers: Optional[int] = None,
Expand All@@ -88,6 +90,7 @@ def _execute_single_task(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
spawner (BaseSpawner): Interface to start process on selected compute resources
max_cores (int): defines the number cores which can be used in parallel
max_workers (int): for backwards compatibility with the standard library, max_workers also defines the number of
Expand DownExpand Up@@ -116,6 +119,7 @@ def _execute_single_task(
elif "fn" in task_dict and "future" in task_dict:
process, active_task_dict = _wrap_execute_task_in_separate_process(
task_dict=task_dict,
return_queue=return_queue,
active_task_dict=active_task_dict,
spawner=spawner,
executor_kwargs=kwargs,
Expand DownExpand Up@@ -162,6 +166,7 @@ def _wait_for_free_slots(

def _wrap_execute_task_in_separate_process(
task_dict: dict,
return_queue: queue.Queue,
active_task_dict: dict,
spawner: type[BaseSpawner],
executor_kwargs: dict,
Expand DownExpand Up@@ -211,6 +216,7 @@ def _wrap_execute_task_in_separate_process(
task_kwargs.update(
{
"task_dict": task_dict,
"return_queue": return_queue,
"spawner": spawner,
"hostname_localhost": hostname_localhost,
"future_obj": f,
Expand All@@ -226,6 +232,7 @@ def _wrap_execute_task_in_separate_process(

def _execute_task_in_thread(
task_dict: dict,
return_queue: queue.Queue,
future_obj: Future,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
Expand DownExpand Up@@ -262,7 +269,7 @@ def _execute_task_in_thread(
worker_id (int): Communicate the worker which ID was assigned to it for future reference and resource
distribution.
"""
if not execute_task_dict(
status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=future_obj,
interface=interface_bootup(
Expand All@@ -277,7 +284,10 @@ def _execute_task_in_thread(
cache_directory=cache_directory,
cache_key=cache_key,
error_log_file=error_log_file,
):
)
if status is False:
future_obj.set_exception(
ExecutorlibSocketError("SocketInterface crashed during execution.")
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/executorlib/backend/executor_nested.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
from concurrent.futures import Future
from typing import Callable, Optional

from executorlib.standalone.interactive.arguments import (
get_future_objects_from_input,
)


class BackendExecutor:
def __init__(self):
self._tasks_dict = {}
self._future_dict = {}

@property
def tasks(self):
return self._tasks_dict

def batched(
self,
iterable: list[Future],
n: int,
) -> list[Future]:
"""
Batch futures from the iterable into tuples of length n. The last batch may be shorter than n.

Args:
iterable (list): list of future objects to batch based on which future objects finish first
n (int): badge size

Returns:
list[Future]: list of future objects one for each batch
"""
raise NotImplementedError("The batched method is not implemented.")

def map(
self,
fn: Callable,
*iterables,
timeout: Optional[float] = None,
chunksize: int = 1,
):
"""Returns an iterator equivalent to map(fn, iter).

Args:
fn: A callable that will take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
chunksize: The size of the chunks the iterable will be broken into
before being passed to a child process. This argument is only
used by ProcessPoolExecutor; it is ignored by
ThreadPoolExecutor.

Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.

Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values.
"""
raise NotImplementedError("The map method is not implemented.")

def submit( # type: ignore
self,
fn: Callable,
/,
*args,
resource_dict: Optional[dict] = None,
**kwargs,
) -> Future:
"""
Submits a callable to be executed with the given arguments.

Schedules the callable to be executed as fn(*args, **kwargs) and returns
a Future instance representing the execution of the callable.

Args:
fn (callable): function to submit for execution
args: arguments for the submitted function
kwargs: keyword arguments for the submitted function
resource_dict (dict): A dictionary of resources required by the task. With the following keys:
- cores (int): number of MPI cores to be used for each function call
- threads_per_core (int): number of OpenMP threads to be used for each function call
- gpus_per_core (int): number of GPUs per worker - defaults to 0
- cwd (str/None): current working directory where the parallel python task is executed
- openmpi_oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI and
SLURM only) - default False
- slurm_cmd_args (list): Additional command line arguments for the srun call (SLURM only)
- error_log_file (str): Name of the error log file to use for storing exceptions raised
by the Python functions submitted to the Executor.

Returns:
Future: A Future representing the given call.
"""
if resource_dict is None:
resource_dict = {}
f: Future = Future()
self._future_dict[f] = id(f)
self._tasks_dict[id(f)] = {
"fn": fn,
"args": args, # at the momemt the future objects are not removed from the args
"kwargs": kwargs, # at the momemt the future objects are not removed from the kwargs
"resource_dict": resource_dict,
"dependencies": [
self._future_dict[future_dependency]
for future_dependency in get_future_objects_from_input(
args=args, kwargs=kwargs
)
],
}
return f
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_parallel.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
import cloudpickle
import zmq

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -43,7 +44,11 @@ def main() -> None:
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -90,7 +95,13 @@ def main() -> None:
else:
# Send output
if mpi_rank_zero:
interface_send(socket=socket, result_dict={"result": output_reply})
interface_send(
socket=socket,
result_dict={
"result": output_reply,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_serial.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
from os.path import abspath
from typing import Optional

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -29,7 +30,11 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -65,7 +70,13 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
)
else:
# Send output
interface_send(socket=socket, result_dict={"result": output})
interface_send(
socket=socket,
result_dict={
"result": output,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 15 additions & 0 deletions src/executorlib/task_scheduler/base.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ def __init__(
self._process_kwargs: dict = {}
self._max_cores = max_cores
self._future_queue: Optional[queue.Queue] = queue.Queue()
self._return_queue: Optional[queue.Queue] = queue.Queue()
self._process: Optional[Union[Thread, list[Thread]]] = None
self._validator = validator

Expand DownExpand Up@@ -84,6 +85,8 @@ def info(self) -> Optional[dict]:
meta_data_dict = self._process_kwargs.copy()
if "future_queue" in meta_data_dict:
del meta_data_dict["future_queue"]
if "return_queue" in meta_data_dict:
del meta_data_dict["return_queue"]
if self._process is not None and isinstance(self._process, list):
meta_data_dict["max_workers"] = len(self._process)
return meta_data_dict
Expand All@@ -102,6 +105,16 @@ def future_queue(self) -> Optional[queue.Queue]:
"""
return self._future_queue

@property
def return_queue(self) -> Optional[queue.Queue]:
"""
Get the return queue.

Returns:
queue.Queue: The return queue.
"""
return self._return_queue

def batched(
self,
iterable: list[Future],
Expand DownExpand Up@@ -238,8 +251,10 @@ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False):
if isinstance(self._process, Thread):
self._process.join()
self._future_queue.join()
self._return_queue.join()
self._process = None
self._future_queue = None
self._return_queue = None

def _set_process(self, process: Thread):
"""
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -75,6 +75,7 @@ def __init__(
max_cores=executor_kwargs.get("max_cores"), validator=validator
)
executor_kwargs["future_queue"] = self._future_queue
executor_kwargs["return_queue"] = self._return_queue
executor_kwargs["spawner"] = spawner
executor_kwargs["queue_join_on_shutdown"] = False
executor_kwargs["restart_limit"] = restart_limit
Expand DownExpand Up@@ -217,6 +218,7 @@ def _set_process(self, process: list[Thread]): # type: ignore

def _execute_multiple_tasks(
future_queue: queue.Queue,
return_queue: queue.Queue,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
hostname_localhost: Optional[bool] = None,
Expand All@@ -240,6 +242,7 @@ def _execute_multiple_tasks(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
cores (int): defines the total number of MPI ranks to use
spawner (BaseSpawner): Spawner to start process on selected compute resources
hostname_localhost (boolean): use localhost instead of the hostname to establish the zmq connection. In the
Expand DownExpand Up@@ -317,7 +320,7 @@ def _execute_multiple_tasks(
f.set_exception(exception=interface_initialization_exception)
else:
# The interface failed during the execution
interface.status = execute_task_dict(
interface.status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=f,
interface=interface,
Expand All@@ -329,6 +332,8 @@ def _execute_multiple_tasks(
reset_task_dict(
future_obj=f, future_queue=future_queue, task_dict=task_dict
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
task_done(future_queue=future_queue)


Expand Down
14 changes: 14 additions & 0 deletions src/executorlib/task_scheduler/interactive/dependency.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -257,6 +257,10 @@ def _execute_tasks_with_dependencies(
task_dict = future_queue.get_nowait()
except queue.Empty:
task_dict = None
try:
task_return_dict = executor.return_queue.get_nowait()
except (queue.Empty, AttributeError):
task_return_dict = None
if ( # shutdown the executor
task_dict is not None and "shutdown" in task_dict and task_dict["shutdown"]
):
Expand DownExpand Up@@ -324,6 +328,16 @@ def _execute_tasks_with_dependencies(
executor_queue=executor_queue,
refresh_rate=refresh_rate,
)
elif task_return_dict is not None:
# we need this future dict later on to resolve the dependencies
future_lookup_dict = {}
for k, v in task_return_dict.items():
future_lookup_dict[k] = executor.submit(
fn=v["fn"],
*v["args"],
**v["kwargs"],
resource_dict=v["resource_dict"],
)
else:
# If there is nothing else to do, sleep for a moment
sleep(refresh_rate)
Expand Down
14 changes: 12 additions & 2 deletions src/executorlib/task_scheduler/interactive/onetoone.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -61,6 +61,7 @@ def __init__(
executor_kwargs.update(
{
"future_queue": self._future_queue,
"return_queue": self._return_queue,
"spawner": spawner,
"max_cores": max_cores,
"max_workers": max_workers,
Expand All@@ -77,6 +78,7 @@ def __init__(

def _execute_single_task(
future_queue: queue.Queue,
return_queue: queue.Queue,
spawner: type[BaseSpawner] = MpiExecSpawner,
max_cores: Optional[int] = None,
max_workers: Optional[int] = None,
Expand All@@ -88,6 +90,7 @@ def _execute_single_task(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
spawner (BaseSpawner): Interface to start process on selected compute resources
max_cores (int): defines the number cores which can be used in parallel
max_workers (int): for backwards compatibility with the standard library, max_workers also defines the number of
Expand DownExpand Up@@ -116,6 +119,7 @@ def _execute_single_task(
elif "fn" in task_dict and "future" in task_dict:
process, active_task_dict = _wrap_execute_task_in_separate_process(
task_dict=task_dict,
return_queue=return_queue,
active_task_dict=active_task_dict,
spawner=spawner,
executor_kwargs=kwargs,
Expand DownExpand Up@@ -162,6 +166,7 @@ def _wait_for_free_slots(

def _wrap_execute_task_in_separate_process(
task_dict: dict,
return_queue: queue.Queue,
active_task_dict: dict,
spawner: type[BaseSpawner],
executor_kwargs: dict,
Expand DownExpand Up@@ -211,6 +216,7 @@ def _wrap_execute_task_in_separate_process(
task_kwargs.update(
{
"task_dict": task_dict,
"return_queue": return_queue,
"spawner": spawner,
"hostname_localhost": hostname_localhost,
"future_obj": f,
Expand All@@ -226,6 +232,7 @@ def _wrap_execute_task_in_separate_process(

def _execute_task_in_thread(
task_dict: dict,
return_queue: queue.Queue,
future_obj: Future,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
Expand DownExpand Up@@ -262,7 +269,7 @@ def _execute_task_in_thread(
worker_id (int): Communicate the worker which ID was assigned to it for future reference and resource
distribution.
"""
if not execute_task_dict(
status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=future_obj,
interface=interface_bootup(
Expand All@@ -277,7 +284,10 @@ def _execute_task_in_thread(
cache_directory=cache_directory,
cache_key=cache_key,
error_log_file=error_log_file,
):
)
if status is False:
future_obj.set_exception(
ExecutorlibSocketError("SocketInterface crashed during execution.")
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/executorlib/backend/executor_nested.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
from concurrent.futures import Future
from typing import Callable, Optional

from executorlib.standalone.interactive.arguments import (
get_future_objects_from_input,
)


class BackendExecutor:
def __init__(self):
self._tasks_dict = {}
self._future_dict = {}

@property
def tasks(self):
return self._tasks_dict

def batched(
self,
iterable: list[Future],
n: int,
) -> list[Future]:
"""
Batch futures from the iterable into tuples of length n. The last batch may be shorter than n.

Args:
iterable (list): list of future objects to batch based on which future objects finish first
n (int): badge size

Returns:
list[Future]: list of future objects one for each batch
"""
raise NotImplementedError("The batched method is not implemented.")

def map(
self,
fn: Callable,
*iterables,
timeout: Optional[float] = None,
chunksize: int = 1,
):
"""Returns an iterator equivalent to map(fn, iter).

Args:
fn: A callable that will take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
chunksize: The size of the chunks the iterable will be broken into
before being passed to a child process. This argument is only
used by ProcessPoolExecutor; it is ignored by
ThreadPoolExecutor.

Returns:
An iterator equivalent to: map(func, *iterables) but the calls may
be evaluated out-of-order.

Raises:
TimeoutError: If the entire result iterator could not be generated
before the given timeout.
Exception: If fn(*args) raises for any values.
"""
raise NotImplementedError("The map method is not implemented.")

def submit( # type: ignore
self,
fn: Callable,
/,
*args,
resource_dict: Optional[dict] = None,
**kwargs,
) -> Future:
"""
Submits a callable to be executed with the given arguments.

Schedules the callable to be executed as fn(*args, **kwargs) and returns
a Future instance representing the execution of the callable.

Args:
fn (callable): function to submit for execution
args: arguments for the submitted function
kwargs: keyword arguments for the submitted function
resource_dict (dict): A dictionary of resources required by the task. With the following keys:
- cores (int): number of MPI cores to be used for each function call
- threads_per_core (int): number of OpenMP threads to be used for each function call
- gpus_per_core (int): number of GPUs per worker - defaults to 0
- cwd (str/None): current working directory where the parallel python task is executed
- openmpi_oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI and
SLURM only) - default False
- slurm_cmd_args (list): Additional command line arguments for the srun call (SLURM only)
- error_log_file (str): Name of the error log file to use for storing exceptions raised
by the Python functions submitted to the Executor.

Returns:
Future: A Future representing the given call.
"""
if resource_dict is None:
resource_dict = {}
f: Future = Future()
self._future_dict[f] = id(f)
self._tasks_dict[id(f)] = {
"fn": fn,
"args": args, # at the momemt the future objects are not removed from the args
"kwargs": kwargs, # at the momemt the future objects are not removed from the kwargs
"resource_dict": resource_dict,
"dependencies": [
self._future_dict[future_dependency]
for future_dependency in get_future_objects_from_input(
args=args, kwargs=kwargs
)
],
}
return f
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_parallel.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,7 @@
import cloudpickle
import zmq

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -43,7 +44,11 @@ def main() -> None:
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -90,7 +95,13 @@ def main() -> None:
else:
# Send output
if mpi_rank_zero:
interface_send(socket=socket, result_dict={"result": output_reply})
interface_send(
socket=socket,
result_dict={
"result": output_reply,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 13 additions & 2 deletions src/executorlib/backend/interactive_serial.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@
from os.path import abspath
from typing import Optional

from executorlib.backend.executor_nested import BackendExecutor
from executorlib.standalone.error import backend_write_error_file
from executorlib.standalone.interactive.backend import call_funct, parse_arguments
from executorlib.standalone.interactive.communication import (
Expand DownExpand Up@@ -29,7 +30,11 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
host=argument_dict["host"], port=argument_dict["zmqport"]
)

memory = {"executorlib_worker_id": int(argument_dict["worker_id"])}
nested_executor = BackendExecutor()
memory = {
"executorlib_worker_id": int(argument_dict["worker_id"]),
"executorlib_executor": nested_executor,
}

# required for flux interface - otherwise the current path is not included in the python path
cwd = abspath(".")
Expand DownExpand Up@@ -65,7 +70,13 @@ def evaluate_cmd(argument_lst: Optional[list[str]] = None):
)
else:
# Send output
interface_send(socket=socket, result_dict={"result": output})
interface_send(
socket=socket,
result_dict={
"result": output,
"tasks_nested": nested_executor.tasks,
},
)
elif (
"init" in input_dict
and input_dict["init"]
Expand Down
15 changes: 15 additions & 0 deletions src/executorlib/task_scheduler/base.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -50,6 +50,7 @@ def __init__(
self._process_kwargs: dict = {}
self._max_cores = max_cores
self._future_queue: Optional[queue.Queue] = queue.Queue()
self._return_queue: Optional[queue.Queue] = queue.Queue()
self._process: Optional[Union[Thread, list[Thread]]] = None
self._validator = validator

Expand DownExpand Up@@ -84,6 +85,8 @@ def info(self) -> Optional[dict]:
meta_data_dict = self._process_kwargs.copy()
if "future_queue" in meta_data_dict:
del meta_data_dict["future_queue"]
if "return_queue" in meta_data_dict:
del meta_data_dict["return_queue"]
if self._process is not None and isinstance(self._process, list):
meta_data_dict["max_workers"] = len(self._process)
return meta_data_dict
Expand All@@ -102,6 +105,16 @@ def future_queue(self) -> Optional[queue.Queue]:
"""
return self._future_queue

@property
def return_queue(self) -> Optional[queue.Queue]:
"""
Get the return queue.

Returns:
queue.Queue: The return queue.
"""
return self._return_queue

def batched(
self,
iterable: list[Future],
Expand DownExpand Up@@ -238,8 +251,10 @@ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False):
if isinstance(self._process, Thread):
self._process.join()
self._future_queue.join()
self._return_queue.join()
self._process = None
self._future_queue = None
self._return_queue = None

def _set_process(self, process: Thread):
"""
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -75,6 +75,7 @@ def __init__(
max_cores=executor_kwargs.get("max_cores"), validator=validator
)
executor_kwargs["future_queue"] = self._future_queue
executor_kwargs["return_queue"] = self._return_queue
executor_kwargs["spawner"] = spawner
executor_kwargs["queue_join_on_shutdown"] = False
executor_kwargs["restart_limit"] = restart_limit
Expand DownExpand Up@@ -217,6 +218,7 @@ def _set_process(self, process: list[Thread]): # type: ignore

def _execute_multiple_tasks(
future_queue: queue.Queue,
return_queue: queue.Queue,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
hostname_localhost: Optional[bool] = None,
Expand All@@ -240,6 +242,7 @@ def _execute_multiple_tasks(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
cores (int): defines the total number of MPI ranks to use
spawner (BaseSpawner): Spawner to start process on selected compute resources
hostname_localhost (boolean): use localhost instead of the hostname to establish the zmq connection. In the
Expand DownExpand Up@@ -317,7 +320,7 @@ def _execute_multiple_tasks(
f.set_exception(exception=interface_initialization_exception)
else:
# The interface failed during the execution
interface.status = execute_task_dict(
interface.status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=f,
interface=interface,
Expand All@@ -329,6 +332,8 @@ def _execute_multiple_tasks(
reset_task_dict(
future_obj=f, future_queue=future_queue, task_dict=task_dict
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
task_done(future_queue=future_queue)


Expand Down
14 changes: 14 additions & 0 deletions src/executorlib/task_scheduler/interactive/dependency.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -257,6 +257,10 @@ def _execute_tasks_with_dependencies(
task_dict = future_queue.get_nowait()
except queue.Empty:
task_dict = None
try:
task_return_dict = executor.return_queue.get_nowait()
except (queue.Empty, AttributeError):
task_return_dict = None
if ( # shutdown the executor
task_dict is not None and "shutdown" in task_dict and task_dict["shutdown"]
):
Expand DownExpand Up@@ -324,6 +328,16 @@ def _execute_tasks_with_dependencies(
executor_queue=executor_queue,
refresh_rate=refresh_rate,
)
elif task_return_dict is not None:
# we need this future dict later on to resolve the dependencies
future_lookup_dict = {}
for k, v in task_return_dict.items():
future_lookup_dict[k] = executor.submit(
fn=v["fn"],
*v["args"],
**v["kwargs"],
resource_dict=v["resource_dict"],
)
else:
# If there is nothing else to do, sleep for a moment
sleep(refresh_rate)
Expand Down
14 changes: 12 additions & 2 deletions src/executorlib/task_scheduler/interactive/onetoone.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -61,6 +61,7 @@ def __init__(
executor_kwargs.update(
{
"future_queue": self._future_queue,
"return_queue": self._return_queue,
"spawner": spawner,
"max_cores": max_cores,
"max_workers": max_workers,
Expand All@@ -77,6 +78,7 @@ def __init__(

def _execute_single_task(
future_queue: queue.Queue,
return_queue: queue.Queue,
spawner: type[BaseSpawner] = MpiExecSpawner,
max_cores: Optional[int] = None,
max_workers: Optional[int] = None,
Expand All@@ -88,6 +90,7 @@ def _execute_single_task(

Args:
future_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
return_queue (queue.Queue): task queue of dictionary objects which are submitted to the parallel process
spawner (BaseSpawner): Interface to start process on selected compute resources
max_cores (int): defines the number cores which can be used in parallel
max_workers (int): for backwards compatibility with the standard library, max_workers also defines the number of
Expand DownExpand Up@@ -116,6 +119,7 @@ def _execute_single_task(
elif "fn" in task_dict and "future" in task_dict:
process, active_task_dict = _wrap_execute_task_in_separate_process(
task_dict=task_dict,
return_queue=return_queue,
active_task_dict=active_task_dict,
spawner=spawner,
executor_kwargs=kwargs,
Expand DownExpand Up@@ -162,6 +166,7 @@ def _wait_for_free_slots(

def _wrap_execute_task_in_separate_process(
task_dict: dict,
return_queue: queue.Queue,
active_task_dict: dict,
spawner: type[BaseSpawner],
executor_kwargs: dict,
Expand DownExpand Up@@ -211,6 +216,7 @@ def _wrap_execute_task_in_separate_process(
task_kwargs.update(
{
"task_dict": task_dict,
"return_queue": return_queue,
"spawner": spawner,
"hostname_localhost": hostname_localhost,
"future_obj": f,
Expand All@@ -226,6 +232,7 @@ def _wrap_execute_task_in_separate_process(

def _execute_task_in_thread(
task_dict: dict,
return_queue: queue.Queue,
future_obj: Future,
cores: int = 1,
spawner: type[BaseSpawner] = MpiExecSpawner,
Expand DownExpand Up@@ -262,7 +269,7 @@ def _execute_task_in_thread(
worker_id (int): Communicate the worker which ID was assigned to it for future reference and resource
distribution.
"""
if not execute_task_dict(
status, nested_task_dict = execute_task_dict(
task_dict=task_dict,
future_obj=future_obj,
interface=interface_bootup(
Expand All@@ -277,7 +284,10 @@ def _execute_task_in_thread(
cache_directory=cache_directory,
cache_key=cache_key,
error_log_file=error_log_file,
):
)
if status is False:
future_obj.set_exception(
ExecutorlibSocketError("SocketInterface crashed during execution.")
)
elif len(nested_task_dict) > 0:
return_queue.put(nested_task_dict)
Loading
Loading