199 """Expose Ray tasks through the executor interface.
201 Install the ``ray`` extra. Pass a cluster address or set ``RAY_ADDRESS``
202 to attach to a running cluster. Otherwise start local Ray. An active
203 Ray connection in the calling process is reused unless an explicit
204 address was passed. The executor closes connections it opens.
206 :param address: Optional Ray cluster address. Use "local" to start
207 local Ray even when ``RAY_ADDRESS`` is set.
208 :param max_workers: CPU count for local Ray. An attached cluster
209 controls its own resources.
211 def __init__(self, *, address: Optional[str] =
None,
212 max_workers: Optional[int] =
None) ->
None:
214 if ray.is_initialized():
215 if address
is not None:
216 raise ValueError(
"Ray is already initialized. Omit the address to reuse its connection.")
218 endpoint = address
if address
is not None else (os.environ.get(
"RAY_ADDRESS")
or "local")
219 if endpoint ==
"local" and max_workers
is not None:
220 ray.init(address=endpoint, num_cpus=max_workers)
222 ray.init(address=endpoint)
224 def submit(self, fn: Callable, *args: Any, **kwargs: Any) -> FutureLike:
225 return RayFuture(_ray_deploy_func.remote(fn, kwargs, *args))
226 def map(self, fn: Callable, *iterables: Any) -> Iterable:
228 fs = [self.
submit(fn, *args)
for args
in zip(*iterables)]
231 def result_iterator():
237 yield fs.pop().result()
241 return result_iterator()
243 """Close the Ray connection if this executor opened it."""
254 def _ray_as_completed_fn(fs, timeout=None):
255 oid_dict = {x.oid: x
for x
in fs}
256 pending = list(oid_dict)
257 deadline =
None if timeout
is None else monotonic() + timeout
259 remaining_time =
None if deadline
is None else max(0, deadline - monotonic())
260 ready, pending = ray.wait(pending, num_returns=1, timeout=remaining_time)
262 raise TimeoutError(
"Ray tasks did not finish within the requested timeout.")
263 yield oid_dict[ready[0]]
264 _ray_as_completed: Optional[Callable] = _ray_as_completed_fn
265 _ray_future_class: Optional[Any] = RayFuture
270 """Executor that encapsulate ray concurrency functions. Need the ray package to be installed and importable."""
271 def __init__(self, *, address: Optional[str] =
None,
272 max_workers: Optional[int] =
None) ->
None:
273 raise NotImplementedError(
"`RayExecutor` needs the ray package to be installed and importable.")
274 def submit(self, fn: Callable, *args: Any, **kwargs: Any) -> FutureLike:
275 raise NotImplementedError(
"`RayExecutor` needs the ray package to be installed and importable.")
276 def map(self, fn: Callable, *iterables: Any) -> Iterable:
277 raise NotImplementedError(
"`RayExecutor` needs the ray package to be installed and importable.")
278 def shutdown(self, wait: bool =
True) ->
None:
279 raise NotImplementedError(
"`RayExecutor` needs the ray package to be installed and importable.")
280 _ray_as_completed: Optional[Callable] =
None
281 _ray_future_class: Optional[Any] =
None
285def generic_as_completed(fs: Sequence[FutureLike], timeout: Optional[int]=
None) -> FutureLike:
286 """Return the next completed future from a homogeneous nonempty sequence.
288 Sequential futures have already completed. Concurrent futures, SCOOP,
289 and Ray use their respective completion mechanisms.
291 :param fs: Pending futures from one backend.
292 :param timeout: Optional wait limit in seconds, passed to that backend.
293 :raises ValueError: If the input is empty or the backend is unknown.
296 raise ValueError(f
"`fs` must not be empty.")
298 if isinstance(fs[0], SequentialFuture):
300 if _scoop_future_class
is not None and isinstance(fs[0], _scoop_future_class)
and _scoop_as_completed
is not None:
301 return next(_scoop_as_completed(fs, timeout))
302 if _ray_future_class
is not None and isinstance(fs[0], _ray_future_class)
and _ray_as_completed
is not None:
303 return next(_ray_as_completed(fs, timeout))
305 futures_module = fs[0].__module__
307 m = importlib.import_module(futures_module)
308 if hasattr(m,
"as_completed"):
309 return next(m.as_completed(fs, timeout))
311 raise ValueError(f
"Futures from `fs` are of unknown type, with unknown `as_completed` corresponding function.")
318_parent_id = os.getpid()
321 def sig_int(signal_num, frame):
323 parent = psutil.Process(_parent_id)
324 for child
in parent.children():
325 if child.pid != os.getpid():
326 print(
"killing child: %s" % child.pid)
331 psutil.Process(os.getpid()).kill()
332 signal.signal(signal.SIGINT, sig_int)
337 """Open and close an evaluation executor as a context manager.
339 Use ``none`` or ``sequential`` for in-process evaluation,
340 ``multithreading`` for a thread pool, and ``multiprocessing`` or
341 ``concurrent`` for a process pool. The process pool prefers forkserver
342 when available and otherwise uses spawn. SCOOP and Ray require
343 their optional runtime packages.
345 :param parallelism_type: Executor backend name.
346 :param max_workers: Optional worker count for the standard pools or CPU
347 count for a local Ray runtime.
348 :param toolbox: Optional DEAP toolbox copied and bound to executor.map.
349 :param force_worker_suicide: Install the process worker's interrupt handler.
350 :param ray_address: Optional cluster address for the Ray backend.
352 Process evaluation needs picklable evaluation functions and candidates.
353 Protect executable entry points with the usual main guard.
356 executor: ExecutorLike
357 toolbox: Optional[Any]
358 orig_toolbox: Optional[Any]
359 max_workers: Optional[int]
360 _parallelism_type: str =
""
361 _parallelism_type_list: Sequence[str] = [
'none',
'sequential',
'multiprocessing',
'concurrent',
'multithreading',
'scoop',
'ray']
362 force_worker_suicide: bool
364 def __init__(self, parallelism_type: str =
"multiprocessing", max_workers: Optional[int] =
None,
365 toolbox: Optional[Any] =
None, force_worker_suicide: bool =
True, *,
366 ray_address: Optional[str] =
None) ->
None:
369 raise ValueError(
"ray_address requires the Ray backend.")
373 self.
toolbox = copy.deepcopy(toolbox)
if toolbox
is not None else None
378 def parallelism_type(self) -> str:
381 @parallelism_type.setter
382 def parallelism_type(self, val: str) ->
None:
384 raise NotImplementedError(
"`parallelism_type` cannot be set after initialisation.")
387 raise ValueError(f
"`parallelism_type` can only be from [{','.join(self._parallelism_type_list)}].")
390 def __enter__(self) -> Any:
394 def __exit__(self, exc_type, exc_value, traceback):
398 """Open and prepare a new executor according to `self.parallelism_type`."""
400 init_fn: Optional[Callable] = _worker_init
406 import concurrent.futures
407 import multiprocessing
408 methods = multiprocessing.get_all_start_methods()
409 ctx = multiprocessing.get_context(
"forkserver" if "forkserver" in methods
else "spawn")
411 self.
executor = concurrent.futures.ProcessPoolExecutor(
412 max_workers=self.
max_workers, mp_context=ctx, initializer=init_fn
415 import concurrent.futures
430 """Close the current executor."""
437 """Describes a class that can be summarised by using the `self.summary` method.
438 The summarised information is provided by the `self.__get_summary_state__` method. """
442 """Return a dictionary containing the relevant entries to build a summary of the class.
443 By default, it includes all public attributes of the class. Must be overridden by subclasses."""
446 for k, v
in inspect.getmembers(self):
447 if not k.startswith(
'_')
and not inspect.ismethod(v):
455 def summary(self, max_depth: Optional[int] =
None, max_entry_length: Optional[int] = 250) -> str:
456 """Return a summary description of the class.
457 The summarised information is provided by the `self.__get_summary_state__` method.
461 :param max_depth: Optional[int]
462 The maximal recursion depth allowed. Used to summarise attributes of `self` that are also Summarisable.
463 If the maximal recursion depth is reached, the attribute is only described with a reduced representation (`repr(attribute)`).
464 If `max_depth` is set to None, there are no recursion limit.
465 :param max_entry_length: Optional[int]
466 If `max_entry_length` is not None, the description of a non-Summarisable entry exceeding `max_entry_length`
467 is cropped to this limit.
469 res: str = f
"Summary {self.__class__.__name__}:\n"
470 subs_max_depth = max_depth - 1
if max_depth
is not None else None
472 for i, k
in enumerate(summary_state.keys()):
475 if isinstance(v, Summarisable):
476 if max_depth
is None or max_depth > 0:
477 res += textwrap.indent(v.summary(subs_max_depth),
' ')
482 str_v = str_v.replace(
"\n",
" ")
483 if max_entry_length
is not None and len(str_v) > max_entry_length:
484 str_v = str_v[:max_entry_length - 4] +
" ..."
486 if i != len(summary_state) - 1:
490 def __repr__(self) -> str:
491 return f
"{self.__class__.__name__}"
501def _atomic_output_path(output_path):
502 destination = Path(output_path)
503 with tempfile.NamedTemporaryFile(dir=destination.parent, delete=
False)
as file:
504 temporary = Path(file.name)
507 os.replace(temporary, destination)
509 temporary.unlink(missing_ok=
True)
513 """Write a result dictionary supplied by the object.
515 Subclasses choose what the snapshot holds through the saved-state
516 hook. Result files can contain Python objects and should only be
517 loaded from trusted sources.
521 """Return a dictionary containing the relevant information to save.
522 By default, it includes all public attributes of the class. Must be overridden by subclasses."""
524 entries = {k:v
for k,v
in inspect.getmembers(self)
if not k.startswith(
'_')
and not inspect.ismethod(v)}
527 def save(self, output_path: str, output_type: str =
"pickle") ->
None:
528 """Serialize a result dictionary and replace the destination atomically.
530 Write the new pickle to a temporary file in the destination directory.
531 Preserve the previous result if serialisation or replacement fails.
533 :param output_path: Destination file in an existing directory.
534 :param output_type: Output format. The supported value is ``pickle``.
535 :raises ValueError: If another output type is requested.
537 if output_type !=
"pickle":
538 raise ValueError(f
"Invalid `output_type` value. Currently, only supports 'pickle'.")
540 with _atomic_output_path(output_path)
as temporary:
541 with temporary.open(
"wb")
as file:
542 pickle.dump(saved_state, file)
546 """Describes a class capable to be copied and deepcopied."""
550 result = cls.__new__(cls)
551 result.__dict__.update(self.
__dict__)
554 def __deepcopy__(self, memo):
556 result = cls.__new__(cls)
557 memo[id(self)] = result
559 setattr(result, k, copy.deepcopy(v, memo))
565 """Describe a class capable to be created from a configuration dictionary."""
568 def from_config(cls, config: Mapping[str, Any], **kwargs: Any) -> Any:
569 """Create a class using the information from `config` to call the class constructor.
573 :param config: Mapping[str, Any]
574 The configuration mapping used to create the class. For each entry, the key corresponds
575 to the name of a parameter of the constructor of the class.
577 Additional information used to create the class. The configuration entries from kwargs
578 take precedence over the entry in `config`.
580 final_kwargs = {**config, **kwargs}
581 final_kwargs.pop(
"type",
None)
582 return cls(**final_kwargs)
587 """Map configured type names to registered Python classes."""
589 def __init__(self) -> None:
593 def register(self, obj: Any, info: Optional[Mapping[Any, Any]] =
None) -> Any:
594 """Decorator method for registering functions/classes
595 The `info` variable can be filled up using the register_with_info
596 decorator instead of this one.
601 warnings.warn(f
'Encountered a name collision "{name}".')
608 def get_info(self, name: str) -> Mapping[str, Any]:
610 raise ValueError(f
'`{name}` is not registered.')
617 """Resolve registered types and named objects in a configuration.
619 A mapping with a type entry describes an object. A string matching a
620 previously built object's name refers to that object. Lists and
621 count mappings can request copies of registered configurations,
622 with reinitialisation where supported. Plain settings mappings
623 pass through to the constructor.
625 Build dependencies before the objects that refer to them. Use the
626 same Factory for the containers and algorithms of one experiment.
629 def __init__(self, registry: Registry=registry) ->
None:
634 def _get_name(self, obj: Any, key: Optional[str], config: Mapping[str, Any]) -> Optional[str]:
635 """Check if `obj` possess a name, and return it."""
637 if hasattr(obj,
"name"):
639 elif key
is not None:
641 elif "name" in config:
642 return config[
"name"]
647 def _build_internal(self, config: MutableMapping[str, Any], default_params: Mapping[str, Any] = {}, **kwargs: Any) -> Any:
650 default_config = {**default_params}
651 for k, v
in config.items():
652 is_object = isinstance(v, Mapping)
and "type" in v
656 if sub_name
is not None and len(sub_name) > 0
and not sub_name
in self:
657 self[sub_name] = sub_obj
658 built_objs.append(sub_obj)
660 elif isinstance(v, str)
and v
in self:
662 elif isinstance(v, Mapping)
and v
and all(key
in self
and isinstance(n, int)
for key, n
in v.items()):
664 for name, count
in v.items():
666 for _
in range(count):
667 if hasattr(obj,
"reinit"):
668 clone = copy.deepcopy(obj)
670 objects.append(clone)
674 elif isinstance(v, list):
675 for i, val
in enumerate(v):
676 if isinstance(val, str)
and val
in self:
677 if hasattr(self[val],
"reinit"):
678 new_val = copy.deepcopy(self[val])
682 config[k][i] = new_val
684 default_config[k] = config[k]
690 type_name: str = config[
"type"]
691 assert type_name
in self.
registry, f
"The class `{type_name}` is not declared in the registry. To get the list of registered classes, use: 'print(registry.keys())'."
693 assert issubclass(cls, CreatableFromConfig), f
"The class `{cls}` must inherit from `CreatableFromConfig` to be built."
695 obj: Any = cls.from_config(config, **default_params, **kwargs)
697 name: Optional[str] = self.
_get_name(obj,
None, config)
698 if name
is not None and len(name) > 0
and not name
in self:
707 def build(self, config: Mapping[str, Any], default_params: Mapping[str, Any] = {}, **kwargs: Any) -> Any:
708 """Build a registered object or the named objects in a configuration section.
710 :param config: Mapping containing a type or nested object definitions.
711 :param default_params: Defaults inherited by object definitions.
712 :param kwargs: Additional arguments forwarded to the top-level factory hook.
713 :returns: The constructed object or a list of objects from a section.
715 The builder transforms a deep copy of the supplied mapping. A known
716 top-level name can return a previously built object.
718 if "name" in config
and config[
"name"]
in self:
719 return self[config[
"name"]]
720 final_config: MutableMapping[str, Any] = dict(copy.deepcopy(config))