diff --git a/venv/lib/python3.10/site-packages/fastapi_cli/__init__.py b/venv/lib/python3.10/site-packages/fastapi_cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a73339bf81370efc24e667e80c0cd6d8b8b80687 --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastapi_cli/__init__.py @@ -0,0 +1 @@ +__version__ = "0.0.8" diff --git a/venv/lib/python3.10/site-packages/fastapi_cli/__main__.py b/venv/lib/python3.10/site-packages/fastapi_cli/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e28416e104515e90fca4b69cc60d0c61fd15d61 --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastapi_cli/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +main() diff --git a/venv/lib/python3.10/site-packages/fastapi_cli/cli.py b/venv/lib/python3.10/site-packages/fastapi_cli/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..77647217ec9928b98e595181bb023a80a58fa695 --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastapi_cli/cli.py @@ -0,0 +1,358 @@ +import logging +from pathlib import Path +from typing import Any, List, Union + +import typer +from rich import print +from rich.tree import Tree +from typing_extensions import Annotated + +from fastapi_cli.discover import get_import_data +from fastapi_cli.exceptions import FastAPICLIException + +from . import __version__ +from .logging import setup_logging +from .utils.cli import get_rich_toolkit, get_uvicorn_log_config + +app = typer.Typer(rich_markup_mode="rich") + +logger = logging.getLogger(__name__) + + +try: + import uvicorn +except ImportError: # pragma: no cover + uvicorn = None # type: ignore[assignment] + + +try: + from fastapi_cloud_cli.cli import ( + app as fastapi_cloud_cli, + ) + + app.add_typer(fastapi_cloud_cli) +except ImportError: # pragma: no cover + pass + + +def version_callback(value: bool) -> None: + if value: + print(f"FastAPI CLI version: [green]{__version__}[/green]") + raise typer.Exit() + + +@app.callback() +def callback( + version: Annotated[ + Union[bool, None], + typer.Option( + "--version", help="Show the version and exit.", callback=version_callback + ), + ] = None, + verbose: bool = typer.Option(False, help="Enable verbose output"), +) -> None: + """ + FastAPI CLI - The [bold]fastapi[/bold] command line app. 😎 + + Manage your [bold]FastAPI[/bold] projects, run your FastAPI apps, and more. + + Read more in the docs: [link=https://fastapi.tiangolo.com/fastapi-cli/]https://fastapi.tiangolo.com/fastapi-cli/[/link]. + """ + + log_level = logging.DEBUG if verbose else logging.INFO + + setup_logging(level=log_level) + + +def _get_module_tree(module_paths: List[Path]) -> Tree: + root = module_paths[0] + name = f"🐍 {root.name}" if root.is_file() else f"📁 {root.name}" + + root_tree = Tree(name) + + if root.is_dir(): + root_tree.add("[dim]🐍 __init__.py[/dim]") + + tree = root_tree + for sub_path in module_paths[1:]: + sub_name = ( + f"🐍 {sub_path.name}" if sub_path.is_file() else f"📁 {sub_path.name}" + ) + tree = tree.add(sub_name) + if sub_path.is_dir(): + tree.add("[dim]🐍 __init__.py[/dim]") + + return root_tree + + +def _run( + path: Union[Path, None] = None, + *, + host: str = "127.0.0.1", + port: int = 8000, + reload: bool = True, + workers: Union[int, None] = None, + root_path: str = "", + command: str, + app: Union[str, None] = None, + proxy_headers: bool = False, +) -> None: + with get_rich_toolkit() as toolkit: + server_type = "development" if command == "dev" else "production" + + toolkit.print_title(f"Starting {server_type} server 🚀", tag="FastAPI") + toolkit.print_line() + + toolkit.print( + "Searching for package file structure from directories with [blue]__init__.py[/blue] files" + ) + + try: + import_data = get_import_data(path=path, app_name=app) + except FastAPICLIException as e: + toolkit.print_line() + toolkit.print(f"[error]{e}") + raise typer.Exit(code=1) from None + + logger.debug(f"Importing from {import_data.module_data.extra_sys_path}") + logger.debug(f"Importing module {import_data.module_data.module_import_str}") + + module_data = import_data.module_data + import_string = import_data.import_string + + toolkit.print(f"Importing from {module_data.extra_sys_path}") + toolkit.print_line() + + root_tree = _get_module_tree(module_data.module_paths) + + toolkit.print(root_tree, tag="module") + toolkit.print_line() + + toolkit.print( + "Importing the FastAPI app object from the module with the following code:", + tag="code", + ) + toolkit.print_line() + toolkit.print( + f"[underline]from [bold]{module_data.module_import_str}[/bold] import [bold]{import_data.app_name}[/bold]" + ) + toolkit.print_line() + + toolkit.print( + f"Using import string: [blue]{import_string}[/]", + tag="app", + ) + + url = f"http://{host}:{port}" + url_docs = f"{url}/docs" + + toolkit.print_line() + toolkit.print( + f"Server started at [link={url}]{url}[/]", + f"Documentation at [link={url_docs}]{url_docs}[/]", + tag="server", + ) + + if command == "dev": + toolkit.print_line() + toolkit.print( + "Running in development mode, for production use: [bold]fastapi run[/]", + tag="tip", + ) + + if not uvicorn: + raise FastAPICLIException( + "Could not import Uvicorn, try running 'pip install uvicorn'" + ) from None + + toolkit.print_line() + toolkit.print("Logs:") + toolkit.print_line() + + uvicorn.run( + app=import_string, + host=host, + port=port, + reload=reload, + workers=workers, + root_path=root_path, + proxy_headers=proxy_headers, + log_config=get_uvicorn_log_config(), + ) + + +@app.command() +def dev( + path: Annotated[ + Union[Path, None], + typer.Argument( + help="A path to a Python file or package directory (with [blue]__init__.py[/blue] files) containing a [bold]FastAPI[/bold] app. If not provided, a default set of paths will be tried." + ), + ] = None, + *, + host: Annotated[ + str, + typer.Option( + help="The host to serve on. For local development in localhost use [blue]127.0.0.1[/blue]. To enable public access, e.g. in a container, use all the IP addresses available with [blue]0.0.0.0[/blue]." + ), + ] = "127.0.0.1", + port: Annotated[ + int, + typer.Option( + help="The port to serve on. You would normally have a termination proxy on top (another program) handling HTTPS on port [blue]443[/blue] and HTTP on port [blue]80[/blue], transferring the communication to your app." + ), + ] = 8000, + reload: Annotated[ + bool, + typer.Option( + help="Enable auto-reload of the server when (code) files change. This is [bold]resource intensive[/bold], use it only during development." + ), + ] = True, + root_path: Annotated[ + str, + typer.Option( + help="The root path is used to tell your app that it is being served to the outside world with some [bold]path prefix[/bold] set up in some termination proxy or similar." + ), + ] = "", + app: Annotated[ + Union[str, None], + typer.Option( + help="The name of the variable that contains the [bold]FastAPI[/bold] app in the imported module or package. If not provided, it is detected automatically." + ), + ] = None, + proxy_headers: Annotated[ + bool, + typer.Option( + help="Enable/Disable X-Forwarded-Proto, X-Forwarded-For, X-Forwarded-Port to populate remote address info." + ), + ] = True, +) -> Any: + """ + Run a [bold]FastAPI[/bold] app in [yellow]development[/yellow] mode. 🧪 + + This is equivalent to [bold]fastapi run[/bold] but with [bold]reload[/bold] enabled and listening on the [blue]127.0.0.1[/blue] address. + + It automatically detects the Python module or package that needs to be imported based on the file or directory path passed. + + If no path is passed, it tries with: + + - [blue]main.py[/blue] + - [blue]app.py[/blue] + - [blue]api.py[/blue] + - [blue]app/main.py[/blue] + - [blue]app/app.py[/blue] + - [blue]app/api.py[/blue] + + It also detects the directory that needs to be added to the [bold]PYTHONPATH[/bold] to make the app importable and adds it. + + It detects the [bold]FastAPI[/bold] app object to use. By default it looks in the module or package for an object named: + + - [blue]app[/blue] + - [blue]api[/blue] + + Otherwise, it uses the first [bold]FastAPI[/bold] app found in the imported module or package. + """ + _run( + path=path, + host=host, + port=port, + reload=reload, + root_path=root_path, + app=app, + command="dev", + proxy_headers=proxy_headers, + ) + + +@app.command() +def run( + path: Annotated[ + Union[Path, None], + typer.Argument( + help="A path to a Python file or package directory (with [blue]__init__.py[/blue] files) containing a [bold]FastAPI[/bold] app. If not provided, a default set of paths will be tried." + ), + ] = None, + *, + host: Annotated[ + str, + typer.Option( + help="The host to serve on. For local development in localhost use [blue]127.0.0.1[/blue]. To enable public access, e.g. in a container, use all the IP addresses available with [blue]0.0.0.0[/blue]." + ), + ] = "0.0.0.0", + port: Annotated[ + int, + typer.Option( + help="The port to serve on. You would normally have a termination proxy on top (another program) handling HTTPS on port [blue]443[/blue] and HTTP on port [blue]80[/blue], transferring the communication to your app." + ), + ] = 8000, + reload: Annotated[ + bool, + typer.Option( + help="Enable auto-reload of the server when (code) files change. This is [bold]resource intensive[/bold], use it only during development." + ), + ] = False, + workers: Annotated[ + Union[int, None], + typer.Option( + help="Use multiple worker processes. Mutually exclusive with the --reload flag." + ), + ] = None, + root_path: Annotated[ + str, + typer.Option( + help="The root path is used to tell your app that it is being served to the outside world with some [bold]path prefix[/bold] set up in some termination proxy or similar." + ), + ] = "", + app: Annotated[ + Union[str, None], + typer.Option( + help="The name of the variable that contains the [bold]FastAPI[/bold] app in the imported module or package. If not provided, it is detected automatically." + ), + ] = None, + proxy_headers: Annotated[ + bool, + typer.Option( + help="Enable/Disable X-Forwarded-Proto, X-Forwarded-For, X-Forwarded-Port to populate remote address info." + ), + ] = True, +) -> Any: + """ + Run a [bold]FastAPI[/bold] app in [green]production[/green] mode. 🚀 + + This is equivalent to [bold]fastapi dev[/bold] but with [bold]reload[/bold] disabled and listening on the [blue]0.0.0.0[/blue] address. + + It automatically detects the Python module or package that needs to be imported based on the file or directory path passed. + + If no path is passed, it tries with: + + - [blue]main.py[/blue] + - [blue]app.py[/blue] + - [blue]api.py[/blue] + - [blue]app/main.py[/blue] + - [blue]app/app.py[/blue] + - [blue]app/api.py[/blue] + + It also detects the directory that needs to be added to the [bold]PYTHONPATH[/bold] to make the app importable and adds it. + + It detects the [bold]FastAPI[/bold] app object to use. By default it looks in the module or package for an object named: + + - [blue]app[/blue] + - [blue]api[/blue] + + Otherwise, it uses the first [bold]FastAPI[/bold] app found in the imported module or package. + """ + _run( + path=path, + host=host, + port=port, + reload=reload, + workers=workers, + root_path=root_path, + app=app, + command="run", + proxy_headers=proxy_headers, + ) + + +def main() -> None: + app() diff --git a/venv/lib/python3.10/site-packages/fastapi_cli/discover.py b/venv/lib/python3.10/site-packages/fastapi_cli/discover.py new file mode 100644 index 0000000000000000000000000000000000000000..43d0e9c976d7026fd65b14901a53bc3ccd792bf1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastapi_cli/discover.py @@ -0,0 +1,132 @@ +import importlib +import sys +from dataclasses import dataclass +from logging import getLogger +from pathlib import Path +from typing import List, Union + +from fastapi_cli.exceptions import FastAPICLIException + +logger = getLogger(__name__) + +try: + from fastapi import FastAPI +except ImportError: # pragma: no cover + FastAPI = None # type: ignore[misc, assignment] + + +def get_default_path() -> Path: + potential_paths = ( + "main.py", + "app.py", + "api.py", + "app/main.py", + "app/app.py", + "app/api.py", + ) + + for full_path in potential_paths: + path = Path(full_path) + if path.is_file(): + return path + + raise FastAPICLIException( + "Could not find a default file to run, please provide an explicit path" + ) + + +@dataclass +class ModuleData: + module_import_str: str + extra_sys_path: Path + module_paths: List[Path] + + +def get_module_data_from_path(path: Path) -> ModuleData: + use_path = path.resolve() + module_path = use_path + if use_path.is_file() and use_path.stem == "__init__": + module_path = use_path.parent + module_paths = [module_path] + extra_sys_path = module_path.parent + for parent in module_path.parents: + init_path = parent / "__init__.py" + if init_path.is_file(): + module_paths.insert(0, parent) + extra_sys_path = parent.parent + else: + break + + module_str = ".".join(p.stem for p in module_paths) + return ModuleData( + module_import_str=module_str, + extra_sys_path=extra_sys_path.resolve(), + module_paths=module_paths, + ) + + +def get_app_name(*, mod_data: ModuleData, app_name: Union[str, None] = None) -> str: + try: + mod = importlib.import_module(mod_data.module_import_str) + except (ImportError, ValueError) as e: + logger.error(f"Import error: {e}") + logger.warning( + "Ensure all the package directories have an [blue]__init__.py[/blue] file" + ) + raise + if not FastAPI: # type: ignore[truthy-function] + raise FastAPICLIException( + "Could not import FastAPI, try running 'pip install fastapi'" + ) from None + object_names = dir(mod) + object_names_set = set(object_names) + if app_name: + if app_name not in object_names_set: + raise FastAPICLIException( + f"Could not find app name {app_name} in {mod_data.module_import_str}" + ) + app = getattr(mod, app_name) + if not isinstance(app, FastAPI): + raise FastAPICLIException( + f"The app name {app_name} in {mod_data.module_import_str} doesn't seem to be a FastAPI app" + ) + return app_name + for preferred_name in ["app", "api"]: + if preferred_name in object_names_set: + obj = getattr(mod, preferred_name) + if isinstance(obj, FastAPI): + return preferred_name + for name in object_names: + obj = getattr(mod, name) + if isinstance(obj, FastAPI): + return name + raise FastAPICLIException("Could not find FastAPI app in module, try using --app") + + +@dataclass +class ImportData: + app_name: str + module_data: ModuleData + import_string: str + + +def get_import_data( + *, path: Union[Path, None] = None, app_name: Union[str, None] = None +) -> ImportData: + if not path: + path = get_default_path() + + logger.debug(f"Using path [blue]{path}[/blue]") + logger.debug(f"Resolved absolute path {path.resolve()}") + + if not path.exists(): + raise FastAPICLIException(f"Path does not exist {path}") + mod_data = get_module_data_from_path(path) + sys.path.insert(0, str(mod_data.extra_sys_path)) + use_app_name = get_app_name(mod_data=mod_data, app_name=app_name) + + import_string = f"{mod_data.module_import_str}:{use_app_name}" + + return ImportData( + app_name=use_app_name, module_data=mod_data, import_string=import_string + ) diff --git a/venv/lib/python3.10/site-packages/fastapi_cli/utils/__init__.py b/venv/lib/python3.10/site-packages/fastapi_cli/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/fastapi_cli/utils/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/fastapi_cli/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b1a7f6e645254a535441e82efd64713ce5668c7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/fastapi_cli/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/fastapi_cli/utils/__pycache__/cli.cpython-310.pyc b/venv/lib/python3.10/site-packages/fastapi_cli/utils/__pycache__/cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61f96ed48e44f5b13a015fc7d75815c191e7de60 Binary files /dev/null and b/venv/lib/python3.10/site-packages/fastapi_cli/utils/__pycache__/cli.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/fastapi_cli/utils/cli.py b/venv/lib/python3.10/site-packages/fastapi_cli/utils/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..f6805e7c6cf7bd3d57ab55f5030c0a98d75092ca --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastapi_cli/utils/cli.py @@ -0,0 +1,76 @@ +import logging +from typing import Any, Dict + +from rich_toolkit import RichToolkit, RichToolkitTheme +from rich_toolkit.styles import TaggedStyle +from uvicorn.logging import DefaultFormatter + + +class CustomFormatter(DefaultFormatter): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.toolkit = get_rich_toolkit() + + def formatMessage(self, record: logging.LogRecord) -> str: + return self.toolkit.print_as_string(record.getMessage(), tag=record.levelname) + + +def get_uvicorn_log_config() -> Dict[str, Any]: + return { + "version": 1, + "disable_existing_loggers": False, + "formatters": { + "default": { + "()": CustomFormatter, + "fmt": "%(levelprefix)s %(message)s", + "use_colors": None, + }, + "access": { + "()": CustomFormatter, + "fmt": "%(levelprefix)s %(client_addr)s - '%(request_line)s' %(status_code)s", + }, + }, + "handlers": { + "default": { + "formatter": "default", + "class": "logging.StreamHandler", + "stream": "ext://sys.stderr", + }, + "access": { + "formatter": "access", + "class": "logging.StreamHandler", + "stream": "ext://sys.stdout", + }, + }, + "loggers": { + "uvicorn": {"handlers": ["default"], "level": "INFO"}, + "uvicorn.error": {"level": "INFO"}, + "uvicorn.access": { + "handlers": ["access"], + "level": "INFO", + "propagate": False, + }, + }, + } + + +logger = logging.getLogger(__name__) + + +def get_rich_toolkit() -> RichToolkit: + theme = RichToolkitTheme( + style=TaggedStyle(tag_width=11), + theme={ + "tag.title": "white on #009485", + "tag": "white on #007166", + "placeholder": "grey85", + "text": "white", + "selected": "#007166", + "result": "grey85", + "progress": "on #007166", + "error": "red", + "log.info": "black on blue", + }, + ) + + return RichToolkit(theme=theme) diff --git a/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/METADATA b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..e2c8c30a04e1ac6296732bbe4d19ce4cefbdb7d3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/METADATA @@ -0,0 +1,68 @@ +Metadata-Version: 2.1 +Name: fastapi-cloud-cli +Version: 0.1.5 +Summary: Deploy and manage FastAPI Cloud apps from the command line 🚀 +Author-Email: Patrick Arminio +License: MIT +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: System Administrators +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python +Classifier: Topic :: Software Development :: Libraries :: Application Frameworks +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development +Classifier: Typing :: Typed +Classifier: Development Status :: 4 - Beta +Classifier: Framework :: FastAPI +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: License :: OSI Approved :: MIT License +Project-URL: Homepage, https://github.com/fastapilabs/fastapi-cloud-cli +Project-URL: Documentation, https://fastapi.tiangolo.com/fastapi-cloud-cli/ +Project-URL: Repository, https://github.com/fastapilabs/fastapi-cloud-cli +Project-URL: Issues, https://github.com/fastapilabs/fastapi-cloud-cli/issues +Project-URL: Changelog, https://github.com/fastapilabs/fastapi-cloud-cli/blob/main/release-notes.md +Requires-Python: >=3.8 +Requires-Dist: typer>=0.12.3 +Requires-Dist: uvicorn[standard]>=0.15.0 +Requires-Dist: rignore>=0.5.1 +Requires-Dist: httpx>=0.27.0 +Requires-Dist: rich-toolkit>=0.14.5 +Requires-Dist: pydantic[email]>=1.6.1 +Requires-Dist: sentry-sdk>=2.20.0 +Provides-Extra: standard +Requires-Dist: uvicorn[standard]>=0.15.0; extra == "standard" +Description-Content-Type: text/markdown + +# FastAPI Cloud CLI + + + Test + + + Publish + + + Coverage + + Package version + + +--- + +**Source Code**: https://github.com/fastapilabs/fastapi-cloud-cli + +--- + +## License + +This project is licensed under the terms of the MIT license. diff --git a/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/RECORD b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..dbfa55b0a64533dc3cec35cb6ab7741132e8e0aa --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/RECORD @@ -0,0 +1,45 @@ +fastapi_cloud_cli-0.1.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +fastapi_cloud_cli-0.1.5.dist-info/METADATA,sha256=hy3DjoOv-y01dnY4o3ECBiL7ymffxOqe-l_QCMGtgx0,3227 +fastapi_cloud_cli-0.1.5.dist-info/RECORD,, +fastapi_cloud_cli-0.1.5.dist-info/WHEEL,sha256=9P2ygRxDrTJz3gsagc0Z96ukrxjr-LFBGOgv3AuKlCA,90 +fastapi_cloud_cli-0.1.5.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34 +fastapi_cloud_cli-0.1.5.dist-info/licenses/LICENSE,sha256=FqD5B4VbXJnefprQseE0U8llL6FxojC-i8muZy7YmSU,1086 +fastapi_cloud_cli/__init__.py,sha256=rPSfWgIeq2YWVPyESOAwCBt8vftsTpIkuLAGDEzyRQc,22 +fastapi_cloud_cli/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30 +fastapi_cloud_cli/__pycache__/__init__.cpython-310.pyc,, +fastapi_cloud_cli/__pycache__/__main__.cpython-310.pyc,, +fastapi_cloud_cli/__pycache__/cli.cpython-310.pyc,, +fastapi_cloud_cli/__pycache__/config.cpython-310.pyc,, +fastapi_cloud_cli/__pycache__/logging.cpython-310.pyc,, +fastapi_cloud_cli/cli.py,sha256=qZjMCm3455tgX8HSLM84LFKSPQgVztF6MPzYcgXSmnY,552 +fastapi_cloud_cli/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fastapi_cloud_cli/commands/__pycache__/__init__.cpython-310.pyc,, +fastapi_cloud_cli/commands/__pycache__/deploy.cpython-310.pyc,, +fastapi_cloud_cli/commands/__pycache__/env.cpython-310.pyc,, +fastapi_cloud_cli/commands/__pycache__/login.cpython-310.pyc,, +fastapi_cloud_cli/commands/__pycache__/logout.cpython-310.pyc,, +fastapi_cloud_cli/commands/__pycache__/whoami.cpython-310.pyc,, +fastapi_cloud_cli/commands/deploy.py,sha256=m1k2TB4d7zoLlpB2mpgBg-hFMmNJmg9HsyHWxghjLqM,19272 +fastapi_cloud_cli/commands/env.py,sha256=34wCmz0OCDk_r8CSX3xRs1pO3KtUGY_Ge4GTC6PaUxA,7127 +fastapi_cloud_cli/commands/login.py,sha256=EgN7wW8qrQnAxLYIoS-kCzUMRVAMiXRqpFpSj_9wmCU,2822 +fastapi_cloud_cli/commands/logout.py,sha256=XpZ4RBzJP8PZVoa6RXgy6hq2_KGsDiAfabxJXLOD3es,329 +fastapi_cloud_cli/commands/whoami.py,sha256=6R9c2GAwmCV7fF1KE85tLMzLiuL7dB4y0iIzZLCa4YA,802 +fastapi_cloud_cli/config.py,sha256=Stme6dH1zwk0LH80x4OKUrBH-DjSAaCoY9_zlgcyH6U,686 +fastapi_cloud_cli/logging.py,sha256=GOlwUO9mi0EcSwgnBZTEA-v9_MjKVmVHlNlIKkorHQU,858 +fastapi_cloud_cli/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fastapi_cloud_cli/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fastapi_cloud_cli/utils/__pycache__/__init__.cpython-310.pyc,, +fastapi_cloud_cli/utils/__pycache__/api.cpython-310.pyc,, +fastapi_cloud_cli/utils/__pycache__/apps.cpython-310.pyc,, +fastapi_cloud_cli/utils/__pycache__/auth.cpython-310.pyc,, +fastapi_cloud_cli/utils/__pycache__/cli.cpython-310.pyc,, +fastapi_cloud_cli/utils/__pycache__/config.cpython-310.pyc,, +fastapi_cloud_cli/utils/__pycache__/env.cpython-310.pyc,, +fastapi_cloud_cli/utils/__pycache__/sentry.cpython-310.pyc,, +fastapi_cloud_cli/utils/api.py,sha256=NWbWvf_rKP-zXkAdpmO9dd7J3u0vHzTapNTMnv4zIto,566 +fastapi_cloud_cli/utils/apps.py,sha256=LbTwRO4zWTBNFB9aiB7nL-v4jkQ1Xh6jP2w4ZpX-lT8,1890 +fastapi_cloud_cli/utils/auth.py,sha256=zpi2h7eMWKzZErXq9zeAd8kZ1mDXsiS0RBr2Z9IWV9s,1613 +fastapi_cloud_cli/utils/cli.py,sha256=IdYlbGRq79DtqHVMldC_f9vvc2Sg76PiUpbeGXWtuoQ,2861 +fastapi_cloud_cli/utils/config.py,sha256=ebwN1RN8NJ3oIcBUyxF48Al0P4zvBnSMMoy779yMBHU,465 +fastapi_cloud_cli/utils/env.py,sha256=a9S6ehNGxhKbQHXxFVJtjqMEkodKwKa0wOvRVh9VBjw,125 +fastapi_cloud_cli/utils/sentry.py,sha256=Vrr4u3O3XvLrOVUUI34JXkEW3jfQEJkDpf274h9KVoE,489 diff --git a/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/WHEEL b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..045c8acdea31cbca5be986e915f784c1aafc720f --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: pdm-backend (2.4.5) +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/entry_points.txt b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..c3ad4726d437022e5c606a4206ffb6007347a008 --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/entry_points.txt @@ -0,0 +1,4 @@ +[console_scripts] + +[gui_scripts] + diff --git a/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/licenses/LICENSE b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ef706eaeccc818c83d2921d7d1199f6ff9210a65 --- /dev/null +++ b/venv/lib/python3.10/site-packages/fastapi_cloud_cli-0.1.5.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024 Sebastián Ramírez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/venv/lib/python3.10/site-packages/mistral_common/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b3c9642df11cca3654313bc381cf402d4a215bf Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/__pycache__/audio.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/audio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd0f1e94e0c0f9529b94da05489a62856f3f8795 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/audio.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/__pycache__/base.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d1820271f03528e7ac27a39272ddfb4e35efed9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c497496685506e2dec76f7c09d11fbdc98701538 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/exceptions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/__pycache__/image.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/image.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74779e3093693f34aaeed3ba3c359495cc09d50d Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/image.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/__pycache__/multimodal.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/multimodal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b876af416baa3b6dd76fa54a879b1b77949a0ab Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/__pycache__/multimodal.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/__init__.py b/venv/lib/python3.10/site-packages/mistral_common/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59dbd7fc847d7321f76a305910483d41ace5a226 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/think.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/think.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa23cd5033c21d2d1a3b0b5443e3603d59d9ed55 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/think.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/tools.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08c09f3342bf129dab3ecefc573fe2378685121c Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/tools.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50fabacdc0813259bdba36f4c25b90969f1e2a61 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/experimental/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__init__.py b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9063ba328d1a76dd6d325279c80e9a3068735ce9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/main.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/main.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7455f2f247bfbfdf28822e511dda99f974b28371 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/main.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/models.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..298a1cca21fc5ccf66f0f23dc0e908a9a4423cdf Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/models.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/routers.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/routers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aafb50a1f83dfaa150fc253d784ad9d17a45360c Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/__pycache__/routers.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/app/main.py b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..5fcb7249fb772f0d82a667f269eb183b568f2d86 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/main.py @@ -0,0 +1,137 @@ +from functools import lru_cache +from pathlib import Path +from typing import Union + +import click +import uvicorn +from fastapi import FastAPI + +from mistral_common.experimental.app.models import ( + EngineBackend, + Settings, + get_settings, +) +from mistral_common.experimental.app.routers import ( + decode_router, + main_router, + tokenize_router, +) +from mistral_common.protocol.instruct.validator import ValidationMode +from mistral_common.tokens.tokenizers.mistral import MistralTokenizer + + +def create_app( + tokenizer: Union[str, Path, MistralTokenizer], + validation_mode: ValidationMode = ValidationMode.test, + engine_url: str = "127.0.0.1", + engine_backend: EngineBackend = EngineBackend.llama_cpp, + timeout: int = 60, +) -> FastAPI: + r"""Create a Mistral-common FastAPI app with the given tokenizer and validation mode. + + Args: + tokenizer: The tokenizer path or a MistralTokenizer instance. + validation_mode: The validation mode to use. + engine_url: The URL of the engine API. + timeout: The timeout of the engine API. + + Returns: + The Mistral-common FastAPI app. + """ + if not isinstance(tokenizer, (MistralTokenizer, str, Path)): + raise ValueError("Tokenizer must be a path or a MistralTokenizer instance.") + + app = FastAPI() + app.include_router(tokenize_router) + app.include_router(decode_router) + app.include_router(main_router) + + @lru_cache + def get_settings_override() -> Settings: + settings = Settings( + engine_url=engine_url, + engine_backend=engine_backend, + timeout=timeout, + ) + if isinstance(tokenizer, MistralTokenizer): + settings.tokenizer = tokenizer + else: + settings._load_tokenizer(tokenizer, validation_mode) + return settings + + get_settings_override() + app.dependency_overrides[get_settings] = get_settings_override + + return app + + +@click.group() +def cli() -> None: + r"""Mistral-common CLI.""" + pass + + +@cli.command(name="serve", context_settings={"auto_envvar_prefix": "UVICORN"}) +@click.argument("tokenizer_path", type=str) +@click.argument( + "validation_mode", + type=click.Choice([mode.value for mode in ValidationMode], case_sensitive=False), + default=ValidationMode.test.value, +) +@click.option( + "--host", + type=str, + default="127.0.0.1", + help="Mistral-common API host", + show_default=True, +) +@click.option( + "--port", + type=int, + default=0, + help="Mistral-common API port", + show_default=True, +) +@click.option( + "--engine-url", + type=str, + default="http://127.0.0.1:8080", + help="Enginge URL", + show_default=True, +) +@click.option( + "--engine-backend", + type=click.Choice([mode.value for mode in EngineBackend], case_sensitive=False), + default=EngineBackend.llama_cpp.value, + help="Engine API backend", + show_default=True, +) +@click.option( + "--timeout", + type=int, + default=60, + help="Timeout", + show_default=True, +) +def serve( + tokenizer_path: Union[str, Path], + validation_mode: Union[ValidationMode, str] = ValidationMode.test, + host: str = "127.0.0.1", + port: int = 0, + engine_url: str = "http://127.0.0.1:8080", + engine_backend: str = EngineBackend.llama_cpp.value, + timeout: int = 60, +) -> None: + r"""Serve the Mistral-common API with the given tokenizer path and validation mode.""" + app = create_app( + tokenizer=tokenizer_path, + validation_mode=ValidationMode(validation_mode), + engine_url=engine_url, + engine_backend=EngineBackend(engine_backend), + timeout=timeout, + ) + uvicorn.run(app, host=host, port=port) + + +if __name__ == "__main__": + cli() diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/app/models.py b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/models.py new file mode 100644 index 0000000000000000000000000000000000000000..80261b0a13c8757f6abdfd1432e3344b6adb77a4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/models.py @@ -0,0 +1,126 @@ +import importlib.metadata +from enum import Enum +from pathlib import Path +from typing import Any, List, Optional, Union + +from pydantic import BaseModel, ConfigDict, field_validator +from pydantic_settings import BaseSettings + +from mistral_common.protocol.instruct.validator import ValidationMode +from mistral_common.tokens.tokenizers.mistral import MistralTokenizer + + +class OpenAIChatCompletionRequest(BaseModel): + r"""OpenAI chat completion request. + + This class is used to parse the request body for the OpenAI chat completion endpoint. + + Attributes: + messages: The messages to use for the chat completion. + tools: The tools to use for the chat completion. + + Note: + This class accepts extra fields that are not validated. + """ + + messages: List[dict[str, Union[str, List[dict[str, Union[str, dict[str, Any]]]]]]] + tools: Optional[List[dict[str, Any]]] = None + + # Allow extra fields as the `from_openai` method will handle them. + # We never validate the input, so we don't need to worry about the extra fields. + model_config = ConfigDict(extra="allow") + + def drop_extra_fields(self) -> dict[str, Any]: + r"""Drop extra fields from the model. + + This method is used to drop extra fields from the model, which are not defined in the model fields. + + Returns: + The extra fields that were dropped from the model. + """ + extra_fields = { + field: value for field, value in self.model_dump().items() if field not in type(self).model_fields + } + + self.__dict__ = {k: v for k, v in self.__dict__.items() if k not in extra_fields} + return extra_fields + + +class EngineBackend(str, Enum): + r"""The engine backend to use. + + Attributes: + llama_cpp: The llama.cpp backend. + """ + + llama_cpp = "llama_cpp" + + +class Settings(BaseSettings): + r"""Settings for the Mistral-common API. + + Attributes: + app_name: The name of the application. + app_version: The version of the application. + engine_url: The URL of the engine. + engine_backend: The backend to use for the engine. + timeout: The timeout to use for the engine API. + """ + + app_name: str = "Mistral-common API" + app_version: str = importlib.metadata.version("mistral-common") + engine_url: str = "127.0.0.1" + engine_backend: EngineBackend = EngineBackend.llama_cpp + api_key: str = "" + timeout: int = 60 + + @field_validator("engine_url", mode="before") + @classmethod + def _validate_engine_url(cls, value: str) -> str: + if isinstance(value, str) and value.endswith("/"): + value = value[:-1] + return value + + @field_validator("engine_backend", mode="before") + @classmethod + def _validate_backend(cls, value: Union[str, EngineBackend]) -> EngineBackend: + if isinstance(value, str): + value = EngineBackend(value) + return value + + def model_post_init(self, context: Any) -> None: + super().model_post_init(context) + self._tokenizer: Optional[MistralTokenizer] = None + + def _load_tokenizer(self, tokenizer_path: Union[str, Path], validation_mode: ValidationMode) -> None: + if tokenizer_path == "": + raise ValueError("Tokenizer path must be set via the environment variable `TOKENIZER_PATH`.") + elif self._tokenizer is not None: + raise ValueError("Tokenizer has already been initialized.") + + if isinstance(tokenizer_path, str): + candidate_tokenizer_path = Path(tokenizer_path) + if candidate_tokenizer_path.exists(): + tokenizer_path = candidate_tokenizer_path + + if isinstance(tokenizer_path, Path) and tokenizer_path.exists(): + self._tokenizer = MistralTokenizer.from_file(tokenizer_path, mode=validation_mode) + else: + self._tokenizer = MistralTokenizer.from_hf_hub(str(tokenizer_path), mode=validation_mode) + + @property + def tokenizer(self) -> MistralTokenizer: + if self._tokenizer is None: + raise ValueError("Tokenizer not initialized.") + return self._tokenizer + + @tokenizer.setter + def tokenizer(self, value: MistralTokenizer) -> None: + if not isinstance(value, MistralTokenizer): + raise ValueError("Tokenizer must be an instance of MistralTokenizer.") + self._tokenizer = value + + +def get_settings() -> Settings: + r"""Get the settings for the Mistral-common API.""" + return Settings() diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/app/routers.py b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/routers.py new file mode 100644 index 0000000000000000000000000000000000000000..97c21089959666a8e862ccc4fa0d9f82771a5e09 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/experimental/app/routers.py @@ -0,0 +1,203 @@ +import json +from typing import Annotated, List, Optional, Union + +import requests +from fastapi import APIRouter, Body, Depends, HTTPException +from fastapi.responses import RedirectResponse +from pydantic import ValidationError + +from mistral_common.experimental.app.models import ( + EngineBackend, + OpenAIChatCompletionRequest, + Settings, + get_settings, +) +from mistral_common.experimental.think import _split_content_and_think_chunks +from mistral_common.experimental.tools import _decode_tool_calls, _split_content_and_tool_calls +from mistral_common.protocol.instruct.messages import AssistantMessage, TextChunk, ThinkChunk +from mistral_common.protocol.instruct.request import ChatCompletionRequest +from mistral_common.tokens.tokenizers.base import SpecialTokenPolicy, Tokenized, TokenizerVersion +from mistral_common.tokens.tokenizers.instruct import InstructTokenizerV13 + +main_router = APIRouter(tags=["app"]) +tokenize_router = APIRouter(prefix="/v1/tokenize", tags=["tokenizer", "tokenize"]) +decode_router = APIRouter(prefix="/v1/detokenize", tags=["tokenizer", "detokenize"]) + + +@main_router.get("/") +async def redirect_to_docs() -> RedirectResponse: + r"""Redirect to the documentation.""" + return RedirectResponse(url="docs") + + +@tokenize_router.post("/") +async def tokenize_request( + request: Union[ChatCompletionRequest, OpenAIChatCompletionRequest], + settings: Annotated[Settings, Depends(get_settings)], +) -> list[int]: + r"""Tokenize a chat completion request.""" + if isinstance(request, OpenAIChatCompletionRequest): + try: + request.drop_extra_fields() + request = ChatCompletionRequest.from_openai(**request.model_dump()) + except (ValidationError, ValueError) as e: + raise HTTPException(status_code=400, detail=str(e)) + + if request.messages == []: + raise HTTPException(status_code=400, detail="Messages list cannot be empty.") + + tokenized = settings.tokenizer.encode_chat_completion(request) + assert isinstance(tokenized, Tokenized), type(tokenized) + return tokenized.tokens + + +@decode_router.post("/string") +async def detokenize_to_string( + settings: Annotated[Settings, Depends(get_settings)], + tokens: list[int] = Body(default_factory=list), + special_token_policy: SpecialTokenPolicy = Body(default=SpecialTokenPolicy.IGNORE), +) -> str: + r"""Detokenize a list of tokens to a string. + + Args: + tokens: The tokens to detokenize. + special_token_policy: The policy to use for special tokens. + + Returns: + The detokenized string or assistant message. + """ + if len(tokens) == 0: + raise HTTPException(status_code=400, detail="Tokens list cannot be empty.") + try: + return settings.tokenizer.decode(tokens, special_token_policy=special_token_policy) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + + +@decode_router.post("/") +async def detokenize_to_assistant_message( + settings: Annotated[Settings, Depends(get_settings)], + tokens: list[int] = Body(default_factory=list), +) -> AssistantMessage: + r"""Detokenize a list of tokens to an assistant message. + + Parse tool calls from the tokens and extract content before the first tool call. + + Args: + tokens: The tokens to detokenize. + + Returns: + The detokenized assistant message. + """ + if len(tokens) == 0: + raise HTTPException(status_code=400, detail="Tokens list cannot be empty.") + + if settings.tokenizer.instruct_tokenizer.tokenizer.version > TokenizerVersion.v1: + content_tokens, tool_calls_tokens = _split_content_and_tool_calls( + tokens, settings.tokenizer.instruct_tokenizer.tokenizer.get_control_token("[TOOL_CALLS]") + ) + else: + content_tokens, tool_calls_tokens = tokens, () + + content: Optional[Union[str, List[Union[TextChunk, ThinkChunk]]]] = None + + if settings.tokenizer.instruct_tokenizer.tokenizer.version >= TokenizerVersion.v13: + assert isinstance(settings.tokenizer.instruct_tokenizer, InstructTokenizerV13) + + begin_think = settings.tokenizer.instruct_tokenizer.BEGIN_THINK + end_think = settings.tokenizer.instruct_tokenizer.END_THINK + else: + begin_think = end_think = None + + if begin_think is not None and end_think is not None: + try: + content_or_think_tokens = _split_content_and_think_chunks(content_tokens, begin_think, end_think) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + + eos = settings.tokenizer.instruct_tokenizer.tokenizer.eos_id + + if content_or_think_tokens: + content = [ + TextChunk(text=settings.tokenizer.decode(chunk, special_token_policy=SpecialTokenPolicy.IGNORE)) + if not is_think + else ThinkChunk( + thinking=settings.tokenizer.decode(chunk, special_token_policy=SpecialTokenPolicy.IGNORE), + closed=chunk[-1] == end_think, + ) + for chunk, is_think in content_or_think_tokens + if chunk != [eos] # Don't add a TextChunk with just the EOS token + ] + if len(content) == 1 and isinstance(content[0], TextChunk): + content = content[0].text + + elif content_tokens: + content = settings.tokenizer.decode(content_tokens, special_token_policy=SpecialTokenPolicy.IGNORE) + + if tool_calls_tokens: + try: + tool_calls = _decode_tool_calls(tool_calls_tokens, settings.tokenizer.instruct_tokenizer.tokenizer) + except (ValueError, json.JSONDecodeError) as e: + raise HTTPException(status_code=400, detail=str(e)) + else: + tool_calls = None + + has_eos = tokens[-1] == settings.tokenizer.instruct_tokenizer.tokenizer.eos_id + + return AssistantMessage(content=content, tool_calls=tool_calls, prefix=not has_eos) + + +@main_router.post("/v1/chat/completions", tags=["chat", "completions"]) +async def generate( + request: Union[ChatCompletionRequest, OpenAIChatCompletionRequest], + settings: Annotated[Settings, Depends(get_settings)], +) -> AssistantMessage: + r"""Generate a chat completion. + + Args: + request: The chat completion request. + settings: The settings for the Mistral-common API. + + Returns: + The generated chat completion. + """ + if isinstance(request, OpenAIChatCompletionRequest): + extra_fields = request.drop_extra_fields() + request = ChatCompletionRequest.from_openai(**request.model_dump()) + else: + extra_fields = {} + tokens_ids = await tokenize_request(request, settings) + + exclude_fields = {"messages", "tools"} + + request_json = request.model_dump() + request_json.update(extra_fields) + + request_json = {k: v for k, v in request_json.items() if k not in exclude_fields} + + if request_json.get("stream", False): + raise HTTPException(status_code=400, detail="Streaming is not supported.") + + try: + if settings.engine_backend == EngineBackend.llama_cpp: + response = requests.post( + f"{settings.engine_url}/completions", + json={ + "prompt": tokens_ids, + "return_tokens": True, + **request_json, + }, + timeout=settings.timeout, + ) + else: + raise ValueError(f"Unsupported engine backend: {settings.engine_backend}") + except requests.exceptions.Timeout: + raise HTTPException(status_code=504, detail="Timeout") + except requests.exceptions.RequestException as e: + raise HTTPException(status_code=500, detail=str(e)) + + if response.status_code != 200: + raise HTTPException(status_code=response.status_code, detail=response.text) + + response_json = response.json() + return await detokenize_to_assistant_message(settings, response_json["tokens"]) diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/think.py b/venv/lib/python3.10/site-packages/mistral_common/experimental/think.py new file mode 100644 index 0000000000000000000000000000000000000000..ae37e1c8005a253787e52d3ea1b19b29f249888a --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/experimental/think.py @@ -0,0 +1,47 @@ +from typing import List, Tuple + + +def _split_content_and_think_chunks( + tokens: List[int], begin_think_token_id: int, end_think_token_id: int +) -> List[Tuple[List[int], bool]]: + r"""Split the content and think chunks from a list of tokens. + + Args: + tokens: List of tokens. + begin_think_token_id: The token id for the begin think token. + end_think_token_id: The token id for the end think token. + + Returns: + List of tuples, where each tuple contains a list of tokens and a boolean indicating if the chunk is a think + chunk. + """ + if not tokens: + return [] + + content_chunks: List[Tuple[List[int], bool]] = [] + current_content: List[int] = [] + + in_think_chunk = False + for token in tokens: + if token == begin_think_token_id and in_think_chunk: + raise ValueError("Nested think chunks are not allowed.") + elif token == begin_think_token_id: + if current_content: + content_chunks.append((current_content, False)) + current_content = [] + in_think_chunk = True + current_content.append(token) + elif token == end_think_token_id: + if not in_think_chunk: + raise ValueError("End think token found without a begin think token.") + current_content.append(token) + content_chunks.append((current_content, True)) + current_content = [] + in_think_chunk = False + else: + current_content.append(token) + + if current_content: + content_chunks.append((current_content, in_think_chunk)) + + return content_chunks diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/tools.py b/venv/lib/python3.10/site-packages/mistral_common/experimental/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..2405bf787be0ed3c45008dfdb11ce17bbfb34888 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/experimental/tools.py @@ -0,0 +1,160 @@ +import json +from typing import List, Sequence, Tuple + +from mistral_common.experimental.utils import ( + _split_integer_list_by_value, + _split_tokens_by_one_occurence_control_token, +) +from mistral_common.protocol.instruct.tool_calls import FunctionCall, ToolCall +from mistral_common.tokens.tokenizers.base import SpecialTokenPolicy, Tokenizer, TokenizerVersion + + +class InvalidToolCallError(ValueError): + pass + + +class InvalidArgsToolCallError(InvalidToolCallError): + pass + + +def _split_content_and_tool_calls( + tokens: List[int], tool_call_token_id: int +) -> tuple[List[int], Tuple[List[int], ...]]: + r"""Split the content and tool calls from a list of tokens. + + The content is the first sequence of tokens that does not start with the tool call token ID. + The tool calls are the remaining sequences of tokens that start with the tool call token ID. + + Args: + tokens: The list of tokens. + tool_call_token_id: The token ID that indicates the start of a tool call. + + Returns: + A tuple containing the content and tool calls. + """ + if not tokens: + return [], () + + maybe_content_and_tools_calls = _split_integer_list_by_value(tokens, tool_call_token_id) + + has_content = maybe_content_and_tools_calls[0][0] != tool_call_token_id + if has_content: + content_tokens = maybe_content_and_tools_calls[0] + tools_calls_tokens = maybe_content_and_tools_calls[1:] + else: + content_tokens = [] + tools_calls_tokens = maybe_content_and_tools_calls + + return content_tokens, tools_calls_tokens + + +def _decode_tool_calls_v2_up_to_v7(tool_call_tokens: list[int], tokenizer: Tokenizer) -> List[ToolCall]: + r"""Decode a list of tool call tokens into a list of tool calls for tokenizer versions v2 to v7. + + Note: + Expects the tool call tokens to be in the format: + + `[TOOL_CALLS][{"id": "call_id", "name": "name", "arguments": {"arg1": "value1", "arg2": "value2"}}, ...]` + or + + `[TOOL_CALLS][{"name": "name", "arguments": {"arg1": "value1", "arg2": "value2"}}, ...]` + """ + tool_calls_list_string = tokenizer.decode(tool_call_tokens, special_token_policy=SpecialTokenPolicy.IGNORE) + try: + tool_calls_decoded_list = json.loads(tool_calls_list_string) + for tool_call in tool_calls_decoded_list: + # Check that the tool call arguments are dicts. + if "arguments" not in tool_call or not isinstance(tool_call["arguments"], dict): + raise InvalidArgsToolCallError("Invalid tool call arguments tokenization. Expected a dict.") + except json.JSONDecodeError as e: + raise InvalidToolCallError( + "Invalid tool call tokenization. Expected a JSON list of tool calls.", + ) from e + + if not isinstance(tool_calls_decoded_list, list): + raise InvalidToolCallError("Invalid tool call tokenization. Expected a list of tool calls.") + + return [ + ToolCall( + id=tool_call.get("id", "null"), + function=FunctionCall(name=tool_call["name"], arguments=tool_call["arguments"]), + ) + for tool_call in tool_calls_decoded_list + ] + + +def _decode_tool_call_v11_with_call_id(tool_call_tokens: list[int], tokenizer: Tokenizer) -> ToolCall: + r"""Decode a list of tool call tokens into a tool call for tokenizer version v11 with call ID. + + Note: + Expects the tool call tokens to be in the format: + + `[TOOL_CALLS]name[CALL_ID]call_id[ARGS]{"arg1": "value1", "arg2": "value2"}` + + """ + name, call_id_and_args = _split_tokens_by_one_occurence_control_token(tool_call_tokens, tokenizer, "[CALL_ID]") + + call_id, args = _split_tokens_by_one_occurence_control_token(call_id_and_args, tokenizer, "[ARGS]") + + try: + tool_call = ToolCall( + id=tokenizer.decode(call_id), + function=FunctionCall( + name=tokenizer.decode(name), + arguments=json.loads(tokenizer.decode(args, special_token_policy=SpecialTokenPolicy.IGNORE)), + ), + ) + except json.JSONDecodeError as e: + raise InvalidArgsToolCallError("Invalid tokenized tool call arguments.") from e + return tool_call + + +def _decode_tool_call_v11(tool_call_tokens: list[int], tokenizer: Tokenizer) -> ToolCall: + r"""Decode a list of tool call tokens into a tool call for tokenizer version v11 without call ID. + + Note: + Expects the tool call tokens to be in the format: + + `[TOOL_CALLS]name[ARGS]{"arg1": "value1", "arg2": "value2"}` + """ + name, args = _split_tokens_by_one_occurence_control_token(tool_call_tokens, tokenizer, "[ARGS]") + try: + tool_call = ToolCall( + function=FunctionCall( + name=tokenizer.decode(name, special_token_policy=SpecialTokenPolicy.IGNORE), + arguments=json.loads(tokenizer.decode(args, special_token_policy=SpecialTokenPolicy.IGNORE)), + ), + ) + except json.JSONDecodeError as e: + raise InvalidArgsToolCallError("Invalid tokenized tool call arguments.") from e + return tool_call + + +def _decode_tool_calls(tool_call_tokens: Sequence[list[int]], tokenizer: Tokenizer) -> List[ToolCall]: + r"""Decode a list of tool call tokens into a list of tool calls. + + Note: + Each list of tool call tokens are expected to be in the format: + - v2 to v7: `[TOOL_CALLS][{"name": "name", "arguments": {"arg1": "value1", "arg2": "value2"}}, ...]` + - v11+ without call ID: `[TOOL_CALLS]name[ARGS]{"arg1": "value1", "arg2": "value2"}` + - v11+ with call ID: `[TOOL_CALLS]name[CALL_ID]call_id[ARGS]{"arg1": "value1", "arg2": "value2"}` + + Args: + tool_call_tokens: A list of lists of tokens. + tokenizer: The tokenizer to use for decoding. + + Returns: + The list of decoded tool calls. + """ + tools_calls = [] + for tool_call in tool_call_tokens: + if tokenizer.version == TokenizerVersion.v1: + raise ValueError("Tool calls are not supported for tokenizer version v1.") + elif tokenizer.version <= TokenizerVersion.v7: + tools_calls.extend(_decode_tool_calls_v2_up_to_v7(tool_call, tokenizer)) + elif tokenizer.version == TokenizerVersion.v11 and tokenizer.get_control_token("[CALL_ID]") in tool_call: + tools_calls.append(_decode_tool_call_v11_with_call_id(tool_call, tokenizer)) + else: + tools_calls.append(_decode_tool_call_v11(tool_call, tokenizer)) + + return tools_calls diff --git a/venv/lib/python3.10/site-packages/mistral_common/experimental/utils.py b/venv/lib/python3.10/site-packages/mistral_common/experimental/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..636b7e0a8a459dd1fed06252cdde84e8deb279f4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/experimental/utils.py @@ -0,0 +1,48 @@ +from typing import List, Tuple + +from mistral_common.tokens.tokenizers.base import Tokenizer + + +def _split_integer_list_by_value(list_: List[int], value: int) -> Tuple[List[int], ...]: + r"""Split a list of integers by a given value. + + Args: + list_: The list to split. + value: The value to split the list by. + + Returns: + A tuple of lists of integers. + + Examples: + >>> _split_integer_list_by_value([1, 2, 3, 4, 5], 3) + ([1, 2], [3, 4, 5]) + >>> _split_integer_list_by_value([1, 2, 3, 4, 5], 6) + ([1, 2, 3, 4, 5],) + >>> _split_integer_list_by_value([1, 2, 3, 4, 5], 1) + ([1, 2, 3, 4, 5],) + >>> _split_integer_list_by_value([1, 2, 3, 4, 5, 3, 5, 6, 7], 3) + ([1, 2], [3, 4, 5], [3, 5, 6, 7]) + """ + result = [list_[0]] + for i, item in enumerate(list_[1:]): + if item == value: + return (result, *_split_integer_list_by_value(list_[1 + i :], value)) + result.append(item) + return (result,) + + +def _split_tokens_by_one_occurence_control_token( + list_: List[int], tokenizer: Tokenizer, control_token: str +) -> Tuple[List[int], List[int]]: + r"""Split a list of integers by a given control token. + + Raises: + ValueError: If the control token is not found in the list or if it is found more than once. + """ + control_token_id = tokenizer.get_control_token(control_token) + first, *rest = _split_integer_list_by_value(list_, control_token_id) + if len(rest) == 0: + raise ValueError(f"Control token {control_token} not found in the list of tokens.") + if len(rest) > 1: + raise ValueError(f"Control token {control_token} found more than once in the list of tokens.") + return first, rest[0] diff --git a/venv/lib/python3.10/site-packages/mistral_common/image.py b/venv/lib/python3.10/site-packages/mistral_common/image.py new file mode 100644 index 0000000000000000000000000000000000000000..52c31d56eb2d1ba7d85dc75eaf37226c7540ba10 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/image.py @@ -0,0 +1,100 @@ +import base64 +import io +from typing import Union + +import requests +from PIL import Image +from pydantic import BeforeValidator, PlainSerializer, SerializationInfo +from typing_extensions import Annotated + +from mistral_common import __version__ + + +def download_image(url: str) -> Image.Image: + r"""Download an image from a URL and return it as a PIL Image. + + Args: + url: The URL of the image to download. + + Returns: + The downloaded image as a PIL Image object. + """ + headers = {"User-Agent": f"mistral-common/{__version__}"} + try: + # Make a request to download the image + response = requests.get(url, headers=headers) + response.raise_for_status() # Raise an error for bad responses (4xx, 5xx) + + # Convert the image content to a PIL Image + img = Image.open(io.BytesIO(response.content)) + return img + + except requests.exceptions.RequestException as e: + raise RuntimeError(f"Error downloading the image from {url}: {e}.") + except Exception as e: + raise RuntimeError(f"Error converting to PIL image: {e}") + + +def maybe_load_image_from_str_or_bytes(x: Union[Image.Image, str, bytes]) -> Image.Image: + r"""Load an image from a string or bytes. + + If the input is already a PIL Image, return it as is. + + Args: + x: The input to load the image from. Can be a PIL Image, a string, or bytes. + If it's a string, it's assumed to be a base64 encoded string of bytes. + + Returns: + The loaded image as a PIL Image object. + """ + if isinstance(x, Image.Image): + return x + if isinstance(x, bytes): + try: + return Image.open(io.BytesIO(x)) + except Exception: + raise RuntimeError("Encountered an error when loading image from bytes.") + + try: + image = Image.open(io.BytesIO(base64.b64decode(x.encode("ascii")))) + return image + except Exception as e: + raise RuntimeError( + f"Encountered an error when loading image from bytes starting " + f"with '{x[:20]}'. Expected either a PIL.Image.Image or a base64 " + f"encoded string of bytes." + ) from e + + +def serialize_image_to_byte_str(im: Image.Image, info: SerializationInfo) -> str: + r"""Serialize an image to a base64 encoded string of bytes. + + Args: + im: The image to serialize. + info: The serialization info. + + Returns: + The serialized image as a base64 encoded string of bytes. + """ + if hasattr(info, "context"): + context = info.context or {} + else: + context = {} + + stream = io.BytesIO() + im_format = im.format or "PNG" + im.save(stream, format=im_format) + im_b64 = base64.b64encode(stream.getvalue()).decode("ascii") + if context and (max_image_b64_len := context.get("max_image_b64_len")): + return im_b64[:max_image_b64_len] + "..." + if context and context.get("add_format_prefix"): + im_b64 = f"data:image/{im_format.lower()};base64," + im_b64 + return im_b64 + + +SerializableImage = Annotated[ + Image.Image, + BeforeValidator(maybe_load_image_from_str_or_bytes), + PlainSerializer(serialize_image_to_byte_str), + "A normal PIL image that supports serialization to b64 bytes string.", +] diff --git a/venv/lib/python3.10/site-packages/mistral_common/multimodal.py b/venv/lib/python3.10/site-packages/mistral_common/multimodal.py new file mode 100644 index 0000000000000000000000000000000000000000..c697315c763d066c8d3089708ea70309ffaa2adc --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/multimodal.py @@ -0,0 +1,3 @@ +# This file is deprecated. TODO(Patrick) - as soon as vllm & transformers have adapted +# to new naming, throw deprecation warning and remove this file. +from mistral_common.image import * # noqa: F403 diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/__init__.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fbdaf2316343fcb132310c97c2c8d6c5373d49a Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/base.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7d643249aba375539c4dca84e98c74b27da6143 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..804662057ca459532a018bf93e27f3fb412500bc Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/base.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/base.py new file mode 100644 index 0000000000000000000000000000000000000000..04fbd0f76c99566dd7a6b8e26400e1825fe47fda --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/base.py @@ -0,0 +1,42 @@ +from typing import Optional + +from pydantic import Field + +from mistral_common.base import MistralBase + + +class UsageInfo(MistralBase): + r"""Usage statistics for a completion request. + + Attributes: + prompt_tokens: Number of tokens in the prompt. + completion_tokens: Number of tokens in the generated completion. + total_tokens: Total number of tokens used in the request (prompt + completion). + + Examples: + >>> info = UsageInfo(prompt_tokens=10, completion_tokens=20, total_tokens=30) + """ + + prompt_tokens: int = 0 + completion_tokens: Optional[int] = 0 + total_tokens: int = 0 + + +class BaseCompletionRequest(MistralBase): + """Base class for completion requests. + + Attributes: + temperature: Sampling temperature to use, between 0 and 1. Higher values like 0.8 will make the output more + random, while lower values like 0.2 will make it more focused and deterministic. + top_p: Nucleus sampling parameter, top-p probability mass, between 0 and 1. + max_tokens: Maximum number of tokens to generate. + random_seed: Random seed for reproducibility. + + Examples: + >>> request = BaseCompletionRequest(temperature=0.7, top_p=0.9, max_tokens=100, random_seed=42) + """ + + temperature: float = Field(default=0.7, ge=0.0, le=1.0) + top_p: float = Field(default=1.0, ge=0.0, le=1.0) + max_tokens: Optional[int] = Field(default=None, ge=0) + random_seed: Optional[int] = Field(default=None, ge=0) diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__init__.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da93823a88227949cf7f73f79c9febc0821bd0f4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/request.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/request.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e43866f350c8c2fd38ff01ee47d7ae6a7b8add4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/request.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/response.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/response.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0293125395a04ed751c5a5d3a2ab0896bc23d68f Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/__pycache__/response.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/request.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/request.py new file mode 100644 index 0000000000000000000000000000000000000000..7c9396efb927c75a0e8df719949a1451cabe632e --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/request.py @@ -0,0 +1,24 @@ +from typing import List, Optional, Union + +from pydantic import Field + +from mistral_common.base import MistralBase + + +class EmbeddingRequest(MistralBase): + r""" "Embedding request model used to generate embeddings for the given input. + + See [EmbeddingResponse][mistral_common.protocol.embedding.response.EmbeddingResponse] for the response model. + + Attributes: + input: Text to embed. + model: ID of the model to use. + encoding_format: The format to return the embeddings in. + + Examples: + >>> request = EmbeddingRequest(input="Hello world!", model="mistral-embed") + """ + + input: Union[str, List[str]] = Field(description="Text to embed.") + model: str = Field(description="ID of the model to use.") + encoding_format: Optional[str] = Field(default="float", description="The format to return the embeddings in.") diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/response.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/response.py new file mode 100644 index 0000000000000000000000000000000000000000..fece310b8877a0c2222df84f143363a5f1df694c --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/embedding/response.py @@ -0,0 +1,56 @@ +from typing import List + +from pydantic import Field + +from mistral_common.base import MistralBase +from mistral_common.protocol.base import UsageInfo +from mistral_common.protocol.utils import random_uuid + + +class EmbeddingObject(MistralBase): + r"""Embedding object returned by the API. + + Attributes: + object: The type of the object returned. + embedding: The embedding vector. + index: The index of the embedding in the input text. + + Examples: + >>> embedding_object = EmbeddingObject( + ... object="embedding", + ... embedding=[0.1, 0.2, 0.3], + ... index=0 + ... ) + """ + + object: str = Field(default="embedding", description="The type of the object returned.") + embedding: List[float] = Field(description="The type of the object returned.") + index: int = Field(description="The index of the embedding in the input text.") + + +class EmbeddingResponse(MistralBase): + r""" "Embedding response returned by the API. + + See the [EmbeddingRequest][mistral_common.protocol.embedding.request.EmbeddingRequest] for the request body. + + Attributes: + id: The ID of the embedding. + object: The type of the object returned. + data: List of embeddings. + model: The model used to generate the embeddings. + + Examples: + >>> response = EmbeddingResponse( + ... id="embd-123", + ... object="list", + ... data=[], + ... model="text-embedding-ada-002", + ... usage=UsageInfo(prompt_tokens=1, total_tokens=1, completion_tokens=0) + ... ) + """ + + id: str = Field(default_factory=lambda: f"embd-{random_uuid()}") + object: str = Field(default="list", description="The type of the object returned.") + data: List[EmbeddingObject] = Field(description="List of embeddings.") + model: str = Field(description="The model used to generate the embeddings.") + usage: UsageInfo diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/fim/__init__.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/fim/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/fim/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/fim/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f3dd009ac1f601c151d34c7865a7b18f2879d76 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/fim/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/fim/__pycache__/request.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/fim/__pycache__/request.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07bf86b83cec78451605d2993c2ecbde25f5fb87 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/fim/__pycache__/request.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/fim/request.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/fim/request.py new file mode 100644 index 0000000000000000000000000000000000000000..70e19597801a87e360bcd50ea7f842c778043c2c --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/fim/request.py @@ -0,0 +1,18 @@ +from typing import Optional + +from mistral_common.protocol.base import BaseCompletionRequest + + +class FIMRequest(BaseCompletionRequest): + r"""A valid Fill in the Middle completion request to be tokenized. + + Attributes: + prompt: The prompt to be completed. + suffix: The suffix of the prompt. If provided, the model will generate text between the prompt and the suffix. + + Examples: + >>> request = FIMRequest(prompt="Hello, my name is", suffix=" and I live in New York.") + """ + + prompt: str + suffix: Optional[str] = None diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__init__.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..815679db8e2658884083ecc7bfa27c808343de40 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/converters.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/converters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..442e9ed79a7908d5368d5fa798b62189d36bb682 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/converters.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/messages.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/messages.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8db4868db45b93bd89e2a8d0153e046155d69564 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/messages.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/normalize.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/normalize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99265758626c758c16299a39a44b492cea9c17e2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/normalize.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/request.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/request.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d54ca131b01db46534dff47ace4e890eaac0ab3e Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/request.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/response.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/response.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cc0e2c159725039af214cd1cc4069c5ce4601d9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/response.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/tool_calls.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/tool_calls.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fc004c73985d9c75b3b7d444a83e1bd55e83c5f Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/tool_calls.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/validator.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/validator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90bb1fb155c72b6db44e24072a5a3b131e4e5c42 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/__pycache__/validator.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/converters.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/converters.py new file mode 100644 index 0000000000000000000000000000000000000000..5e88a10d724490f50120eae7e65a60f72867ed1a --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/converters.py @@ -0,0 +1,132 @@ +from typing import Any, Dict, List, Set, Union + +from mistral_common.protocol.instruct.messages import ( + AssistantMessage, + ChatMessage, + SystemMessage, + ToolMessage, + UserMessage, +) +from mistral_common.protocol.instruct.tool_calls import Tool + + +def convert_openai_messages( + messages: List[Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]], +) -> List[ChatMessage]: + r"""Convert OpenAI messages to Mistral messages. + + Args: + messages: The OpenAI messages to convert. + + Returns: + The Mistral messages. + """ + converted_messages: List[ChatMessage] = [] + for openai_message in messages: + message_role = openai_message.get("role") + message: ChatMessage + if message_role == "user": + message = UserMessage.from_openai(openai_message) + elif message_role == "assistant": + message = AssistantMessage.from_openai(openai_message) + elif message_role == "tool": + message = ToolMessage.from_openai(openai_message) + elif message_role == "system": + message = SystemMessage.from_openai(openai_message) + else: + raise ValueError(f"Unknown message role: {message_role}") + converted_messages.append(message) + return converted_messages + + +def convert_openai_tools( + tools: List[Dict[str, Any]], +) -> List[Tool]: + r"""Convert OpenAI tools to Mistral tools. + + Args: + tools: The OpenAI tools to convert. + + Returns: + The Mistral tools. + """ + converted_tools = [Tool.from_openai(openai_tool) for openai_tool in tools] + return converted_tools + + +def _check_openai_fields_names(valid_fields_names: Set[str], names: Set[str]) -> None: + r"""Check if the names are valid field names. + + Names are valid if they are inside the `valid_fields_names` set or chat completion OpenAI fields. If the names are + not valid field names, raise a ValueError. + + The error message will contain the invalid field names sorted by if they are openAI valid field names or not. + + Args: + valid_fields_names: The valid field names. + names: The names to check. + + Raises: + ValueError: If the names are not valid field names. + """ + + openai_valid_params = set() + non_valid_params = set() + + for name in names: + if name in valid_fields_names: + continue + elif name in _OPENAI_COMPLETION_FIELDS: + openai_valid_params.add(name) + else: + non_valid_params.add(name) + + if openai_valid_params or non_valid_params: + raise ValueError( + "Invalid parameters passed to `ChatCompletionRequest.from_openai`:\n" + f"OpenAI valid parameters but not in `ChatCompletionRequest`: {openai_valid_params}\n" + f"Non valid parameters: {non_valid_params}" + ) + + +def _is_openai_field_name(name: str) -> bool: + return name in _OPENAI_COMPLETION_FIELDS + + +_OPENAI_COMPLETION_FIELDS: Set[str] = { + "messages", + "model", + "audio", + "frequency_penalty", + "function_call", + "functions", + "logit_bias", + "logprobs", + "max_completion_tokens", + "max_tokens", + "metadata", + "modalities", + "n", + "parallel_tool_calls", + "prediction", + "presence_penalty", + "reasoning_effort", + "response_format", + "seed", + "service_tier", + "stop", + "store", + "stream", + "stream_options", + "temperature", + "tool_choice", + "tools", + "top_logprobs", + "top_p", + "user", + "web_search_options", + "extra_headers", + "extra_query", + "extra_body", + "timeout", +} diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/messages.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..e780cbdd362d96e5b66dac3830672cdd7c95b30f --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/messages.py @@ -0,0 +1,658 @@ +import re +from enum import Enum +from pathlib import Path +from typing import Any, Dict, List, Literal, Optional, TypeVar, Union +from urllib.parse import urlparse + +from pydantic import ConfigDict, Field, ValidationError, field_validator +from typing_extensions import Annotated, TypeAlias + +from mistral_common.audio import EXPECTED_FORMAT_VALUES, Audio +from mistral_common.base import MistralBase +from mistral_common.image import SerializableImage +from mistral_common.protocol.instruct.tool_calls import ToolCall + + +class ChunkTypes(str, Enum): + r"""Enum for the types of chunks that can be sent to the model. + + Attributes: + text: A text chunk. + image: An image chunk. + image_url: An image url chunk. + input_audio: An input audio chunk. + audio_url: An audio url chunk. + + Examples: + >>> from mistral_common.protocol.instruct.messages import ChunkTypes + >>> chunk_type = ChunkTypes.text + """ + + text = "text" + image = "image" + image_url = "image_url" + input_audio = "input_audio" + audio_url = "audio_url" + thinking = "thinking" + + +class BaseContentChunk(MistralBase): + r"""Base class for all content chunks. + + Content chunks are used to send different types of content to the model. + + Attributes: + type: The type of the chunk. + """ + + type: Literal[ + ChunkTypes.text, + ChunkTypes.image, + ChunkTypes.image_url, + ChunkTypes.input_audio, + ChunkTypes.audio_url, + ChunkTypes.thinking, + ] + + def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]: + r"""Converts the chunk to the OpenAI format. + + Should be implemented by subclasses. + """ + raise NotImplementedError(f"to_openai method not implemented for {type(self).__name__}") + + @classmethod + def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "BaseContentChunk": + r"""Converts the OpenAI chunk to the Mistral format. + + Should be implemented by subclasses. + """ + raise NotImplementedError(f"from_openai method not implemented for {cls.__name__}") + + +class ImageChunk(BaseContentChunk): + r"""Image chunk. + + Attributes: + image: The image to be sent to the model. + + Examples: + >>> from PIL import Image + >>> image_chunk = ImageChunk(image=Image.new('RGB', (200, 200), color='blue')) + """ + + type: Literal[ChunkTypes.image] = ChunkTypes.image + image: SerializableImage + model_config = ConfigDict(arbitrary_types_allowed=True) + + def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]: + r"""Converts the chunk to the OpenAI format.""" + base64_image = self.model_dump(include={"image"}, context={"add_format_prefix": True})["image"] + return {"type": "image_url", "image_url": {"url": base64_image}} + + @classmethod + def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "ImageChunk": + r"""Converts the OpenAI chunk to the Mistral format.""" + assert openai_chunk.get("type") == "image_url", openai_chunk + + image_url_dict = openai_chunk["image_url"] + assert isinstance(image_url_dict, dict) and "url" in image_url_dict, image_url_dict + + if re.match(r"^data:image/\w+;base64,", image_url_dict["url"]): # Remove the prefix if it exists + image_url_dict["url"] = image_url_dict["url"].split(",")[1] + + return cls.model_validate({"image": image_url_dict["url"]}) + + +class ImageURL(MistralBase): + r"""Image URL or a base64 encoded image. + + Attributes: + url: The URL of the image. + detail: The detail of the image. + + Examples: + >>> image_url = ImageURL(url="https://example.com/image.png") + """ + + url: str + detail: Optional[str] = None + + +class ImageURLChunk(BaseContentChunk): + r"""Image URL chunk. + + Attributes: + image_url: The URL of the image or a base64 encoded image to be sent to the model. + + Examples: + >>> image_url_chunk = ImageURLChunk(image_url="data:image/png;base64,iVBORw0") + """ + + type: Literal[ChunkTypes.image_url] = ChunkTypes.image_url + image_url: Union[ImageURL, str] + + model_config = ConfigDict(arbitrary_types_allowed=True) + + def get_url(self) -> str: + if isinstance(self.image_url, ImageURL): + return self.image_url.url + return self.image_url + + def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]: + r"""Converts the chunk to the OpenAI format.""" + image_url_dict = {"url": self.get_url()} + if isinstance(self.image_url, ImageURL) and self.image_url.detail is not None: + image_url_dict["detail"] = self.image_url.detail + + out_dict: Dict[str, Union[str, Dict[str, str]]] = { + "type": "image_url", + "image_url": image_url_dict, + } + return out_dict + + @classmethod + def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "ImageURLChunk": + r"""Converts the OpenAI chunk to the Mistral format.""" + return cls.model_validate({"image_url": openai_chunk["image_url"]}) + + +class RawAudio(MistralBase): + r"""Base64 encoded audio data. + + This class represents raw audio data encoded in base64 format. + + Attributes: + data: The base64 encoded audio data, which can be a string or bytes. + format: The format of the audio data. + + Examples: + >>> audio = RawAudio(data="base64_encoded_audio_data", format="mp3") + """ + + data: Union[str, bytes] + format: str + + @classmethod + def from_audio(cls, audio: Audio) -> "RawAudio": + """Creates a RawAudio instance from an Audio object. + + Args: + audio: An Audio object containing audio data, format, and duration. + + Returns: + An AudioChunk instance initialized with the audio data. + """ + format = audio.format + data = audio.to_base64(format, False) + + return cls(data=data, format=format) + + @field_validator("format") + def should_not_be_empty(cls, v: str) -> str: + if v not in EXPECTED_FORMAT_VALUES: + raise ValidationError(f"`format` should be one of {EXPECTED_FORMAT_VALUES}. Got: {v}`") + + return v + + +class AudioURL(MistralBase): + r"""Audio URL. + + Attributes: + url: The URL of the audio file. + """ + + url: str + + +class AudioURLType(str, Enum): + r"""Enum for the types of audio URLs. + + Attributes: + url: A URL. + base64: A base64 encoded audio. Can be prefixed with `data:audio/;base64,`. + file: A file path. + file_uri: A file URI (eg. `file:///path/to/file`). + """ + + url = "url" + base64 = "base64" + file = "file" + file_uri = "file_uri" + + +class AudioURLChunk(BaseContentChunk): + r"""Audio URL chunk. + + Attributes: + type: The type of the chunk, which is always `ChunkTypes.audio_url`. + audio_url: The URL of the audio file. + """ + + type: Literal[ChunkTypes.audio_url] = ChunkTypes.audio_url + audio_url: Union[str, AudioURL] + + @property + def url(self) -> str: + if isinstance(self.audio_url, AudioURL): + return self.audio_url.url + return self.audio_url + + def get_url_type(self) -> AudioURLType: + r"""Returns the type of the audio URL. + + Note: + URLs should be either: + - a valid URL (http:// or https://) + - a valid file path (e.g. /path/to/file) + - a valid file URI (e.g. file:///path/to/file) + - a base64 encoded audio. It is assumed to be base64 encoded if it is not a valid URL or file path. + + Returns: + The type of the audio URL. + """ + url_scheme = urlparse(self.url).scheme + if url_scheme in {"http", "https"}: + return AudioURLType.url + elif url_scheme == "data": + return AudioURLType.base64 + elif url_scheme == "file": + return AudioURLType.file_uri + + try: + url_path = Path(self.url) + exist_path = url_path.exists() + except OSError: # File name too long + exist_path = False + + if exist_path: + return AudioURLType.file + + return AudioURLType.base64 + + def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]: + r"""Converts the chunk to the OpenAI format.""" + if isinstance(self.audio_url, AudioURL): + return self.model_dump() + else: + return {"type": self.type, "audio_url": {"url": self.audio_url}} + + @classmethod + def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "AudioURLChunk": + r"""Converts the OpenAI chunk to the Mistral format.""" + return cls.model_validate(openai_chunk) + + +class AudioChunk(BaseContentChunk): + r"""Audio chunk containing raw audio data. + + This class represents a chunk of audio data that can be used as input. + + Attributes: + type: The type of the chunk, which is always ChunkTypes.input_audio. + input_audio: The RawAudio object containing the audio data. + + Examples: + >>> audio_chunk = AudioChunk(input_audio=RawAudio(data="base64_encoded_audio_data", format="mp3")) + """ + + type: Literal[ChunkTypes.input_audio] = ChunkTypes.input_audio + input_audio: RawAudio + + @field_validator("input_audio") + def should_not_be_empty(cls, v: RawAudio) -> RawAudio: + if not v.data.strip(): + raise ValidationError(f"`InputAudio` should not be empty. Got: {v}`") + + return v + + @classmethod + def from_audio(cls, audio: Audio) -> "AudioChunk": + r"""Creates an AudioChunk instance from an Audio object. + + Args: + audio: An Audio object containing audio data. + + Returns: + An AudioChunk instance initialized with the audio data. + """ + return cls(input_audio=RawAudio.from_audio(audio)) + + def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]: + r"""Converts the chunk to the OpenAI format. + + Returns: + A dictionary representing the audio chunk in the OpenAI format. + """ + content = ( + self.input_audio.data.decode("utf-8") if isinstance(self.input_audio.data, bytes) else self.input_audio.data + ) + return { + "type": self.type, + "input_audio": RawAudio(data=content, format=self.input_audio.format).model_dump(), + } + + @classmethod + def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "AudioChunk": + r"""Converts the OpenAI chunk to the Mistral format. + + Args: + openai_chunk: A dictionary representing the audio chunk in the OpenAI format. + + Returns: + An AudioChunk instance initialized with the data from the OpenAI chunk. + """ + return cls.model_validate(openai_chunk) + + +class TextChunk(BaseContentChunk): + r"""Text chunk. + + Attributes: + text: The text to be sent to the model. + + Examples: + >>> text_chunk = TextChunk(text="Hello, how can I help you?") + """ + + type: Literal[ChunkTypes.text] = ChunkTypes.text + text: str + + def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]: + r"""Converts the chunk to the OpenAI format.""" + return self.model_dump() + + @classmethod + def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "TextChunk": + r"""Converts the OpenAI chunk to the Mistral format.""" + return cls.model_validate(openai_chunk) + + +class ThinkChunk(BaseContentChunk): + r"""Thinking chunk. + + Attributes: + type: The type of the chunk, which is always ChunkTypes.thinking. + thinking: The list of text chunks of the thinking. + closed: Whether the thinking chunk is closed or not. + """ + + type: Literal[ChunkTypes.thinking] = ChunkTypes.thinking + thinking: str + closed: bool = Field(default=True, description="Whether the thinking chunk is closed or not.") + + def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]: + r"""Converts the chunk to the OpenAI format.""" + return self.model_dump() + + @classmethod + def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "ThinkChunk": + r"""Converts the OpenAI chunk to the Mistral format.""" + return cls.model_validate(openai_chunk) + + +ContentChunk = Annotated[ + Union[TextChunk, ImageChunk, ImageURLChunk, AudioChunk, AudioURLChunk, ThinkChunk], Field(discriminator="type") +] +UserContentChunk = Annotated[ + Union[TextChunk, ImageChunk, ImageURLChunk, AudioChunk, AudioURLChunk], Field(discriminator="type") +] + + +def _convert_openai_content_chunks(openai_content_chunks: Dict[str, Union[str, Dict[str, str]]]) -> ContentChunk: + content_type_str = openai_content_chunks.get("type") + + if content_type_str is None: + raise ValueError("Content chunk must have a type field.") + + content_type = ChunkTypes(content_type_str) + + if content_type == ChunkTypes.text: + return TextChunk.from_openai(openai_content_chunks) + elif content_type == ChunkTypes.image_url: + return ImageURLChunk.from_openai(openai_content_chunks) + elif content_type == ChunkTypes.image: + return ImageChunk.from_openai(openai_content_chunks) + elif content_type == ChunkTypes.input_audio: + return AudioChunk.from_openai(openai_content_chunks) + elif content_type == ChunkTypes.audio_url: + return AudioURLChunk.from_openai(openai_content_chunks) + elif content_type == ChunkTypes.thinking: + return ThinkChunk.from_openai(openai_content_chunks) + else: + raise ValueError(f"Unknown content chunk type: {content_type}") + + +class Roles(str, Enum): + r"""Enum for the roles of the messages. + + Attributes: + system: The system role. + user: The user role. + assistant: The assistant role. + tool: The tool role. + + Examples: + >>> role = Roles.user + """ + + system = "system" + user = "user" + assistant = "assistant" + tool = "tool" + + +class BaseMessage(MistralBase): + r"""Base class for all messages. + + Attributes: + role: The role of the message. + """ + + role: Literal[Roles.system, Roles.user, Roles.assistant, Roles.tool] + + def to_openai(self) -> Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]: + r"""Converts the message to the OpenAI format. + + Should be implemented by subclasses. + """ + raise NotImplementedError(f"to_openai method not implemented for {type(self).__name__}") + + @classmethod + def from_openai( + cls, openai_message: Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]] + ) -> "BaseMessage": + r"""Converts the OpenAI message to the Mistral format. + + Should be implemented by subclasses. + """ + raise NotImplementedError(f"from_openai method not implemented for {cls.__name__}.") + + +class UserMessage(BaseMessage): + r"""User message. + + Attributes: + content: The content of the message. + + Examples: + >>> message = UserMessage(content="Can you help me to write a poem?") + """ + + role: Literal[Roles.user] = Roles.user + content: Union[str, List[UserContentChunk]] + + def to_openai(self) -> Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]: + r"""Converts the message to the OpenAI format.""" + if isinstance(self.content, str): + return {"role": self.role, "content": self.content} + return {"role": self.role, "content": [chunk.to_openai() for chunk in self.content]} + + @classmethod + def from_openai( + cls, openai_message: Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]] + ) -> "UserMessage": + r"""Converts the OpenAI message to the Mistral format.""" + if isinstance(openai_message["content"], str): + return cls.model_validate(openai_message) + return cls.model_validate( + { + "role": openai_message["role"], + "content": [_convert_openai_content_chunks(chunk) for chunk in openai_message["content"]], + }, + ) + + +class SystemMessage(BaseMessage): + r"""System message. + + Attributes: + content: The content of the message. + + Examples: + >>> message = SystemMessage(content="You are a helpful assistant.") + """ + + role: Literal[Roles.system] = Roles.system + content: Union[str, List[Union[TextChunk, ThinkChunk]]] + + def to_openai(self) -> Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]: + r"""Converts the message to the OpenAI format.""" + return self.model_dump() + + @classmethod + def from_openai( + cls, openai_message: Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]] + ) -> "SystemMessage": + r"""Converts the OpenAI message to the Mistral format.""" + return cls.model_validate(openai_message) + + +class AssistantMessage(BaseMessage): + r"""Assistant message. + + Attributes: + role: The role of the message. + content: The content of the message. + tool_calls: The tool calls of the message. + prefix: Whether the message is a prefix. + + Examples: + >>> message = AssistantMessage(content="Hello, how can I help you?") + """ + + role: Literal[Roles.assistant] = Roles.assistant + content: Optional[Union[str, List[Union[TextChunk, ThinkChunk]]]] = None + tool_calls: Optional[List[ToolCall]] = None + prefix: bool = False + + def to_openai(self) -> Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]: + r"""Converts the message to the OpenAI format.""" + out_dict: dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]] = { + "role": self.role, + } + if self.content is None: + pass + elif isinstance(self.content, str): + out_dict["content"] = self.content + else: + out_dict["content"] = [chunk.to_openai() for chunk in self.content] + if self.tool_calls is not None: + out_dict["tool_calls"] = [tool_call.to_openai() for tool_call in self.tool_calls] + + return out_dict + + @classmethod + def from_openai( + cls, openai_message: Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]] + ) -> "AssistantMessage": + r"""Converts the OpenAI message to the Mistral format.""" + openai_tool_calls = openai_message.get("tool_calls", None) + tools_calls = ( + [ + ToolCall.from_openai(openai_tool_call) # type: ignore[arg-type] + for openai_tool_call in openai_tool_calls + ] + if openai_tool_calls is not None + else None + ) + openai_content = openai_message.get("content", None) + content: Optional[Union[str, List[ContentChunk]]] = None + if openai_content is None or isinstance(openai_content, str): + content = openai_content + elif isinstance(openai_content, list): + content = [_convert_openai_content_chunks(chunk) for chunk in openai_content] + else: + raise ValueError(f"Unknown content type: {type(openai_content)}") + + return cls.model_validate( + { + "role": openai_message["role"], + "content": content, + "tool_calls": tools_calls, + } + ) + + +class FinetuningAssistantMessage(AssistantMessage): + r"""Assistant message for finetuning. + + Attributes: + weight: The weight of the message to train on. + + Examples: + >>> message = FinetuningAssistantMessage(content="Hello, how can I help you?", weight=0.5) + """ + + weight: Optional[float] = None + + +class ToolMessage(BaseMessage): + r"""Tool message. + + Attributes: + content: The content of the message. + tool_call_id: The tool call id of the message. + name: The name of the tool. (Deprecated in V3 tokenization) + + Examples: + >>> message = ToolMessage(content="Hello, how can I help you?", tool_call_id="123") + """ + + content: str + role: Literal[Roles.tool] = Roles.tool + tool_call_id: Optional[str] = None + + # Deprecated in V3 tokenization + name: Optional[str] = None + + def to_openai(self) -> Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]: + r"""Converts the message to the OpenAI format.""" + assert self.tool_call_id is not None, "tool_call_id must be provided for tool messages." + return self.model_dump(exclude={"name"}) + + @classmethod + def from_openai(cls, messages: Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]) -> "ToolMessage": + r"""Converts the OpenAI message to the Mistral format.""" + tool_message = cls.model_validate(messages) + assert tool_message.tool_call_id is not None, "tool_call_id must be provided for tool messages." + return tool_message + + +ChatMessage = Annotated[Union[SystemMessage, UserMessage, AssistantMessage, ToolMessage], Field(discriminator="role")] + +FinetuningMessage = Annotated[ + Union[SystemMessage, UserMessage, FinetuningAssistantMessage, ToolMessage], + Field(discriminator="role"), +] + +ChatMessageType = TypeVar("ChatMessageType", bound=ChatMessage) + +# Used for type hinting in generic classes where we might override the message types +UserMessageType = TypeVar("UserMessageType", bound=UserMessage) +AssistantMessageType = TypeVar("AssistantMessageType", bound=AssistantMessage) +ToolMessageType = TypeVar("ToolMessageType", bound=ToolMessage) +SystemMessageType = TypeVar("SystemMessageType", bound=SystemMessage) + +UATS: TypeAlias = Union[UserMessageType, AssistantMessageType, ToolMessageType, SystemMessageType] diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/normalize.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..4cb6f38a0f965b6318c089fdf49c830dde45e383 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/normalize.py @@ -0,0 +1,456 @@ +import json +from typing import Generic, List, Optional, Sequence, Type, Union, overload + +from mistral_common.protocol.instruct.messages import ( + UATS, + AssistantMessage, + AssistantMessageType, + FinetuningAssistantMessage, + Roles, + SystemMessage, + SystemMessageType, + TextChunk, + ThinkChunk, + ToolMessage, + ToolMessageType, + UserContentChunk, + UserMessage, + UserMessageType, +) +from mistral_common.protocol.instruct.request import ChatCompletionRequest, InstructRequest +from mistral_common.protocol.instruct.tool_calls import FunctionCall, Tool, ToolCall +from mistral_common.tokens.tokenizers.base import InstructRequestType, TokenizerVersion + +CHUNK_JOIN_STR = "\n\n" + + +class InstructRequestNormalizer( + Generic[UserMessageType, AssistantMessageType, ToolMessageType, SystemMessageType, InstructRequestType] +): + r"""Takes a [ChatCompletionRequest][mistral_common.protocol.instruct.request.ChatCompletionRequest] and normalizes + it into an [InstructRequest][mistral_common.tokens.instruct.request.InstructRequest]. + + The normalization process does several things such as: + - Aggregate consecutive messages of the same role + - Aggregate system prompts + - Normalize json content + - Normalize tool calls + + Examples: + >>> normalizer = InstructRequestNormalizer.normalizer() + """ + + _system_prompt_in_begin: bool = False + _allow_tool_call_and_content: bool = False + + def __init__( + self, + user_message_class: Type[UserMessageType], + assistant_message_class: Type[AssistantMessageType], + tool_message_class: Type[ToolMessageType], + system_message_class: Type[SystemMessageType], + instruct_request_class: Type[InstructRequestType], + ): + r"""Initializes the normalizer with the appropriate message classes. + + Args: + user_message_class: The class for user messages. + assistant_message_class: The class for assistant messages. + tool_message_class: The class for tool messages. + system_message_class: The class for system messages. + instruct_request_class: The class for instruct requests. + """ + self._user_message_class = user_message_class + self._assistant_message_class = assistant_message_class + self._tool_message_class = tool_message_class + self._instruct_request_class = instruct_request_class + # this is unused but makes creation nicer + self._system_message_class = system_message_class + + @staticmethod + def normalizer() -> "InstructRequestNormalizer": + r"""Returns a normalizer for the default instruct request. + + Examples: + >>> normalizer = InstructRequestNormalizer.normalizer() + """ + return InstructRequestNormalizer( + UserMessage, + AssistantMessage, + ToolMessage, + SystemMessage, + InstructRequest[UATS, Tool], + ) + + def _normalize_json_content(self, content: Optional[str]) -> str: + if content is None or len(content) == 0: + return "{}" + + try: + parsed_json = json.loads(content) + normalized_content = json.dumps(parsed_json, ensure_ascii=False) + except json.JSONDecodeError: + normalized_content = content + return normalized_content + + @overload + def _aggregate_content_chunks( + self, content: List[Union[str, TextChunk, ThinkChunk]] + ) -> Union[str, List[Union[TextChunk, ThinkChunk]]]: ... + @overload + def _aggregate_content_chunks(self, content: str) -> str: ... + @overload + def _aggregate_content_chunks(self, content: List[str]) -> str: ... + def _aggregate_content_chunks( + self, content: Union[str, List[Union[str, TextChunk, ThinkChunk]], List[str]] + ) -> Union[str, List[Union[TextChunk, ThinkChunk]]]: + if isinstance(content, str): + return content + + assert isinstance(content, list), f"Expected list, got {type(content)}" + + aggregated_content: List[Union[TextChunk, ThinkChunk]] = [] + for chunk in content: + if isinstance(chunk, str): + chunk = TextChunk(text=chunk) + + if isinstance(chunk, TextChunk): + # TODO(Julien): Add a check for previous text chunks especially if one is open in validator.py + if aggregated_content and isinstance(aggregated_content[-1], TextChunk): + aggregated_content[-1].text += CHUNK_JOIN_STR + chunk.text + else: + aggregated_content.append(chunk) + elif isinstance(chunk, ThinkChunk): + aggregated_content.append(chunk) + else: + raise ValueError(f"Unsupported chunk type {type(chunk)}") + + if len(aggregated_content) == 1 and isinstance(aggregated_content[0], TextChunk): + return aggregated_content[0].text + return aggregated_content + + def _aggregate_system_prompts(self, request: ChatCompletionRequest[UATS]) -> Optional[str]: + system_prompt: List[str] = [] + + for message in request.messages: + if message.role == Roles.system and message.content: + aggregated_content = self._aggregate_content_chunks(message.content) + system_prompt.append(aggregated_content) + + return "\n\n".join(system_prompt) if len(system_prompt) else None + + def _aggregate_tool_messages(self, messages: List[UATS], latest_call_ids: List[str]) -> List[ToolMessageType]: + r""" + We currently do not do any aggregation for tool messages, but we normalize the json content + """ + tool_messages: List[ToolMessageType] = [] + for message in messages: + assert isinstance(message, self._tool_message_class), "Expected tool message" + content = self._aggregate_content_chunks(message.content) + normalized_content = self._normalize_json_content(content) + tool_messages.append( + self._tool_message_class( + content=normalized_content, tool_call_id=message.tool_call_id, name=message.name + ) + ) + + return tool_messages + + def _normalize_tool_call(self, tool_call: ToolCall) -> ToolCall: + normalized_function_aruments = self._normalize_json_content(tool_call.function.arguments) + return ToolCall( + function=FunctionCall(name=tool_call.function.name, arguments=normalized_function_aruments), + id=tool_call.id, + ) + + def _aggregate_system_messages(self, messages: List[UATS]) -> List[SystemMessageType]: + return [] + + def _aggregate_assistant_messages(self, messages: List[UATS]) -> AssistantMessageType: + messages_contents: List[Union[str, TextChunk, ThinkChunk]] = [] + tool_calls: List[ToolCall] = [] + prefix: bool = False + weight: Optional[float] = None + + for message in messages: + assert isinstance(message, self._assistant_message_class), "Expected assistant message" + + if not self._allow_tool_call_and_content and (message.tool_calls and message.content): + raise ValueError(f"Tool calls and content cannot be used together in the same message. {message}") + + if message.tool_calls: + for tool_call in message.tool_calls: + normalized_tool_call = self._normalize_tool_call(tool_call) + tool_calls.append(normalized_tool_call) + + if (content := message.content) is not None: + messages_contents.extend([content] if isinstance(content, str) else content) + + prefix |= message.prefix + + if isinstance(message, FinetuningAssistantMessage): + # Only FinetuningAssistantMessage can be weighted + if weight is not None: + assert weight == message.weight, ( + "Expected weights of aggregated FinetuningAssistantMessage to be equal" + ) + weight = message.weight + + if messages_contents: + aggregated_content = self._aggregate_content_chunks(messages_contents) + else: + aggregated_content = None + + aggregated_message = self._assistant_message_class( + content=aggregated_content, + tool_calls=tool_calls or None, + prefix=prefix, + ) + + if weight is not None and hasattr(aggregated_message, "weight"): + aggregated_message.weight = weight + return aggregated_message + + def _aggregate_user_messages(self, messages: List[UATS]) -> UserMessageType: + """ + Just coalesce neighboring blocks of text + """ + all_content: List[UserContentChunk] = [] + text_chunks: List[str] = [] + for message in messages: + assert isinstance(message, self._user_message_class), f"Expected user message got {type(message)}" + if isinstance(message.content, str): + text_chunks.append(message.content) + else: # it's a List[ContentChunk] + for chunk in message.content: + if isinstance(chunk, TextChunk): + text_chunks.append(chunk.text) + else: + if text_chunks: + all_content.append(TextChunk(text="\n\n".join(text_chunks))) + text_chunks = [] + all_content.append(chunk) + + text_content = "\n\n".join(text_chunks) if text_chunks else "" + + if not all_content: + # if no ContentChunk was passed, we return content as a str + return self._user_message_class(content=text_content) + + if text_content: + # else we return a List of content chunks + all_content.append(TextChunk(text=text_content)) + + return self._user_message_class(content=all_content) + + def _aggregate_role( + self, messages: List[UATS], role: Optional[Roles], latest_call_ids: List[str] + ) -> Sequence[UATS]: + if role == Roles.tool: + return self._aggregate_tool_messages(messages, latest_call_ids) + elif role == Roles.assistant: + return [self._aggregate_assistant_messages(messages)] + elif role == Roles.user: + return [self._aggregate_user_messages(messages)] + else: # System messages are ignored + return self._aggregate_system_messages(messages) + + def _aggregate_messages(self, request: ChatCompletionRequest[UATS]) -> List[UATS]: + aggregated_messages: List[UATS] = [] + messages_to_aggregate: List[UATS] = [] + current_role: Optional[Roles] = None + current_weight: Optional[float] = None + latest_call_ids: List[str] = [] + + # Collect consecutive lists of messages with the same role and weight + for message in request.messages: + new_weight = getattr(message, "weight", None) + if current_role != message.role or (new_weight != current_weight): + aggregated_messages.extend(self._aggregate_role(messages_to_aggregate, current_role, latest_call_ids)) + + if current_role == Roles.assistant: + assistant_message = aggregated_messages[-1] + assert isinstance(aggregated_messages[-1], AssistantMessage) + if assistant_message.tool_calls is not None: + for tool_call in assistant_message.tool_calls: + latest_call_ids.append(tool_call.id) + + elif current_role == Roles.tool: + # reordering only depends on the latest aggregated assistant message + latest_call_ids.clear() + + messages_to_aggregate.clear() + current_weight = new_weight + current_role = message.role + messages_to_aggregate.append(message) + + # Add the last set of messages + aggregated_messages.extend(self._aggregate_role(messages_to_aggregate, current_role, latest_call_ids)) + + # If the first message is not a user message, or we didn't aggregate + # anything (all system messages) for example, add an empty user message + if len(aggregated_messages) == 0 or ( + not self._system_prompt_in_begin and aggregated_messages[0].role != Roles.user + ): + aggregated_messages.insert(0, self._user_message_class(content="")) + + return aggregated_messages + + def from_chat_completion_request(self, request: ChatCompletionRequest[UATS]) -> InstructRequestType: + r"""Converts a chat completion request to an instruct request. + + Args: + request: The chat completion request to convert. + + Returns: + The converted instruct request. + + Examples: + >>> from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage + >>> request = ChatCompletionRequest( + ... messages=[ + ... UserMessage(content="Hello"), + ... AssistantMessage(content="Hi"), + ... ], + ... ) + >>> normalizer = InstructRequestNormalizer.normalizer() + >>> instruct_request = normalizer.from_chat_completion_request(request) + """ + system_prompt = self._aggregate_system_prompts(request) + messages = self._aggregate_messages(request) + + return self._instruct_request_class( + messages=messages, + system_prompt=system_prompt, + available_tools=request.tools, + continue_final_message=request.continue_final_message, + ) + + +class InstructRequestNormalizerV7(InstructRequestNormalizer): + r"""Normalizer for the v7 tokenizer. + + Examples: + >>> normalizer = InstructRequestNormalizerV7.normalizer() + """ + + _system_prompt_in_begin: bool = True + _allow_tool_call_and_content: bool = True + + @staticmethod + def normalizer() -> "InstructRequestNormalizerV7": + r"""Returns a normalizer for the default instruct request + + Examples: + >>> normalizer = InstructRequestNormalizerV7.normalizer() + """ + return InstructRequestNormalizerV7( + UserMessage, + AssistantMessage, + ToolMessage, + SystemMessage, + InstructRequest[UATS, Tool], + ) + + def _aggregate_system_messages(self, messages: List[UATS]) -> List[SystemMessageType]: + return [ + self._system_message_class(content=self._aggregate_content_chunks(message.content)) + for message in messages + if isinstance(message, self._system_message_class) + ] + + def _aggregate_role( + self, messages: List[UATS], role: Optional[Roles], latest_call_ids: list[str] + ) -> Sequence[UATS]: + if role == Roles.tool: + return self._aggregate_tool_messages(messages, latest_call_ids) + elif role == Roles.assistant: + return [self._aggregate_assistant_messages(messages)] + elif role == Roles.user: + return [self._aggregate_user_messages(messages)] + elif role == Roles.system: + return self._aggregate_system_messages(messages) + else: + assert role is None and len(messages) == 0 + return [] + + def _aggregate_system_prompts(self, request: ChatCompletionRequest[UATS]) -> Optional[str]: + raise NotImplementedError("We should not aggregate system prompts") + + def from_chat_completion_request(self, request: ChatCompletionRequest[UATS]) -> InstructRequestType: # type: ignore[type-var] + r"""Converts a chat completion request to an instruct request. + + Args: + request: The chat completion request to convert. + + Returns: + The converted instruct request. + + Examples: + >>> from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage + >>> request = ChatCompletionRequest( + ... messages=[ + ... UserMessage(content="Hello"), + ... AssistantMessage(content="Hi"), + ... ], + ... ) + >>> normalizer = InstructRequestNormalizerV7.normalizer() + >>> instruct_request = normalizer.from_chat_completion_request(request) + """ + messages = self._aggregate_messages(request) + return self._instruct_request_class(messages=messages, system_prompt=None, available_tools=request.tools) # type: ignore[no-any-return] + + +class InstructRequestNormalizerV13(InstructRequestNormalizerV7): + r"""Normalizer for the v13 tokenizer. + + It reorders tool messages based on the tool call order. + + Examples: + >>> normalizer = InstructRequestNormalizerV13.normalizer() + """ + + @staticmethod + def normalizer() -> "InstructRequestNormalizerV13": + r"""Returns a normalizer for the default instruct request.""" + return InstructRequestNormalizerV13( + UserMessage, + AssistantMessage, + ToolMessage, + SystemMessage, + InstructRequest[UATS, Tool], + ) + + def _aggregate_tool_messages(self, messages: List[UATS], latest_call_ids: List[str]) -> List[ToolMessageType]: + tool_messages: List[ToolMessageType] = super()._aggregate_tool_messages(messages, latest_call_ids) + id_to_tool_call_idx = {call_id: idx for idx, call_id in enumerate(latest_call_ids)} + id_to_tool_result_idx = {message.tool_call_id: idx for idx, message in enumerate(tool_messages)} + # First order by tool call idx and then by tool result idx + tool_messages.sort( + key=lambda msg: ( + id_to_tool_call_idx.get(msg.tool_call_id or "null", float("inf")), + id_to_tool_result_idx[msg.tool_call_id], + ), + ) + return tool_messages + + +def normalizer_for_tokenizer_version(version: TokenizerVersion) -> InstructRequestNormalizer: + r"""Gets the appropriate normalizer for the given tokenizer version. + + Args: + version: The tokenizer version to get the normalizer for. + + Returns: + The appropriate normalizer for the given tokenizer version. + + Examples: + >>> normalizer = normalizer_for_tokenizer_version(TokenizerVersion.v1) + """ + if version in {TokenizerVersion.v1, TokenizerVersion.v2, TokenizerVersion.v3}: + return InstructRequestNormalizer.normalizer() + elif version in {TokenizerVersion.v7, TokenizerVersion.v11}: + return InstructRequestNormalizerV7.normalizer() + elif version == TokenizerVersion.v13: + return InstructRequestNormalizerV13.normalizer() + raise ValueError(f"Unknown tokenizer version {version}") diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/request.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/request.py new file mode 100644 index 0000000000000000000000000000000000000000..cbd3f5946ff2b565c40ed72e58f877a8ac3a94e0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/request.py @@ -0,0 +1,334 @@ +from enum import Enum +from typing import Any, Dict, Generic, List, Optional, Union + +from pydantic import Field + +from mistral_common.base import MistralBase +from mistral_common.protocol.base import BaseCompletionRequest +from mistral_common.protocol.instruct.converters import ( + _check_openai_fields_names, + _is_openai_field_name, + convert_openai_messages, + convert_openai_tools, +) +from mistral_common.protocol.instruct.messages import ( + ChatMessage, + ChatMessageType, +) +from mistral_common.protocol.instruct.tool_calls import Tool, ToolChoice, ToolType + + +class ResponseFormats(str, Enum): + r"""Enum of the different formats of an instruct response. + + Attributes: + text: The response is a plain text. + json: The response is a JSON object. + + Examples: + >>> response_format = ResponseFormats.text + """ + + text = "text" + json = "json_object" + + +class ResponseFormat(MistralBase): + r"""The format of the response. + + Attributes: + type: The type of the response. + + Examples: + >>> response_format = ResponseFormat(type=ResponseFormats.text) + """ + + type: ResponseFormats = ResponseFormats.text + + +class ChatCompletionRequest(BaseCompletionRequest, Generic[ChatMessageType]): + r"""Request for a chat completion. + + Attributes: + model: The model to use for the chat completion. + messages: The messages to use for the chat completion. + response_format: The format of the response. + tools: The tools to use for the chat completion. + tool_choice: The tool choice to use for the chat completion. + truncate_for_context_length: Whether to truncate the messages for the context length. + continue_final_message: Whether to continue the final message. + + Examples: + >>> from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage + >>> from mistral_common.protocol.instruct.tool_calls import ToolTypes, Function + >>> request = ChatCompletionRequest( + ... messages=[ + ... UserMessage(content="Hello!"), + ... AssistantMessage(content="Hi! How can I help you?"), + ... ], + ... response_format=ResponseFormat(type=ResponseFormats.text), + ... tools=[Tool(type=ToolTypes.function, function=Function(name="get_weather", parameters={}))], + ... tool_choice=ToolChoice.auto, + ... truncate_for_context_length=True, + ... ) + """ + + model: Optional[str] = None + messages: List[ChatMessageType] + response_format: ResponseFormat = Field(default_factory=ResponseFormat) + tools: Optional[List[Tool]] = None + tool_choice: ToolChoice = ToolChoice.auto + truncate_for_context_length: bool = False + continue_final_message: bool = False + + def to_openai(self, **kwargs: Any) -> Dict[str, List[Dict[str, Any]]]: + r"""Convert the request messages and tools into the OpenAI format. + + Args: + kwargs: Additional parameters to be added to the request. + + Returns: + The request in the OpenAI format. + + Examples: + >>> from mistral_common.protocol.instruct.messages import UserMessage + >>> from mistral_common.protocol.instruct.tool_calls import Tool, Function + >>> request = ChatCompletionRequest(messages=[UserMessage(content="Hello, how are you?")], temperature=0.15) + >>> request.to_openai(stream=True) + {'temperature': 0.15, 'top_p': 1.0, 'response_format': {'type': 'text'}, 'tool_choice': 'auto', 'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'stream': True} + >>> request = ChatCompletionRequest(messages=[UserMessage(content="Hello, how are you?")], tools=[ + ... Tool(function=Function( + ... name="get_current_weather", + ... description="Get the current weather in a given location", + ... parameters={ + ... "type": "object", + ... "properties": { + ... "location": { + ... "type": "string", + ... "description": "The city and state, e.g. San Francisco, CA", + ... }, + ... "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + ... }, + ... "required": ["location"], + ... }, + ... ), + ... )]) + >>> request.to_openai() + {'temperature': 0.7, 'top_p': 1.0, 'response_format': {'type': 'text'}, 'tool_choice': 'auto', 'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'tools': [{'type': 'function', 'function': {'name': 'get_current_weather', 'description': 'Get the current weather in a given location', 'parameters': {'type': 'object', 'properties': {'location': {'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA'}, 'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}}, 'required': ['location']}}}]} + """ # noqa: E501 + + # Handle messages and tools separately. + openai_request: Dict[str, Any] = self.model_dump( + exclude={"messages", "tools", "truncate_for_context_length"}, exclude_none=True + ) + + # Rename random_seed to seed. + seed = openai_request.pop("random_seed", None) + if seed is not None: + openai_request["seed"] = seed + + if self.truncate_for_context_length: + raise NotImplementedError("Truncating for context length is not implemented for OpenAI requests.") + + for kwarg in kwargs: + # Check for duplicate keyword arguments. + if kwarg in openai_request: + raise ValueError(f"Duplicate keyword argument: {kwarg}") + # Check if kwarg should have been set in the request. + # This occurs when the field is different between the Mistral and OpenAI API. + elif kwarg in ChatCompletionRequest.model_fields: + raise ValueError(f"Keyword argument {kwarg} is already set in the request.") + # Check if kwarg is a valid OpenAI field name. + elif not _is_openai_field_name(kwarg): + raise ValueError(f"Invalid keyword argument: {kwarg}, it should be an OpenAI field name.") + + openai_messages = [] + for message in self.messages: + openai_messages.append(message.to_openai()) + + openai_request["messages"] = openai_messages + if self.tools is not None: + openai_request["tools"] = [tool.to_openai() for tool in self.tools] + + openai_request.update(kwargs) + + return openai_request + + @classmethod + def from_openai( + cls, + messages: List[Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]], + tools: Optional[List[Dict[str, Any]]] = None, + continue_final_message: bool = False, + **kwargs: Any, + ) -> "ChatCompletionRequest": + r"""Create a chat completion request from the OpenAI format. + + Args: + messages: The messages in the OpenAI format. + tools: The tools in the OpenAI format. + continue_final_message: Whether to continue the final message. + **kwargs: Additional keyword arguments to pass to the constructor. These should be the same as the fields + of the request class or the OpenAI API equivalent. + + + Returns: + The chat completion request. + """ + if "seed" in kwargs and "random_seed" in kwargs: + raise ValueError("Cannot specify both `seed` and `random_seed`.") + + random_seed = kwargs.pop("seed", None) or kwargs.pop("random_seed", None) + + _check_openai_fields_names(set(cls.model_fields.keys()), set(kwargs.keys())) + + converted_messages: list[ChatMessage] = convert_openai_messages(messages) + + converted_tools = convert_openai_tools(tools) if tools is not None else None + + return cls( + messages=converted_messages, # type: ignore[arg-type] + tools=converted_tools, + random_seed=random_seed, + continue_final_message=continue_final_message, + **kwargs, + ) + + +class InstructRequest(MistralBase, Generic[ChatMessageType, ToolType]): + r"""A valid Instruct request to be tokenized. + + Attributes: + messages: The history of the conversation. + system_prompt: The system prompt to be used for the conversation. + available_tools: The tools available to the assistant. + truncate_at_max_tokens: The maximum number of tokens to truncate the conversation at. + continue_final_message: Whether to continue the final message. + + Examples: + >>> from mistral_common.protocol.instruct.messages import UserMessage, SystemMessage + >>> request = InstructRequest( + ... messages=[UserMessage(content="Hello, how are you?")], system_prompt="You are a helpful assistant." + ... ) + """ + + messages: List[ChatMessageType] + system_prompt: Optional[str] = None + available_tools: Optional[List[ToolType]] = None + truncate_at_max_tokens: Optional[int] = None + continue_final_message: bool = False + + def to_openai(self, **kwargs: Any) -> Dict[str, List[Dict[str, Any]]]: + r"""Convert the request messages and tools into the OpenAI format. + + Args: + kwargs: Additional parameters to be added to the request. + + Returns: + The request in the OpenAI format. + + Examples: + >>> from mistral_common.protocol.instruct.messages import UserMessage + >>> from mistral_common.protocol.instruct.tool_calls import Tool, Function + >>> request = InstructRequest(messages=[UserMessage(content="Hello, how are you?")]) + >>> request.to_openai(temperature=0.15, stream=True) + {'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'temperature': 0.15, 'stream': True} + >>> request = InstructRequest( + ... messages=[UserMessage(content="Hello, how are you?")], + ... available_tools=[ + ... Tool(function=Function( + ... name="get_current_weather", + ... description="Get the current weather in a given location", + ... parameters={ + ... "type": "object", + ... "properties": { + ... "location": { + ... "type": "string", + ... "description": "The city and state, e.g. San Francisco, CA", + ... }, + ... "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + ... }, + ... "required": ["location"], + ... }, + ... ), + ... )]) + >>> request.to_openai() + {'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'tools': [{'type': 'function', 'function': {'name': 'get_current_weather', 'description': 'Get the current weather in a given location', 'parameters': {'type': 'object', 'properties': {'location': {'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA'}, 'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}}, 'required': ['location']}}}]} + """ # noqa: E501 + + # Handle messages, tools, and truncate_at_max_tokens separately. + openai_request: Dict[str, Any] = self.model_dump( + exclude={"messages", "available_tools", "truncate_at_max_tokens"}, exclude_none=True + ) + + for kwarg in kwargs: + # Check for duplicate keyword arguments. + if kwarg in openai_request: + raise ValueError(f"Duplicate keyword argument: {kwarg}") + # Check if kwarg should have been set in the request. + # This occurs when the field is different between the Mistral and OpenAI API. + elif kwarg in InstructRequest.model_fields: + raise ValueError(f"Keyword argument {kwarg} is already set in the request.") + # Check if the keyword argument is a valid OpenAI field name. + elif not _is_openai_field_name(kwarg): + raise ValueError(f"Invalid keyword argument: {kwarg}, it should be an OpenAI field name.") + + openai_messages: list[dict[str, Any]] = [] + if self.system_prompt is not None: + openai_messages.append({"role": "system", "content": self.system_prompt}) + + for message in self.messages: + openai_messages.append(message.to_openai()) + + openai_request["messages"] = openai_messages + if self.available_tools is not None: + # Rename available_tools to tools + openai_request["tools"] = [tool.to_openai() for tool in self.available_tools] + + if self.truncate_at_max_tokens is not None: + raise NotImplementedError("Truncating at max tokens is not implemented for OpenAI requests.") + + openai_request.update(kwargs) + + return openai_request + + @classmethod + def from_openai( + cls, + messages: List[Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]], + tools: Optional[List[Dict[str, Any]]] = None, + continue_final_message: bool = False, + **kwargs: Any, + ) -> "InstructRequest": + r"""Create an instruct request from the OpenAI format. + + Args: + messages: The messages in the OpenAI format. + tools: The tools in the OpenAI format. + continue_final_message: Whether to continue the final message. + **kwargs: Additional keyword arguments to pass to the constructor. These should be the same as the fields + of the request class or the OpenAI API equivalent. + + Returns: + The instruct request. + """ + # Handle the case where the tools are passed as `available_tools`. + # This is to maintain compatibility with the OpenAI API. + if "available_tools" in kwargs: + if tools is None: + tools = kwargs.pop("available_tools") + else: + raise ValueError("Cannot specify both `tools` and `available_tools`.") + + _check_openai_fields_names(set(cls.model_fields.keys()), set(kwargs.keys())) + + converted_messages: list[ChatMessage] = convert_openai_messages(messages) + + converted_tools = convert_openai_tools(tools) if tools is not None else None + + return cls( + messages=converted_messages, # type: ignore[arg-type] + available_tools=converted_tools, # type: ignore[arg-type] + continue_final_message=continue_final_message, + **kwargs, + ) diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/response.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/response.py new file mode 100644 index 0000000000000000000000000000000000000000..952117055f71663d365fe9aa1615771029dd364e --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/response.py @@ -0,0 +1,189 @@ +import time +from enum import Enum +from typing import List, Optional + +from pydantic import Field + +from mistral_common.base import MistralBase +from mistral_common.protocol.base import UsageInfo +from mistral_common.protocol.instruct.tool_calls import ToolCall +from mistral_common.protocol.utils import random_uuid + + +class FinishReason(str, Enum): + r"""Possible finish reasons. + + Attributes: + stop: The model hit a natural stop point or a provided stop sequence. + length: The maximum number of tokens specified in the request was reached. + model_length: The model hit its context length limit. + error: An error occurred during generation. + tool_calls: The model called a tool. + + Examples: + >>> reason = FinishReason.stop + """ + + stop = "stop" + length = "length" + model_length = "model_length" + error = "error" + tool_call = "tool_calls" + + +class ChatCompletionTokenLogprobs(MistralBase): + r"""Log probabilities for a token. + + Attributes: + token: The token. + logprob: The log probability of the token. + bytes: The bytes of the token. + + Examples: + >>> token_logprobs = ChatCompletionTokenLogprobs(token="hello", logprob=-0.5, bytes=[104, 101, 108, 108, 111]) + """ + + token: str + logprob: float + bytes: List[int] + + +class ChatCompletionResponseChoiceLogprobs(MistralBase): + r"""Log probabilities for a choice. + + Attributes: + content: The log probabilities for the content. + + Examples: + >>> choice_logprobs = ChatCompletionResponseChoiceLogprobs( + ... content=[ChatCompletionTokenLogprobs(token="hello", logprob=-0.5, bytes=[104, 101, 108, 108, 111])] + ... ) + """ + + content: List[ChatCompletionTokenLogprobs] + + +class DeltaMessage(MistralBase): + r"""A message in a chat completion. + + Attributes: + role: The role of the message. + content: The content of the message. + tool_calls: The tool calls in the message. + + Examples: + >>> message = DeltaMessage(role="user", content="Hello, world!") + """ + + role: Optional[str] = None + content: Optional[str] = None + tool_calls: Optional[List[ToolCall]] = None + + +class ChatCompletionResponseChoice(MistralBase): + r"""A choice in a chat completion. + + Attributes: + index: The index of the choice. + message: The message of the choice. + finish_reason: The finish reason of the choice. + logprobs: The log probabilities of the choice. + + Examples: + >>> choice = ChatCompletionResponseChoice(index=0, message=DeltaMessage(role="user", content="Hello, world!")) + """ + + index: int + message: DeltaMessage + finish_reason: Optional[FinishReason] = None + logprobs: Optional[ChatCompletionResponseChoiceLogprobs] = None + + +class ChatCompletionResponse(MistralBase): + r"""A chat completion response. + + See [ChatCompletionRequest][mistral_common.protocol.instruct.request.ChatCompletionRequest] for the request. + + Attributes: + id: The id of the response. + object: The object of the response. + created: The creation time of the response. + model: The model of the response. + choices: The choices of the response. + usage: The usage of the response. + + Examples: + >>> response = ChatCompletionResponse( + ... id="chatcmpl-123", + ... object="chat.completion", + ... created=1677652288, + ... model="mistral-tiny", + ... choices=[ + ... ChatCompletionResponseChoice(index=0, message=DeltaMessage(role="user", content="Hello, world!")) + ... ], + ... usage=UsageInfo(prompt_tokens=10, total_tokens=20, completion_tokens=10), + ... ) + """ + + id: str = Field(default_factory=lambda: f"chatcmpl-{random_uuid()}") + object: str = "chat.completion" + created: int = Field(default_factory=lambda: int(time.time())) + model: str + choices: List[ChatCompletionResponseChoice] + usage: UsageInfo + + +class ChatCompletionResponseStreamChoice(MistralBase): + r"""A choice in a chat completion stream response. + + Attributes: + index: The index of the choice. + delta: The delta of the choice. + finish_reason: The finish reason of the choice. + logprobs: The log probabilities of the choice. + + Examples: + >>> choice = ChatCompletionResponseStreamChoice( + ... index=0, delta=DeltaMessage(role="user", content="Hello, world!") + ... ) + + """ + + index: int + delta: DeltaMessage + finish_reason: Optional[FinishReason] = None + logprobs: Optional[ChatCompletionResponseChoiceLogprobs] = None + + +class ChatCompletionStreamResponse(MistralBase): + r"""A chat completion stream response. + + See [ChatCompletionRequest][mistral_common.protocol.instruct.request.ChatCompletionRequest] for the request. + + Attributes: + id: The id of the response. + object: The object of the response. + created: The creation time of the response. + model: The model of the response. + choices: The choices of the response. + usage: The usage of the response. + + Examples: + >>> response = ChatCompletionStreamResponse( + ... id="chatcmpl-123", + ... object="chat.completion.chunk", + ... created=1677652288, + ... model="mistral-tiny", + ... choices=[ + ... ChatCompletionResponseStreamChoice(index=0, delta=DeltaMessage(role="user", content="Hello, world!")) + ... ], + ... usage=UsageInfo(prompt_tokens=10, total_tokens=20, completion_tokens=10), + ... ) + """ + + id: str = Field(default_factory=lambda: f"chatcmpl-{random_uuid()}") + object: str = "chat.completion.chunk" + created: int = Field(default_factory=lambda: int(time.time())) + model: str + choices: List[ChatCompletionResponseStreamChoice] + usage: Optional[UsageInfo] = None diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/tool_calls.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/tool_calls.py new file mode 100644 index 0000000000000000000000000000000000000000..40e3d7e3ddafa47d811a794da5e73070ed7de1a5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/tool_calls.py @@ -0,0 +1,171 @@ +import json +from enum import Enum +from typing import Any, Dict, TypeVar, Union + +from pydantic import field_validator + +from mistral_common.base import MistralBase + + +class Function(MistralBase): + r"""Function definition for tools. + + Attributes: + name: The name of the function. + description: A description of what the function does. + parameters: The parameters the functions accepts, described as a JSON Schema object. + + Examples: + >>> function = Function( + ... name="get_current_weather", + ... description="Get the current weather in a given location", + ... parameters={ + ... "type": "object", + ... "properties": { + ... "location": { + ... "type": "string", + ... "description": "The city and state, e.g. San Francisco, CA", + ... }, + ... "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + ... }, + ... "required": ["location"], + ... }, + ... ) + """ + + name: str + description: str = "" + parameters: Dict[str, Any] + + +class ToolTypes(str, Enum): + r"""Enum of tool types. + + Attributes: + function: A function tool. + + Examples: + >>> tool_type = ToolTypes.function + """ + + function = "function" + + +class ToolChoice(str, Enum): + r"""Enum of tool choice types. + + Attributes: + auto: Automatically choose the tool. + none: Do not use any tools. + any: Use any tool. + + Examples: + >>> tool_choice = ToolChoice.auto + """ + + auto = "auto" + none = "none" + any = "any" + + +class Tool(MistralBase): + r"""Tool definition. + + Attributes: + type: The type of the tool. + function: The function definition. + + Examples: + >>> tool = Tool( + ... function=Function( + ... name="get_current_weather", + ... description="Get the current weather in a given location", + ... parameters={ + ... "type": "object", + ... "properties": { + ... "location": { + ... "type": "string", + ... "description": "The city and state, e.g. San Francisco, CA", + ... }, + ... "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + ... }, + ... "required": ["location"], + ... }, + ... ), + ... ) + """ + + type: ToolTypes = ToolTypes.function + function: Function + + def to_openai(self) -> Dict[str, Any]: + return self.model_dump() + + @classmethod + def from_openai(cls, openai_tool: Dict[str, Any]) -> "Tool": + return cls.model_validate(openai_tool) + + +class FunctionCall(MistralBase): + r"""Function call. + + Attributes: + name: The name of the function to call. + arguments: The arguments to pass to the function. + + Examples: + >>> function_call = FunctionCall( + ... name="get_current_weather", + ... arguments={"location": "San Francisco, CA", "unit": "celsius"}, + ... ) + """ + + name: str + arguments: str + + @field_validator("arguments", mode="before") + def validate_arguments(cls, v: Union[str, Dict[str, Any]]) -> str: + """Convert arguments to a JSON string if they are a dictionary. + + Args: + v: The arguments to validate. + + Returns: + The arguments as a JSON string. + """ + if isinstance(v, dict): + return json.dumps(v) + return v + + +class ToolCall(MistralBase): + r"""Tool call. + + Attributes: + id: The ID of the tool call. Required for V3+ tokenization + type: The type of the tool call. + function: The function call. + + Examples: + >>> tool_call = ToolCall( + ... id="call_abc123", + ... function=FunctionCall( + ... name="get_current_weather", + ... arguments={"location": "San Francisco, CA", "unit": "celsius"}, + ... ), + ... ) + """ + + id: str = "null" + type: ToolTypes = ToolTypes.function + function: FunctionCall + + def to_openai(self) -> Dict[str, Any]: + return self.model_dump() + + @classmethod + def from_openai(cls, tool_call: Dict[str, Any]) -> "ToolCall": + return cls.model_validate(tool_call) + + +ToolType = TypeVar("ToolType", bound=Tool) diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/validator.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/validator.py new file mode 100644 index 0000000000000000000000000000000000000000..637ef6ff57f01e7007dd187ceea057adbd96a48a --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/instruct/validator.py @@ -0,0 +1,453 @@ +import re +from enum import Enum +from typing import Generic, List, Set + +from jsonschema import Draft7Validator, SchemaError + +from mistral_common.exceptions import ( + InvalidAssistantMessageException, + InvalidFunctionCallException, + InvalidMessageStructureException, + InvalidRequestException, + InvalidSystemPromptException, + InvalidToolException, + InvalidToolMessageException, + InvalidToolSchemaException, +) +from mistral_common.protocol.instruct.messages import ( + UATS, + AssistantMessage, + AssistantMessageType, + FinetuningAssistantMessage, + Roles, + SystemMessageType, + ToolMessageType, + UserMessageType, +) +from mistral_common.protocol.instruct.request import ChatCompletionRequest +from mistral_common.protocol.instruct.tool_calls import ( + Function, + FunctionCall, + Tool, + ToolCall, +) + + +class ValidationMode(Enum): + r"""Enum for the validation mode. + + Attributes: + serving: The serving mode. + finetuning: The finetuning mode. + test: The test mode. + + Examples: + >>> mode = ValidationMode.serving + """ + + serving = "serving" + finetuning = "finetuning" + test = "test" + + +class MistralRequestValidator(Generic[UserMessageType, AssistantMessageType, ToolMessageType, SystemMessageType]): + r"""Validator for Mistral requests. + + This class validates the structure and content of Mistral requests. + + Examples: + >>> from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage + >>> validator = MistralRequestValidator() + >>> messages = [UserMessage(content="Hello how are you ?")] + >>> validator.validate_messages(messages, False) + """ + + _allow_tool_call_and_content: bool = False + + def __init__(self, mode: ValidationMode = ValidationMode.test): + r"""Initializes the `MistralRequestValidator`. + + Args: + mode: The validation mode. Defaults to ValidationMode.test. + """ + self._mode = mode + + def validate_messages(self, messages: List[UATS], continue_final_message: bool) -> None: + r"""Validates the list of messages. + + Args: + messages: The list of messages to validate. + continue_final_message: Whether to continue the final message. + + Examples: + >>> from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage + >>> validator = MistralRequestValidator() + >>> messages = [AssistantMessage(content="Hi"), UserMessage(content="Hello")] + >>> validator.validate_messages(messages, False) + """ + self._validate_message_list_structure(messages, continue_final_message=continue_final_message) + self._validate_message_list_content(messages) + + def validate_request(self, request: ChatCompletionRequest) -> ChatCompletionRequest[UATS]: + r"""Validates the request + + Args: + request: The request to validate. + + Returns: + The validated request. + + Examples: + >>> from mistral_common.protocol.instruct.messages import UserMessage + >>> validator = MistralRequestValidator() + >>> request = ChatCompletionRequest(messages=[UserMessage(content="Hello")]) + >>> validated_request = validator.validate_request(request) + """ + + if self._mode == ValidationMode.serving: + if request.model is None: + raise InvalidRequestException("Model name parameter is required for serving mode") + + # Validate the messages + self.validate_messages(request.messages, continue_final_message=request.continue_final_message) + + # Validate the tools + self._validate_tools(request.tools or []) + + return request + + def _validate_function(self, function: Function) -> None: + """ + Checks: + - That the function schema is valid + """ + try: + Draft7Validator.check_schema(function.parameters) + except SchemaError as e: + raise InvalidToolSchemaException(f"Invalid tool schema: {e.message}") + + if not re.match(r"^[a-zA-Z0-9_-]{1,64}$", function.name): + raise InvalidToolException( + f"Function name was {function.name} but must be a-z, A-Z, 0-9, " + "or contain underscores and dashes, with a maximum length of 64." + ) + + def _validate_tools(self, tools: List[Tool]) -> None: + """ + Checks: + - That the tool schemas are valid + """ + + for tool in tools: + self._validate_function(tool.function) + + def _validate_user_message(self, message: UserMessageType) -> None: + pass + + def _validate_tool_message(self, message: ToolMessageType) -> None: + """ + Checks: + - The tool name is valid + """ + if message.name is not None: + if not re.match(r"^[a-zA-Z0-9_-]{1,64}$", message.name): + raise InvalidToolMessageException( + f"Function name was {message.name} but must be a-z, A-Z, 0-9, " + "or contain underscores and dashes, with a maximum length of 64." + ) + + def _validate_system_message(self, message: SystemMessageType) -> None: + """ + Checks: + - That the system prompt has content + """ + if message.content is None: + raise InvalidSystemPromptException("System prompt must have content") + + def _validate_function_call(self, function_call: FunctionCall) -> None: + """ + Checks: + - That the function call has a valid name + """ + if not re.match(r"^[a-zA-Z0-9_-]{1,64}$", function_call.name): + raise InvalidFunctionCallException( + f"Function name was {function_call.name} but must be a-z, A-Z, 0-9, " + "or contain underscores and dashes, with a maximum length of 64." + ) + + def _validate_tool_call(self, tool_call: ToolCall, is_last_message: bool) -> None: + """ + Checks: + - That the tool call has a valid function + """ + + self._validate_function_call(tool_call.function) + + def _validate_assistant_message(self, message: AssistantMessageType, is_last_message: bool = False) -> None: + """ + Checks: + - That the assistant message has either text or tool_calls, but not both + - That the tool calls are valid + """ + + # Validate that the message has either text or tool_calls + # but not both and not neither. + if (not self._allow_tool_call_and_content) and (bool(message.content) == bool(message.tool_calls)): + raise InvalidAssistantMessageException( + "Assistant message must have either content or tool_calls, but not both." + ) + + # If we have tool calls, validate them + if message.tool_calls is not None: + # Validate that the tool calls are valid + for tool_call in message.tool_calls: + self._validate_tool_call(tool_call, is_last_message=is_last_message) + + if self._mode == ValidationMode.finetuning and isinstance(message, FinetuningAssistantMessage): + if message.weight is not None and message.weight not in [0, 1]: + raise InvalidAssistantMessageException("Assistant message weight must be either 0 or 1") + + if message.prefix: + if not is_last_message: + raise InvalidAssistantMessageException("Assistant message with prefix True must be last message") + # note : we already validate that assistant message has content 3 lines up. + + def _validate_tool_calls_followed_by_tool_messages(self, messages: List[UATS]) -> None: + """ + Checks: + - That the number of tool calls and tool messages are the same + - That the tool calls are followed by tool messages + """ + prev_role = None + expected_tool_messages = 0 + for message in messages: + if prev_role is None: + prev_role = message.role + continue + + if message.role == Roles.tool: + expected_tool_messages -= 1 + elif message.role == Roles.assistant: + # if we have an assistant message and we have not received all the function calls + # we need to raise an exception + if expected_tool_messages != 0: + raise InvalidMessageStructureException("Not the same number of function calls and responses") + + if message.tool_calls is not None: + # Validate that the number of function calls and responses are the same + expected_tool_messages = len(message.tool_calls) + + prev_role = message.role + + if expected_tool_messages != 0 and self._mode == ValidationMode.serving: + raise InvalidMessageStructureException("Not the same number of function calls and responses") + elif expected_tool_messages < 0 and self._mode == ValidationMode.finetuning: + raise InvalidMessageStructureException("More tool responses than tool calls") + + def _validate_message_order(self, messages: List[UATS]) -> None: + """ + Validates the order of the messages, for example user -> assistant -> user -> assistant -> ... + """ + previous_role = None + for message in messages: + current_role = message.role + + if previous_role is not None: + if previous_role == Roles.system: + expected_roles = {Roles.user, Roles.assistant, Roles.system} + elif previous_role == Roles.user: + expected_roles = {Roles.assistant, Roles.system, Roles.user} + elif previous_role == Roles.assistant: + expected_roles = {Roles.assistant, Roles.user, Roles.tool} + elif previous_role == Roles.tool: + expected_roles = {Roles.assistant, Roles.tool} + + if current_role not in expected_roles: + raise InvalidMessageStructureException( + f"Unexpected role '{current_role}' after role '{previous_role}'" + ) + + previous_role = current_role + + def _validate_last_message(self, message: UATS, continue_final_message: bool) -> None: + # The last message must be a user or tool message in serving mode or an assistant message in finetuning mode + last_message_role = message.role + if self._mode == ValidationMode.finetuning: + if last_message_role != Roles.assistant: + raise InvalidMessageStructureException( + f"Expected last role Assistant for finetuning but got {last_message_role}" + ) + if continue_final_message: + raise InvalidMessageStructureException("Cannot continue final message in finetuning mode") + else: + bad_assistant = isinstance(message, AssistantMessage) and not message.prefix and not continue_final_message + bad_role = message.role not in {Roles.user, Roles.tool} + if bad_assistant and bad_role: + raise InvalidMessageStructureException( + f"Expected last role User or Tool (or Assistant with prefix or continue_final_message set to True) " + f"for serving but got {last_message_role}" + ) + elif continue_final_message and (last_message_role != Roles.assistant or message.prefix): + raise InvalidMessageStructureException( + f"Expected last role Assistant with prefix False for serving with continue_final_message set to " + f"True but got {last_message_role}" + ) + + def _validate_message_list_structure(self, messages: List[UATS], continue_final_message: bool) -> None: + """ + Validates the structure of the list of messages + + For example the messages must be in the correct order of user/assistant/tool + """ + + if len(messages) == 0: + raise InvalidMessageStructureException("Conversation must have at least one message") + + # If we have one message it must be a user or a system message + if len(messages) == 1: + if messages[0].role not in {Roles.user, Roles.system}: + raise InvalidMessageStructureException("Conversation must start with a user message or system message") + + # Always check the last message if in fine-tuning mode + if self._mode == ValidationMode.finetuning or len(messages) > 1: + self._validate_last_message(messages[-1], continue_final_message=continue_final_message) + + self._validate_message_order(messages) + self._validate_tool_calls_followed_by_tool_messages(messages) + + def _validate_message_list_content(self, messages: List[UATS]) -> None: + """ + Validates the content of the messages + """ + + for idx, message in enumerate(messages): + if message.role == Roles.user: + self._validate_user_message(message) + elif message.role == Roles.assistant: + self._validate_assistant_message(message, is_last_message=idx == len(messages) - 1) + elif message.role == Roles.tool: + self._validate_tool_message(message) + elif message.role == Roles.system: + self._validate_system_message(message) + else: + raise InvalidRequestException(f"Unsupported message type {type(message)}") + + +class MistralRequestValidatorV3(MistralRequestValidator): + r"""Validator for v3 Mistral requests. + + This validator adds additional validation for tool call IDs. + + Examples: + >>> validator = MistralRequestValidatorV3() + """ + + def _validate_tool_message(self, message: ToolMessageType) -> None: + """ + Checks: + - The tool name is valid + - Tool call id is valid + """ + if message.name is not None: + if not re.match(r"^[a-zA-Z0-9_-]{1,64}$", message.name): + raise InvalidToolMessageException( + f"Function name was {message.name} but must be a-z, A-Z, 0-9, " + "or contain underscores and dashes, with a maximum length of 64." + ) + + if message.tool_call_id is None: + raise InvalidRequestException("Tool call id has to be defined.") + + if not re.match(r"^[a-zA-Z0-9]{9}$", message.tool_call_id): + raise InvalidToolMessageException( + f"Tool call id was {message.tool_call_id} but must be a-z, A-Z, 0-9, with a length of 9." + ) + + def _validate_tool_call(self, tool_call: ToolCall, is_last_message: bool) -> None: + """ + Validate that the tool call has a valid ID + """ + if tool_call.id != "null": + if not re.match(r"^[a-zA-Z0-9]{9}$", tool_call.id): + raise InvalidFunctionCallException( + f"Tool call id was {tool_call.id} but must be a-z, A-Z, 0-9, with a length of 9." + ) + if self._mode == ValidationMode.finetuning and not is_last_message and tool_call.id == "null": + err_message = "Tool call id of assistant message that is not last has to be defined in finetuning mode." + raise InvalidFunctionCallException(err_message) + + if self._mode == ValidationMode.serving and tool_call.id == "null": + raise InvalidFunctionCallException("Tool call id has to be defined in serving mode.") + + self._validate_function_call(tool_call.function) + + def _validate_last_message(self, message: UATS, continue_final_message: bool) -> None: + super()._validate_last_message(message, continue_final_message) + + if self._mode == ValidationMode.finetuning: + # in finetuning mode it has to be an assistant message + # as checked by parent `_validate_last_message` + if message.tool_calls is not None: + for tool_call in message.tool_calls: + self._validate_tool_call(tool_call, is_last_message=True) + + +class MistralRequestValidatorV5(MistralRequestValidatorV3): + r"""Validator for v5 Mistral requests. + + This validator allows for both tool calls and content in the assistant message. + + Examples: + >>> validator = MistralRequestValidatorV5() + """ + + _allow_tool_call_and_content: bool = True + + +class MistralRequestValidatorV13(MistralRequestValidatorV5): + def _validate_tool_calls_followed_by_tool_messages(self, messages: List[UATS]) -> None: + """ + Checks: + - That the number and ids of tool calls and tool messages are the same + - That the tool calls are followed by tool messages + - That tool calls have distinct ids for a given assistant message + """ + prev_role = None + expected_tool_ids: Set[str] = set() + observed_tool_ids: Set[str] = set() + for message in messages: + if prev_role is None: + prev_role = message.role + continue + + if message.role == Roles.tool: + tool_call_id = message.tool_call_id + if tool_call_id in observed_tool_ids: + raise InvalidMessageStructureException(f"Duplicate tool call id {tool_call_id} in tool results") + if tool_call_id not in expected_tool_ids: + raise InvalidMessageStructureException(f"Unexpected tool call id {tool_call_id} in tool results") + observed_tool_ids.add(tool_call_id) + + elif message.role == Roles.assistant: + # if we have an assistant message and we have not recieved all the function calls + # we need to raise an exception + if len(expected_tool_ids) != len(observed_tool_ids): + raise InvalidMessageStructureException("Not the same number of function calls and responses") + + expected_tool_ids.clear() + observed_tool_ids.clear() + if message.tool_calls is not None: + # Validate that the number of function calls and ids are the same + for tool_call in message.tool_calls: + if tool_call.id in expected_tool_ids: + raise InvalidMessageStructureException( + f"Duplicate tool call id {tool_call.id} in assistant message" + ) + expected_tool_ids.add(tool_call.id) + + prev_role = message.role + + if len(expected_tool_ids) != len(observed_tool_ids) and self._mode == ValidationMode.serving: + raise InvalidMessageStructureException("Not the same number of function calls and responses") + elif len(expected_tool_ids) < len(observed_tool_ids) and self._mode == ValidationMode.finetuning: + raise InvalidMessageStructureException("More tool responses than tool calls") diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/transcription/__init__.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/transcription/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/transcription/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/transcription/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b41bce116f0835a5781c4a8667eb43782a9104c Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/transcription/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/transcription/__pycache__/request.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/protocol/transcription/__pycache__/request.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2834c90f28c02dc92b5af72216042dcaba5829c5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/protocol/transcription/__pycache__/request.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/transcription/request.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/transcription/request.py new file mode 100644 index 0000000000000000000000000000000000000000..7b23b33ff9172898662063804e0c9bfbe75c0c0e --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/transcription/request.py @@ -0,0 +1,121 @@ +import io +from typing import Any, Dict, List, Optional + +from pydantic import Field +from pydantic_extra_types.language_code import LanguageAlpha2 + +from mistral_common.audio import Audio, is_soundfile_installed +from mistral_common.protocol.base import BaseCompletionRequest +from mistral_common.protocol.instruct.messages import RawAudio + + +class TranscriptionRequest(BaseCompletionRequest): + r"""A class representing a request for audio transcription. + + This class handles the conversion of audio data into a format suitable for transcription + using the OpenAI API. It includes methods to convert the request to and from the OpenAI format. + + Attributes: + id: An optional identifier for the transcription request. + model: The model to be used for transcription. + audio: The audio data to be transcribed. + language: The language of the input audio in ISO-639-1 format (optional). + strict_audio_validation: A flag indicating whether to perform strict validation of the audio data. + """ + + id: Optional[str] = None + model: str + audio: RawAudio + language: Optional[LanguageAlpha2] = Field( + ..., + description=( + "The language of the input audio. Supplying the input language " + "in ISO-639-1 format will improve language adherence." + ), + ) + strict_audio_validation: bool = True + + def to_openai(self, exclude: tuple = (), **kwargs: Any) -> Dict[str, List[Dict[str, Any]]]: + r"""Convert the transcription request into the OpenAI format. + + This method prepares the transcription request data for compatibility with the OpenAI API. + It handles the conversion of audio data and additional parameters into the required format. + + Args: + exclude: Fields to exclude from the conversion. + kwargs: Additional parameters to be added to the request. + + Returns: + The request in the OpenAI format. + + Raises: + ImportError: If the required soundfile library is not installed. + """ + openai_request: Dict[str, Any] = self.model_dump(exclude={"audio"}) + + if not is_soundfile_installed(): + raise ImportError( + "soundfile is required for this function. Install it with 'pip install mistral-common[soundfile]'" + ) + + import soundfile as sf + + if isinstance(self.audio.data, bytes): + buffer = io.BytesIO(self.audio.data) + else: + assert isinstance(self.audio.data, str) + audio = Audio.from_base64(self.audio.data) + + buffer = io.BytesIO() + sf.write(buffer, audio.audio_array, audio.sampling_rate, format=audio.format) + # reset cursor to beginning + buffer.seek(0) + + openai_request["file"] = buffer + openai_request["seed"] = openai_request.pop("random_seed") + openai_request.update(kwargs) + + # remove mistral-specific + default_exclude = ("id", "max_tokens", "strict_audio_validation") + default_exclude += exclude + for k in default_exclude: + openai_request.pop(k, None) + + return openai_request + + @classmethod + def from_openai(cls, openai_request: Dict[str, Any], strict: bool = False) -> "TranscriptionRequest": + r"""Create a TranscriptionRequest instance from an OpenAI request dictionary. + + This method converts an OpenAI request dictionary into a TranscriptionRequest instance, + handling the conversion of audio data and other parameters. + + Args: + openai_request: The OpenAI request dictionary. + strict: A flag indicating whether to perform strict validation of the audio data. + + Returns: + An instance of TranscriptionRequest. + """ + file = openai_request.get("file") + seed = openai_request.get("seed") + converted_dict = { + k: v + for k, v in openai_request.items() + if (k in cls.model_fields and not (v is None and k in ["temperature", "top_p"])) + } + + assert file is not None, file + if isinstance(file, io.BytesIO): + audio_bytes = file.getvalue() + else: + # for example if file is UploadFile, this should work + audio_bytes = file.file.read() + + audio = Audio.from_bytes(audio_bytes, strict=strict) + audio_str = audio.to_base64(audio.format) + raw_audio = RawAudio(data=audio_str, format=audio.format) + + converted_dict["audio"] = raw_audio + converted_dict["random_seed"] = seed + return cls(**converted_dict) diff --git a/venv/lib/python3.10/site-packages/mistral_common/protocol/utils.py b/venv/lib/python3.10/site-packages/mistral_common/protocol/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..653d3a47750b4ef71ec4c3d178ccbd9768297fdc --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/protocol/utils.py @@ -0,0 +1,6 @@ +import uuid + + +def random_uuid() -> str: + """Generate a random UUID.""" + return str(uuid.uuid4().hex) diff --git a/venv/lib/python3.10/site-packages/mistral_common/py.typed b/venv/lib/python3.10/site-packages/mistral_common/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/__init__.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/tokens/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce01fff77dc230b9639693b7eb98fcf11d4649e5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/tokens/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/instruct/__init__.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/instruct/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/instruct/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/tokens/instruct/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab7ee10805aa1766b9fba825a267ce43efbab4ef Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/tokens/instruct/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/instruct/__pycache__/request.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/tokens/instruct/__pycache__/request.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67c57f0df82f4239b2c98aa951a272b1892e8785 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/tokens/instruct/__pycache__/request.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/instruct/request.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/instruct/request.py new file mode 100644 index 0000000000000000000000000000000000000000..b73174676f08ed55dcffc6fef0f9c077e6720f25 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/tokens/instruct/request.py @@ -0,0 +1,12 @@ +# this file is deprecated +import warnings + +from mistral_common.protocol.fim.request import FIMRequest # noqa: F401 +from mistral_common.protocol.instruct.request import InstructRequest # noqa: F401 + +warnings.warn( + "This file is deprecated and will be deleted in v1.9.0, please import as follows instead: \n" + "`from mistral_common.protocol.fim.request import FimRequest` \n or \n" + "`from mistral_common.protocol.instruct.request import InstructRequest`", + FutureWarning, +) diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__init__.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a786d85f7e4534ea3a25dc7833311bb7ff9ab0d Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/audio.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/audio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82901a709495e7c10705ae5784d651f67cbad575 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/audio.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/base.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1195cef2585d30dcc184b23158f1ebb8dee01001 Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/multimodal.cpython-310.pyc b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/multimodal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98283325d666728c6cadddc57ab24d0a16715b6a Binary files /dev/null and b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/__pycache__/multimodal.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/audio.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/audio.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b832a635e3ad416ebe77af506c27a4a32748a2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/audio.py @@ -0,0 +1,220 @@ +import logging +import math +from dataclasses import dataclass +from typing import List, Optional, Union + +import numpy as np + +from mistral_common.audio import Audio +from mistral_common.protocol.instruct.messages import AudioChunk, AudioURLChunk, AudioURLType + +logger = logging.getLogger(__name__) + + +@dataclass +class AudioSpectrogramConfig: + r"""Configuration for generating an audio spectrogram. + + Attributes: + num_mel_bins: Number of mel bins, typically 80 or 128. + hop_length: Length of the overlapping windows for + the STFT used to obtain the Mel Frequency coefficients, typically 160. + window_size: Window size of the Fourier transform, typically 400. + """ + + # Number of mel bins, typically 80 or 128 + num_mel_bins: int + # Length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients, typically 160 + hop_length: int + # Window size of the Fourier transform, typically 400 + window_size: int + + def __post_init__(self) -> None: + assert self.num_mel_bins > 0, self.num_mel_bins + assert self.hop_length > 0, self.hop_length + assert self.window_size > 0, self.window_size + + +@dataclass +class AudioConfig: + r"""Configuration for audio processing. + + Attributes: + sampling_rate: Sampling rate of the audio. + frame_rate: Number of frames per second accepted by the tokenizer model. + encoding_config: Configuration for audio spectrogram. + chunk_length_s: Whether to pad an audio into multiples of chunk_length_s seconds (optional). + """ + + sampling_rate: int + # number of frames per second accepted by the tokenizer model. + frame_rate: float + encoding_config: AudioSpectrogramConfig + # Whether to pad an audio into multiples of chunk_length_s seconds + chunk_length_s: Optional[float] = None + + def __post_init__(self) -> None: + assert self.frame_rate > 0, self.frame_rate + assert self.sampling_rate > 0, self.sampling_rate + + if self.chunk_length_s is not None: + assert self.chunk_length_s > 0, self.chunk_length_s + assert self.chunk_frames > 0, ( + f"chunk_length_s and sampling_rate must both be > 0, got {self.chunk_length_s} and {self.sampling_rate}" + ) + + @property + def chunk_frames(self) -> int: + r"""Calculate the number of frames per chunk.""" + assert self.chunk_length_s is not None, f"Can't call chunk_frames if {self.chunk_length_s=}." + return int(self.chunk_length_s * self.sampling_rate) + + @property + def audio_length_per_tok(self) -> int: + r"""Calculate the length of audio per token.""" + downsample_factor = self.sampling_rate // self.frame_rate + downsample_factor /= self.encoding_config.hop_length + return int(downsample_factor) + + +@dataclass +class AudioEncoding: + r"""Encapsulates the tokens and audio data for an audio chunk. + + Attributes: + tokens: Text tokens corresponding to this audio chunk. + audio: Original audio waveform data. + """ + + # Text tokens corresponding to this audio chunk + tokens: List[int] + # Original audio waveform data. + audio: Audio + + +@dataclass +class SpecialAudioIDs: + r"""Special text tokens corresponding to audio token sequence. + + Attributes: + audio: Token representing audio. + begin_audio: Token representing the beginning of audio. + """ + + audio: int + begin_audio: int + + +class AudioEncoder: + r"""Encodes audio chunks into a format suitable for further processing. + + Attributes: + audio_config: Configuration for audio processing. + encoding_config: Configuration for audio spectrogram. + special_ids: Special tokens for audio encoding. + """ + + def __init__(self, audio_config: AudioConfig, special_ids: SpecialAudioIDs) -> None: + self.audio_config = audio_config + self.encoding_config = audio_config.encoding_config + self.special_ids = special_ids + + def pad(self, audio_array: np.ndarray, sampling_rate: int) -> np.ndarray: + r"""Pad the audio array to the desired length. + + Args: + audio_array: Audio data as a numpy array. + sampling_rate: Sampling rate of the audio. + + Returns: + Padded audio array. + """ + if self.audio_config.chunk_length_s: + next_multiple_of_chunk_frames = self.next_multiple_of_chunk_frames(audio_array.shape[-1], sampling_rate) + audio_array = np.pad(audio_array, (0, next_multiple_of_chunk_frames - audio_array.shape[-1])) + elif audio_array.shape[-1] < self.encoding_config.window_size: + # minimum length for audios is at least one spectrogram frame + audio_array = np.pad(audio_array, (0, self.encoding_config.window_size - audio_array.shape[-1])) + + return audio_array + + def next_multiple_of_chunk_frames(self, audio_array_len: int, sampling_rate: int) -> int: + r"""Calculate the next multiple of chunk frames. + + Args: + audio_array_len: Length of the audio array. + sampling_rate: Sampling rate of the audio. + + Returns: + The next multiple of chunk frames. + """ + assert sampling_rate == self.audio_config.sampling_rate, ( + f"Expected {sampling_rate=} to be {self.audio_config.sampling_rate=}" + ) + assert self.audio_config.chunk_length_s is not None, ( + f"Can't call next_multiple_of_chunk_frames if {self.audio_config.chunk_length_s=}." + ) + + return math.ceil(audio_array_len / self.audio_config.chunk_frames) * self.audio_config.chunk_frames + + def _encode_audio(self, audio: Audio) -> AudioEncoding: + audio.resample(self.audio_config.sampling_rate) + + audio.audio_array = self.pad(audio.audio_array, self.audio_config.sampling_rate) + signal_length = audio.audio_array.shape[0] + + # for spectrogram-based models, the waveform is downsampled by the hop_length when computing the log-mel + if signal_length % self.encoding_config.hop_length != 0: + signal_length = math.ceil(signal_length / self.encoding_config.hop_length - 1) + else: + signal_length = signal_length // self.encoding_config.hop_length + + num_audio_tokens = math.ceil(signal_length / self.audio_config.audio_length_per_tok) + audio_tokens = [self.begin_audio_token] + [self.audio_token] * num_audio_tokens + + return AudioEncoding( + tokens=audio_tokens, + audio=audio, + ) + + def _encode_audio_chunk(self, content: AudioChunk) -> AudioEncoding: + audio = Audio.from_raw_audio(content.input_audio) + return self._encode_audio(audio) + + def _encode_audio_url_chunk(self, content: AudioURLChunk) -> AudioEncoding: + url_type = content.get_url_type() + + if url_type in {AudioURLType.file, AudioURLType.file_uri}: + audio = Audio.from_file(content.url) + elif url_type == AudioURLType.url: + audio = Audio.from_url(content.url) + else: + audio = Audio.from_base64(content.url) + + return self._encode_audio(audio) + + def __call__(self, content: Union[AudioChunk, AudioURLChunk]) -> AudioEncoding: + r"""Call the encoder on an audio chunk or URL chunk. + + Args: + content: Audio or URL chunk to encode. + + Returns: + Encoded audio data and tokens. + """ + if isinstance(content, AudioURLChunk): + return self._encode_audio_url_chunk(content) + elif isinstance(content, AudioChunk): + return self._encode_audio_chunk(content) + else: + raise ValueError(f"Unsupported content type: {type(content)}") + + @property + def audio_token(self) -> int: + r"""Get the audio token.""" + return self.special_ids.audio + + @property + def begin_audio_token(self) -> int: + r"""Get the begin audio token.""" + return self.special_ids.begin_audio diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/base.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..dc005b85cc5acb5411494eabccd2f20d272ea207 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/base.py @@ -0,0 +1,403 @@ +import re +from abc import ABC, abstractmethod +from enum import Enum +from pathlib import Path +from typing import Generic, List, Optional, Tuple, TypeVar, Union + +import numpy as np +from pydantic import ConfigDict, Field + +from mistral_common.audio import Audio +from mistral_common.base import MistralBase +from mistral_common.protocol.fim.request import FIMRequest +from mistral_common.protocol.instruct.messages import ( + AssistantMessageType, + UserContentChunk, + UserMessage, +) +from mistral_common.protocol.instruct.request import InstructRequest +from mistral_common.protocol.instruct.tool_calls import Tool +from mistral_common.protocol.transcription.request import TranscriptionRequest +from mistral_common.tokens.tokenizers.audio import AudioEncoder +from mistral_common.tokens.tokenizers.image import ImageEncoder + + +class UserMessagePosition(str, Enum): + """Where to encode available tools""" + + first = "first" + last = "last" + + +class SpecialTokens(str, Enum): + r"""Enum of special tokens used in the tokenizer. + + Attributes: + unk: The unknown token. + bos: The beginning of string token. + eos: The end of string token. + begin_inst: The beginning of instruction token. + end_inst: The end of instruction token. + begin_tools: The beginning of tools token. + end_tools: The end of tools token. + begin_tool_results: The beginning of tool results token. + end_tool_results: The end of tool results token. + tool_calls: The tool calls token. + img: The image token. + pad: The pad token. + img_break: The image break token. + img_end: The image end token. + prefix: The prefix token for FIM. + middle: The middle token for FIM. + suffix: The suffix token for FIM. + begin_system: The beginning of system prompt token. + end_system: The end of system prompt token. + begin_tool_content: The beginning of tool content token. + args: The args token. + call_id: The call id token. + audio: The audio token. + begin_audio: The beginning of audio token. + transcribe: The transcribe token. + begin_think: The beginning of think token. + end_think: The end of think token. + + Examples: + >>> unk = SpecialTokens.unk + """ + + unk = "" + bos = "" + eos = "" + begin_inst = "[INST]" + end_inst = "[/INST]" + begin_tools = "[AVAILABLE_TOOLS]" + end_tools = "[/AVAILABLE_TOOLS]" + begin_tool_results = "[TOOL_RESULTS]" + end_tool_results = "[/TOOL_RESULTS]" + tool_calls = "[TOOL_CALLS]" + img = "[IMG]" + pad = "" + img_break = "[IMG_BREAK]" + img_end = "[IMG_END]" + prefix = "[PREFIX]" + middle = "[MIDDLE]" + suffix = "[SUFFIX]" + begin_system = "[SYSTEM_PROMPT]" + end_system = "[/SYSTEM_PROMPT]" + begin_tool_content = "[TOOL_CONTENT]" + args = "[ARGS]" + call_id = "[CALL_ID]" + audio = "[AUDIO]" + begin_audio = "[BEGIN_AUDIO]" + transcribe = "[TRANSCRIBE]" + begin_think = "[THINK]" + end_think = "[/THINK]" + + +class SpecialTokenPolicy(int, Enum): + r"""What to do with special tokens when encoding/decoding. + + Attributes: + IGNORE: Ignore special tokens. + KEEP: Keep special tokens. + RAISE: Raise an error if special tokens are found. + """ + + IGNORE = 0 + KEEP = 1 + RAISE = 2 + + +class TokenizerVersion(str, Enum): + r"""Enum of tokenizer versions. + + Allow to distinguish between different versions of the tokenizer and maintain backward compatibility. + + Attributes: + v1: The first version of the tokenizer. + v2: The second version of the tokenizer that includes special control tokens [INST], [\INST]. + v3: The third version of the tokenizer that includes improved function calling. + v7: The seventh version of the tokenizer that includes improved system prompt and function calling. + v11: The eleventh version of the tokenizer that includes improved function calling. + v13: The thirteenth version of the tokenizer that includes no call id tokenization and better prompt caching. + + Examples: + >>> version = TokenizerVersion.v1 + """ + + def __new__(cls, value: str) -> "TokenizerVersion": + if not re.match(r"^v\d+$", value): + raise ValueError(f"Invalid version format: {value}. Must be 'v' followed by a number.") + obj = str.__new__(cls, value) + obj._value_ = value + return obj + + @property + def _version_num(self) -> int: + return int(self.value[1:]) + + def __lt__(self, other: "str | TokenizerVersion") -> bool: + if isinstance(other, str): + other = TokenizerVersion(other) + return self._version_num < other._version_num + + def __le__(self, other: "str | TokenizerVersion") -> bool: + if isinstance(other, str): + other = TokenizerVersion(other) + return self._version_num <= other._version_num + + def __gt__(self, other: "str | TokenizerVersion") -> bool: + if isinstance(other, str): + other = TokenizerVersion(other) + return self._version_num > other._version_num + + def __ge__(self, other: "str | TokenizerVersion") -> bool: + if isinstance(other, str): + other = TokenizerVersion(other) + return self._version_num >= other._version_num + + v1 = "v1" # vocab_size = 32000 + v2 = "v2" # vocab_size = 32768 with special control tokens [INST], [\INST] + v3 = "v3" # vocab_size = 32768 (spm) OR 131072 (tekken) with improved function calling + v7 = "v7" # vocab_size = 32768 (spm) or 131072 (tekken) with improved system prompt and function calling + v11 = "v11" # 131072 (tekken) with improved function calling + v13 = "v13" # 131072 (tekken) with no call id and better prompt caching + + +class Tokenized(MistralBase): + r"""A tokenized [`InstructRequest`][mistral_common.tokens.instruct.request]. + + Attributes: + tokens: The token ids. + text: The text representation of the tokens. + prefix_ids: The prefix ids for FIM. + images: The loaded images associated with the tokens. + + Examples: + >>> tokenized = Tokenized(tokens=[1, 2, 3], text="Hello world", prefix_ids=[1], images=[]) + """ + + model_config = ConfigDict(arbitrary_types_allowed=True) + tokens: List[int] + text: Optional[str] = None + prefix_ids: Optional[List[int]] = None + images: List[np.ndarray] = Field(default_factory=list) + audios: List[Audio] = Field(default_factory=list) + + +class Tokenizer(ABC): + @property + @abstractmethod + def n_words(self) -> int: + r"""Vocabulary size of the tokenizer.""" + + @abstractmethod + def vocab(self) -> List[str]: + r"""All tokens in the vocabulary as strings.""" + + @abstractmethod + def id_to_piece(self, token_id: int) -> str: + r"""Convert a token id to the token str.""" + + @property + @abstractmethod + def bos_id(self) -> int: + r"""id of the Beginning of String token.""" + + @property + @abstractmethod + def eos_id(self) -> int: + r"""id of the End of String token.""" + + @property + @abstractmethod + def pad_id(self) -> int: + r"""id of the Pad token.""" + + @property + @abstractmethod + def unk_id(self) -> int: + r"""id of the Unk token.""" + + @abstractmethod + def encode(self, s: str, bos: bool, eos: bool) -> List[int]: + """Convert a string to a list of token ids.""" + + @abstractmethod + def decode(self, tokens: List[int], special_token_policy: Optional[SpecialTokenPolicy] = None) -> str: + r"""Decode the token ids to a string. + + Args: + tokens: The token ids to decode. + special_token_policy: The policy to use for special tokens. + Passing `None` will default to `self._special_token_policy` for + [Tekkenizer][mistral_common.tokens.tokenizers.tekken.Tekkenizer] and `SpecialTokenPolicy.IGNORE` + for [SentencePieceTokenizer][mistral_common.tokens.tokenizers.sentencepiece.SentencePieceTokenizer]. + Note that passing `None` will be deprecated and `special_token_policy` will default to + `SpecialTokenPolicy.IGNORE` in `mistral_common=1.10.0`. + + Returns: + The decoded string. + """ + + @abstractmethod + def get_control_token(self, s: str) -> int: + r"""Get the id of a control token.""" + + @property + @abstractmethod + def version(self) -> TokenizerVersion: + r"""Get the version of the tokenizer.""" + + @abstractmethod + def to_string(self, tokens: List[int]) -> str: + r"""[DEPRECATED] Converts a list of token ids into a string, keeping special tokens. + + Use `decode` with `special_token_policy=SpecialTokenPolicy.KEEP` instead. + + This is a convenient method for debugging. + """ + ... + + @abstractmethod + def _to_string(self, tokens: List[int]) -> str: ... + + @property + @abstractmethod + def file_path(self) -> Path: + r"""The file path of the tokenizer.""" + ... + + +InstructRequestType = TypeVar("InstructRequestType", bound=InstructRequest) +FIMRequestType = TypeVar("FIMRequestType", bound=FIMRequest) +TokenizedType = TypeVar("TokenizedType", bound=Tokenized) + + +class InstructTokenizer(Generic[InstructRequestType, FIMRequestType, TokenizedType, AssistantMessageType]): + r"""Base class for instruct tokenizers. + + Attributes: + tokenizer: The tokenizer to use. + image_encoder: The image encoder to use if any. + """ + + tokenizer: Tokenizer + image_encoder: Optional[ImageEncoder] + audio_encoder: Optional[AudioEncoder] + + def __init__( + self, tokenizer: Tokenizer, image_encoder: Optional[ImageEncoder], audio_encoder: Optional[AudioEncoder] + ) -> None: + r"""Initialize the instruct tokenizer. + + Args: + tokenizer: The tokenizer to use. + image_encoder: The image encoder to use if any. + audio_encoder: The audio encoder to use if any. + """ + + @abstractmethod + def encode_instruct(self, request: InstructRequestType) -> TokenizedType: + r"""Instruct request to Tokenized object + + Args: + request: The instruct request to encode. + + Returns: + The tokenized instruct request. + """ + + @abstractmethod + def encode_transcription(self, request: TranscriptionRequest) -> TokenizedType: + r""" + Encodes an audio transcription request into a tokenized format. + + This method processes a transcription request containing audio data, + encodes the user message, and returns the tokenized output. + + Args: + request: The transcription request object containing + the audio data to be encoded. + + Returns: + Tokenized: The tokenized representation of the audio data, including processed audio and tokens + """ + ... + + @abstractmethod + def decode(self, tokens: List[int], special_token_policy: Optional[SpecialTokenPolicy] = None) -> str: + r"""Convert token ids to string + + Args: + tokens: The token ids to decode. + special_token_policy: The policy to use for special tokens. + Passing `None` will default to `self._special_token_policy` for + [Tekkenizer][mistral_common.tokens.tokenizers.tekken.Tekkenizer] and `SpecialTokenPolicy.IGNORE` + for [SentencePieceTokenizer][mistral_common.tokens.tokenizers.sentencepiece.SentencePieceTokenizer]. + Note that passing `None` will be deprecated and `special_token_policy` will default to + `SpecialTokenPolicy.IGNORE` in `mistral_common=1.10.0`. + + Returns: + The decoded string. + """ + + @abstractmethod + def encode_fim(self, request: FIMRequestType) -> TokenizedType: + r"""FIM request to Tokenized object + + Args: + request: The FIM request to encode. + + Returns: + The tokenized FIM request. + """ + + @abstractmethod + def encode_user_message( + self, + message: UserMessage, + available_tools: Optional[List[Tool]], + is_last: bool, + is_first: bool, + system_prompt: Optional[str] = None, + force_img_first: bool = False, + ) -> Tuple[List[int], List[np.ndarray], List[Audio]]: + r"""Encode a user message. + + Args: + message: The user message to encode. + available_tools: The available tools. + is_last: Whether the message is the last one. + is_first: Whether the message is the first one. + system_prompt: The system prompt. + force_img_first: Whether to force the image to be first. + + Returns: + The encoded tokens and images. + """ + ... + + @abstractmethod + def encode_user_content( + self, + content: Union[str, List[UserContentChunk]], + is_last: bool, + system_prompt: Optional[str] = None, + force_img_first: bool = False, + ) -> Tuple[List[int], List[np.ndarray], List[Audio]]: + r"""Encode a user content. + + Args: + content: The user content to encode. + is_last: Whether the content is the last one. + system_prompt: The system prompt. + force_img_first: Whether to force the image to be first. + + Returns: + The encoded tokens and images. + """ + ... + + @abstractmethod + def _to_string(self, tokens: List[int]) -> str: ... diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/image.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/image.py new file mode 100644 index 0000000000000000000000000000000000000000..0d4e86c23472dead8ecfd25a80f8b58371257cde --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/image.py @@ -0,0 +1,239 @@ +import base64 +import logging +from dataclasses import dataclass +from enum import Enum +from io import BytesIO +from typing import List, Tuple, Union + +import numpy as np +from PIL import Image + +from mistral_common.image import SerializableImage, download_image +from mistral_common.protocol.instruct.messages import ImageChunk, ImageURLChunk + +logger = logging.getLogger(__name__) + + +_cv2_installed: bool +try: + import cv2 + + _cv2_installed = True +except ImportError: + _cv2_installed = False +except Exception as e: + # cv2 has lots of import problems: https://github.com/opencv/opencv-python/issues/884 + # for better UX, let's simply skip all errors that might arise from import for now + logger.warning( + f"Warning: Your installation of OpenCV appears to be broken: {e}." + "Please follow the instructions at https://github.com/opencv/opencv-python/issues/884 " + "to correct your environment. The import of cv2 has been skipped." + ) + + +def is_cv2_installed() -> bool: + r"""Check if OpenCV is installed.""" + return _cv2_installed + + +@dataclass +class ImageEncoding: + """A tokenized image. + + Attributes: + tokens: The token ids. + image: The image as a numpy array. + + Examples: + >>> import numpy as np + >>> image_encoding = ImageEncoding(tokens=[1, 2, 3], image=np.array([[0., 0.5, 1.]])) + """ + + tokens: List[int] + image: np.ndarray + + +@dataclass +class SpecialImageIDs: + """Special image tokens ids. + + Attributes: + img: The image token id. + img_break: The image break token id. + img_end: The image end token id. + + Examples: + >>> special_image_ids = SpecialImageIDs(img=1, img_break=2, img_end=3) + """ + + img: int + img_break: int + img_end: int + + +def image_from_chunk(chunk: Union[ImageURLChunk, ImageChunk]) -> SerializableImage: + r"""Get a serializable image from a chunk. + + Args: + chunk: The chunk to get the image from. + + Returns: + The image as a PIL Image object. + """ + if isinstance(chunk, ImageChunk): + return chunk.image + if chunk.get_url().startswith("data:image"): + data = chunk.get_url().split(",")[1] + image_data = base64.b64decode(data) + return Image.open(BytesIO(image_data)) + if chunk.get_url().startswith("file"): + return Image.open(open(chunk.get_url().replace("file://", ""), "rb")) + if chunk.get_url().startswith("http"): + return download_image(chunk.get_url()) + + raise RuntimeError(f"Unsupported image url scheme {chunk.get_url()}") + + +DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073) # RGB +DATASET_STD = (0.26862954, 0.26130258, 0.27577711) # RGB + + +# only relevant for spm +class MultiModalVersion(str, Enum): + r"""Version of the image tokenizer.""" + + m1 = "m1" + + @property + def config(self) -> "ImageConfig": + if self.name == "m1": + return ImageConfig(16, 1024) + + raise NotImplementedError(f"{self.name}") + + +@dataclass +class ImageConfig: + r"""Configuration for the image tokenizers.""" + + image_patch_size: int + max_image_size: int + spatial_merge_size: int = 1 + + +def _convert_to_rgb(image: Image.Image) -> Image.Image: + r"""Convert a PIL image to RGB. + + We ensure transparent background becomes white. + """ + if image.mode == "RGB": + return image + if image.mode != "RGBA": + image = image.convert("RGBA") + white_bg: Image.Image = Image.new("RGBA", image.size, "WHITE") + white_bg.paste(image, (0, 0), image) + return white_bg.convert("RGB") + + +def normalize( + np_image: np.ndarray, + mean: Tuple[float, float, float], + std: Tuple[float, float, float], +) -> np.ndarray: + r"""Normalize a tensor image with mean and standard deviation. + + Args: + np_image: Image to be normalized. + mean: Mean for each channel. + std: Standard deviation for each channel. + + Returns: + Normalized image with shape (C, H, W). + """ + np_image = np_image / 255.0 + + assert len(np_image.shape) == 3, f"{np_image.shape=}" + assert np_image.shape[2] == len(mean) == len(std), f"{np_image.shape=}, {mean=}, {std=}" + + np_image = (np_image - mean) / std + + return np_image.transpose(2, 0, 1) + + +def transform_image(image: Image.Image, new_size: Tuple[int, int]) -> np.ndarray: + r"""Transform an image to a numpy array with the given size. + + Args: + image: Image to be transformed. + new_size: New size of the image. + + Returns: + Transformed image with shape (C, H, W). + """ + if not is_cv2_installed(): + raise ImportError("OpenCV is required for this function. Install it with 'pip install mistral-common[opencv]'") + + np_image = cv2.resize(np.array(_convert_to_rgb(image), dtype=np.float32), new_size, interpolation=cv2.INTER_CUBIC) + return normalize(np_image, DATASET_MEAN, DATASET_STD) + + +class ImageEncoder: + r"""Image encoder for the image tokenizer.""" + + def __init__(self, image_config: ImageConfig, special_ids: SpecialImageIDs) -> None: + r"""Initialize the image encoder. + + Args: + image_config: Configuration for the image tokenizer. + special_ids: Special image tokens ids. + """ + self.image_config = image_config + self.special_ids = special_ids + + @property + def mm_config(self) -> ImageConfig: + # this property is deprecated, use image_config instead + # TODO(Patrick) - throw deprecation warning once + # changes implemented into vLLM and transformers + return self.image_config + + def _image_to_num_tokens(self, img: Image.Image) -> Tuple[int, int]: + w: Union[int, float] + h: Union[int, float] + + w, h = img.size + ratio = max(h / self.image_config.max_image_size, w / self.image_config.max_image_size) + if ratio > 1: + w = round(w / ratio) + h = round(h / ratio) + + width_tokens = (w - 1) // (self.image_config.image_patch_size * self.image_config.spatial_merge_size) + 1 + height_tokens = (h - 1) // (self.image_config.image_patch_size * self.image_config.spatial_merge_size) + 1 + + return width_tokens, height_tokens + + def __call__(self, content: Union[ImageChunk, ImageURLChunk]) -> ImageEncoding: + r"""Converts an image chunk to an image encoding. + + Args: + content: image chunk to be converted. + + Returns: + Image encoding. + """ + image = image_from_chunk(content) + w, h = self._image_to_num_tokens(image) + assert w > 0 + assert h > 0 + image_tokens = ([self.special_ids.img] * w + [self.special_ids.img_break]) * h + image_tokens[-1] = self.special_ids.img_end + new_image_size = ( + w * self.image_config.image_patch_size * self.image_config.spatial_merge_size, + h * self.image_config.image_patch_size * self.image_config.spatial_merge_size, + ) + processed_image = transform_image(image, new_image_size) + return ImageEncoding(tokens=image_tokens, image=processed_image) + + @property + def image_token(self) -> int: + return self.special_ids.img diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/instruct.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/instruct.py new file mode 100644 index 0000000000000000000000000000000000000000..b43f92120818dbdbe2838ce693c0cd5b32de2912 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/instruct.py @@ -0,0 +1,1155 @@ +import json +from abc import abstractmethod +from typing import Any, Dict, Generic, List, Optional, Sequence, Tuple, Union, overload + +import numpy as np + +from mistral_common.audio import Audio +from mistral_common.exceptions import ( + InvalidAssistantMessageException, + InvalidMessageStructureException, + TokenizerException, +) +from mistral_common.protocol.fim.request import FIMRequest +from mistral_common.protocol.instruct.messages import ( + UATS, + AssistantMessage, + AssistantMessageType, + AudioChunk, + AudioURLChunk, + ContentChunk, + ImageChunk, + ImageURLChunk, + SystemMessage, + TextChunk, + ThinkChunk, + ToolMessage, + UserContentChunk, + UserMessage, +) +from mistral_common.protocol.instruct.request import InstructRequest +from mistral_common.protocol.instruct.tool_calls import Tool, ToolCall +from mistral_common.protocol.transcription.request import TranscriptionRequest +from mistral_common.tokens.tokenizers.audio import AudioEncoder +from mistral_common.tokens.tokenizers.base import ( + FIMRequestType, + InstructRequestType, + InstructTokenizer, + SpecialTokenPolicy, + SpecialTokens, + Tokenized, + TokenizedType, + Tokenizer, + UserMessagePosition, +) +from mistral_common.tokens.tokenizers.image import ImageEncoder +from mistral_common.tokens.tokenizers.tekken import Tekkenizer + + +class InstructTokenizerBase( + InstructTokenizer, Generic[InstructRequestType, FIMRequestType, TokenizedType, AssistantMessageType] +): + r"""Base instruct tokenizer.""" + + def __init__( + self, + tokenizer: Tokenizer, + image_encoder: Optional[ImageEncoder] = None, + audio_encoder: Optional[AudioEncoder] = None, + ): + r"""Initialize the instruct tokenizer. + + Args: + tokenizer: The tokenizer to use. + image_encoder: The image encoder to use if any. + audio_encoder: The audio encoder to use. + """ + self.tokenizer = tokenizer + self.image_encoder = image_encoder + self.audio_encoder = audio_encoder + super().__init__(tokenizer, image_encoder, audio_encoder) + + @property + def mm_encoder(self) -> Optional[ImageEncoder]: + # this funtion is deprecated, use image_encoder instead + # TODO(Patrick) - throw a deprecation warning once + # changes applied to vllm and transformers + return self.image_encoder + + def start(self) -> List[int]: + r"""Return the start tokens.""" + return [self.tokenizer.bos_id] + + @staticmethod + def find_first_last_user(request: InstructRequest) -> Tuple[int, int]: + r"""Find the first and last user message in the request. + + Args: + request: The request to search for user messages. + + Returns: + The index of the first and last user message. + """ + last_user_idx = -1 + first_user_idx = -1 + for i, msg in list(enumerate(request.messages)): + if isinstance(msg, UserMessage): + if first_user_idx == -1: + first_user_idx = i + last_user_idx = i + return first_user_idx, last_user_idx + + @abstractmethod + def encode_tool_message(self, message: ToolMessage, is_before_last_user_message: bool) -> List[int]: + r"""Encode a tool message. + + Raises: + NotImplementedError: The tool message is not implemented for the base tokenizer. + """ + raise NotImplementedError("Tool message not implemented") + + @abstractmethod + def encode_assistant_message( + self, message: AssistantMessageType, is_before_last_user_message: bool, continue_message: bool + ) -> List[int]: + r"""Encode an assistant message. + + Raises: + NotImplementedError: The assistant message is not implemented for the base tokenizer. + """ + raise NotImplementedError("Assistant message not implemented") + + @abstractmethod + def encode_think(self, chunk: ThinkChunk) -> List[int]: + r"""Encode a think chunk. + + Raises: + NotImplementedError: The think chunk is not implemented for the base tokenizer. + """ + raise NotImplementedError("Think chunk not implemented") + + def _truncate_for_max_tokens( + self, + tokenized: List[Optional[List[int]]], + messages: List[AssistantMessageType], + max_tokens: int, + last_user_message_index: int, + ) -> None: + # Tokenizer ⩽ V3 does not support truncation + return + + @classmethod + def validate_messages(cls, messages: List[UATS]) -> None: + # for v7 we start validates messages + ... + + def encode_instruct( + self, + request: InstructRequest[AssistantMessageType, Tool], + ) -> Tokenized: + r"""Encode an instruct request. + + Args: + request: The request to encode. + + Returns: + The encoded tokens. + """ + # init at bos + images: List[np.ndarray] = [] + audios: List[Audio] = [] + prefix_ids: Optional[List[int]] = None + tokens_list: List[Optional[List[int]]] = [] + + # validate messages + self.validate_messages(request.messages) + + # find last user message + first_user_idx, last_user_idx = self.find_first_last_user(request) + for msg_idx, msg in enumerate(request.messages): + if ( + request.continue_final_message + and (msg_idx == len(request.messages) - 1) + and not isinstance(msg, AssistantMessage) + ): + raise InvalidMessageStructureException( + "Cannot continue final message if it is not an assistant message" + ) + if isinstance(msg, UserMessage): + new_tokens, new_images, new_audios = self.encode_user_message( + msg, + request.available_tools, + msg_idx == last_user_idx, + msg_idx == first_user_idx, + system_prompt=request.system_prompt, + force_img_first=True, # img is always first when providing text/img chunk pair + ) + images.extend(new_images) + audios.extend(new_audios) + elif isinstance(msg, ToolMessage): + new_tokens = self.encode_tool_message(msg, msg_idx < last_user_idx) + elif isinstance(msg, AssistantMessage): + continue_message = request.continue_final_message and (msg_idx == len(request.messages) - 1) + + new_tokens = self.encode_assistant_message( + msg, msg_idx < last_user_idx, continue_message=continue_message + ) + if msg_idx == len(request.messages) - 1: + prefix_ids = new_tokens + elif isinstance(msg, SystemMessage): + new_tokens = self.encode_system_message(msg) + else: + raise TokenizerException(f"Unknown message type {type(msg)}") + + tokens_list.append(new_tokens) + + if request.truncate_at_max_tokens is not None: + self._truncate_for_max_tokens( + tokens_list, + request.messages, + request.truncate_at_max_tokens, + last_user_idx, + ) + tokens = self.start() + + for tok in tokens_list: + if tok is not None: + tokens.extend(tok) + + return Tokenized( + tokens=tokens, + text=self.decode(tokens, special_token_policy=SpecialTokenPolicy.KEEP), + prefix_ids=prefix_ids, + images=images, + audios=audios, + ) + + def decode(self, tokens: List[int], special_token_policy: Optional[SpecialTokenPolicy] = None) -> str: + r"""Decode tokens to a string. + + Args: + tokens: The tokens to decode. + special_token_policy: The policy to use for special tokens. + Passing `None` will default to `self._special_token_policy` for + [Tekkenizer][mistral_common.tokens.tokenizers.tekken.Tekkenizer] and `SpecialTokenPolicy.IGNORE` + for [SentencePieceTokenizer][mistral_common.tokens.tokenizers.sentencepiece.SentencePieceTokenizer]. + Note that passing `None` will be deprecated and `special_token_policy` will default to + `SpecialTokenPolicy.IGNORE` in `mistral_common=1.10.0`. + + Returns: + The decoded string. + """ + return self.tokenizer.decode(tokens, special_token_policy=special_token_policy) + + def _to_string(self, tokens: List[int]) -> str: + return self.tokenizer._to_string(tokens) + + +class InstructTokenizerV1( + InstructTokenizerBase, Generic[InstructRequestType, FIMRequestType, TokenizedType, AssistantMessageType] +): + r"""Instruct tokenizer V1. + + This tokenizer has basic for messages. It does not support tools or image inputs. + """ + + def encode_user_message( + self, + message: UserMessage, + available_tools: Optional[List[Tool]], + is_last: bool, + is_first: bool, + system_prompt: Optional[str] = None, + force_img_first: bool = False, + ) -> Tuple[List[int], List[np.ndarray], List[Audio]]: + r"""Encode a user message. + + Args: + message: The message to encode. + available_tools: Not used. + is_last: Not used. + is_first: Whether the message is the first one. + system_prompt: The system prompt. + force_img_first: Not used. + + Returns: + The encoded tokens and empty list. + """ + assert isinstance(message.content, str), "Message content must be normalized" + assert self.image_encoder is None, "InstructTokenizerV1 cannot encode images" + + content = "" + if is_first and system_prompt: + content = system_prompt + "\n\n" + message.content + else: + content = message.content + + message_txt = f"[INST] {content} [/INST]" + curr_tokens, image, audio = self.encode_user_content(content=message_txt, is_last=False, system_prompt=None) + return curr_tokens, image, audio + + def encode_system_message(self, message: SystemMessage) -> List[int]: + raise NotImplementedError(f"System message encoding not implemented for {self.__class__.__name__}") + + def encode_user_content( + self, + content: Union[str, List[UserContentChunk]], + is_last: bool, + system_prompt: Optional[str] = None, + force_img_first: bool = False, + ) -> Tuple[List[int], List[np.ndarray], List[Audio]]: + r"""Encode a user content. + + Args: + content: The content to encode. + is_last: Whether the message is the last one. + system_prompt: The system prompt. + force_img_first: Not used. + + Returns: + The encoded tokens and empty list. + """ + assert isinstance(content, str) + + if is_last and system_prompt: + content = system_prompt + "\n\n" + content + + tokens = self.tokenizer.encode(content, bos=False, eos=False) + return tokens, [], [] + + def encode_tool_message(self, message: ToolMessage, is_before_last_user_message: bool) -> List[int]: + r"""Encode a tool message. + + Raises: + TokenizerException: The tool message is not implemented for this version. + """ + raise TokenizerException("Tools not implemented for tokenizer V1") + + def encode_assistant_message( + self, message: AssistantMessageType, is_before_last_user_message: bool, continue_message: bool + ) -> List[int]: + r"""Encode an assistant message. + + Args: + message: The message to encode. + is_before_last_user_message: Not used. + continue_message: Whether to continue the message generation. + Only use this if the assistant message is the last message. + + Returns: + The encoded tokens. + """ + assert isinstance(message, AssistantMessage), message + if message.tool_calls is not None and len(message.tool_calls) > 0: + raise TokenizerException("Tools not implemented for tokenizer V1") + if continue_message and message.prefix: + raise InvalidAssistantMessageException( + "`continue_message` is only supported for assistant messages that have `prefix=False`." + ) + elif message.content: + assert isinstance(message.content, str), "Message content must be a string for tokenizer < V13" + curr_tokens = self.tokenizer.encode(message.content, bos=False, eos=False) + else: + raise TokenizerException(f"{message.content} // {message.tool_calls}") + if not message.prefix and not continue_message: + curr_tokens.append(self.tokenizer.eos_id) + return curr_tokens + + def encode_think(self, chunk: ThinkChunk) -> List[int]: + r"""Encode a think chunk. + + Raises: + TokenizerException: The think chunk is not implemented for this version. + """ + raise TokenizerException("Think not implemented for tokenizer < V13.") + + def encode_fim(self, request: FIMRequest) -> Tokenized: + r"""Encode a FIM request. + + Raises: + TokenizerException: The FIM request is not implemented for this version. + """ + raise TokenizerException(f"FIM not available for {self.tokenizer.version}") + + def encode_transcription(self, request: TranscriptionRequest) -> Tokenized: + raise TokenizerException(f"Transcription not available for {self.tokenizer.version}") + + +class InstructTokenizerV2( + InstructTokenizerV1, Generic[InstructRequestType, FIMRequestType, TokenizedType, AssistantMessageType] +): + r"""Instruct tokenizer V2. + + This tokenizer adds supports to images, tools and FIM requests. + """ + + _user_message_position_to_encode_tools = UserMessagePosition.last + + def __init__( + self, + tokenizer: Tokenizer, + image_encoder: Optional[ImageEncoder] = None, + audio_encoder: Optional[AudioEncoder] = None, + ): + r"""Initialize the tokenizer. + + Args: + tokenizer: The tokenizer to use. + image_encoder: The image encoder to use. + audio_encoder: The audio encoder to use. + """ + super().__init__(tokenizer, image_encoder, audio_encoder) + self.BEGIN_INST = self.tokenizer.get_control_token(SpecialTokens.begin_inst.value) + self.END_INST = self.tokenizer.get_control_token(SpecialTokens.end_inst.value) + self.BEGIN_AVAILABLE_TOOLS = self.tokenizer.get_control_token(SpecialTokens.begin_tools.value) + self.END_AVAILABLE_TOOLS = self.tokenizer.get_control_token(SpecialTokens.end_tools.value) + self.BEGIN_TOOL_RESULTS = self.tokenizer.get_control_token(SpecialTokens.begin_tool_results.value) + self.END_TOOL_RESULTS = self.tokenizer.get_control_token(SpecialTokens.end_tool_results.value) + self.TOOL_CALLS = self.tokenizer.get_control_token(SpecialTokens.tool_calls.value) + self.BOS = self.tokenizer.get_control_token(SpecialTokens.bos.value) + self.PREFIX = self.tokenizer.get_control_token(SpecialTokens.prefix.value) + self.SUFFIX = self.tokenizer.get_control_token(SpecialTokens.suffix.value) + + def encode_user_message( + self, + message: UserMessage, + available_tools: Optional[List[Tool]], + is_last: bool, + is_first: bool, + system_prompt: Optional[str] = None, + force_img_first: bool = False, + ) -> Tuple[List[int], List[np.ndarray], List[Audio]]: + r"""Encode a user message. + + Args: + message: The message to encode. + available_tools: The list of available tools if any. + is_last: Whether the message is the last one. + is_first: Not used. + system_prompt: The system prompt. + force_img_first: Whether to force the image to be first. + + Returns: + The encoded tokens and the list of images. + """ + do_encode_tools = False + do_encode_tools |= is_first and (self._user_message_position_to_encode_tools == UserMessagePosition.first) + do_encode_tools |= is_last and (self._user_message_position_to_encode_tools == UserMessagePosition.last) + tools_tokens: List[int] = [] + + if do_encode_tools and available_tools: + tools = [tool.model_dump() for tool in available_tools] + tools_json_tokens = self.tokenizer.encode(json.dumps(tools, ensure_ascii=False), bos=False, eos=False) + tools_tokens = [ + self.BEGIN_AVAILABLE_TOOLS, + *tools_json_tokens, + self.END_AVAILABLE_TOOLS, + ] + + tokens, image, audio = self.encode_user_content( + content=message.content, + is_last=is_last, + system_prompt=system_prompt, + force_img_first=force_img_first, + ) + + prefix_tokens = [*tools_tokens, self.BEGIN_INST] + suffix_tokens = [self.END_INST] + + curr_tokens = prefix_tokens + tokens + suffix_tokens + + return curr_tokens, image, audio + + def _parse_json_content(self, content: str) -> Any: + try: + return json.loads(content) + except json.JSONDecodeError: + return content + + def _prepare_tool_result(self, tool_message: ToolMessage) -> Dict[str, Any]: + r"""Bit of a hack due to the way tool results are tokenized.""" + return { + "name": tool_message.name, + "content": self._parse_json_content(tool_message.content), + } + + def encode_tool_message(self, message: ToolMessage, is_before_last_user_message: bool) -> List[int]: + r"""Encode a tool message. + + Args: + message: The message to encode. + is_before_last_user_message: Whether the message is before the last user message. If true, the message is + not encoded. + + Returns: + The encoded tokens. + """ + if is_before_last_user_message: + # don't tokenize last tool response before last user msg + return [] + + # Currently only supports single tool results + tool_result_str = json.dumps([self._prepare_tool_result(message)], ensure_ascii=False) + curr_tokens = [ + self.BEGIN_TOOL_RESULTS, + *self.tokenizer.encode(tool_result_str, bos=False, eos=False), + self.END_TOOL_RESULTS, + ] + return curr_tokens + + def _prepare_function_call(self, tool_call: ToolCall) -> Dict[str, Any]: + r"""Bit of a hack due to the way function calls are tokenized.""" + return { + "name": tool_call.function.name, + "arguments": self._parse_json_content(tool_call.function.arguments), + } + + def _encode_normal_content_assistant_message(self, message: AssistantMessageType) -> List[int]: + assert message.content, f"Assistant message must have content. Got {message}" + assert isinstance(message.content, str), "Message content must be a string for tokenizer < V7" + return self.tokenizer.encode(message.content.rstrip(" "), bos=False, eos=False) + + def _encode_tool_calls_in_assistant_message(self, message: AssistantMessageType) -> List[int]: + assert message.tool_calls, f"Assistant message must have tool calls. Got {message}" + prepared_tool_calls = [] + for tool_call in message.tool_calls: + prepared_tool_calls.append(self._prepare_function_call(tool_call)) + tool_call_str = json.dumps(prepared_tool_calls, ensure_ascii=False) + curr_tokens = [ + self.TOOL_CALLS, + *self.tokenizer.encode(tool_call_str, bos=False, eos=False), + ] + return curr_tokens + + def encode_assistant_message( + self, message: AssistantMessageType, is_before_last_user_message: bool, continue_message: bool + ) -> List[int]: + r"""Encode an assistant message. + + Args: + message: The message to encode. + is_before_last_user_message: Whether the message is before the last user message. If has tools and true, the + message is not encoded. + continue_message: Whether to continue the message generation. + Only use this if the assistant message is the last message. + + Returns: + The encoded tokens. + """ + if message.tool_calls and message.content: + raise ValueError(f"Cannot have tool calls and content defined in the same assistant message {message}") + if continue_message and message.prefix: + raise InvalidAssistantMessageException( + "`continue_message` is only supported for assistant messages that have `prefix=False`." + ) + + if message.tool_calls: + if is_before_last_user_message: + # don't tokenize tool call before last user message + return [] + curr_tokens = self._encode_tool_calls_in_assistant_message(message) + elif message.content: + assert isinstance(message.content, str), "Message content must be a string for tokenizer < V7" + curr_tokens = self._encode_normal_content_assistant_message(message) + else: + raise TokenizerException(f"Invalid assistant message: {message.content}") + if not message.prefix and not continue_message: + curr_tokens.append(self.tokenizer.eos_id) + return curr_tokens + + def _encode_infilling(self, text: str) -> List[int]: + r"""Remove prefix space in the case of SentencePieceTokenizers.""" + + return self.tokenizer.encode("☺" + text, bos=False, eos=False)[2:] + + def encode_fim(self, request: FIMRequest) -> Tokenized: + r"""Encode a FIM request. + + Args: + request: The request to encode. + + Returns: + The encoded tokens. + """ + prefix_tokens = self.tokenizer.encode(request.prompt, bos=False, eos=False) + suffix_tokens = self._encode_infilling(request.suffix) if request.suffix else [] + tokens = [ + self.BOS, + self.SUFFIX, + *suffix_tokens, + self.PREFIX, + *prefix_tokens, + ] + return Tokenized(tokens=tokens, text=self.decode(tokens, special_token_policy=SpecialTokenPolicy.KEEP)) + + +class InstructTokenizerV3( + InstructTokenizerV2, Generic[InstructRequestType, FIMRequestType, TokenizedType, AssistantMessageType] +): + r"""Instruct tokenizer V3. + + The only difference with V2 tokenizer is that it encodes the tool messages differently. + """ + + def __init__( + self, + tokenizer: Tokenizer, + image_encoder: Optional[ImageEncoder] = None, + audio_encoder: Optional[AudioEncoder] = None, + ): + r"""Initialize the tokenizer. + + Args: + tokenizer: The tokenizer to use. + image_encoder: The image encoder to use. + audio_encoder: The audio encoder to use. + """ + super().__init__(tokenizer, image_encoder=image_encoder, audio_encoder=audio_encoder) + + def _prepare_function_call(self, tool_call: ToolCall) -> Dict[str, Any]: + function_call = { + "name": tool_call.function.name, + "arguments": self._parse_json_content(tool_call.function.arguments), + } + + if tool_call.id and tool_call.id != "null": + function_call["id"] = tool_call.id + + return function_call + + def _prepare_tool_result(self, tool_message: ToolMessage) -> Dict[str, Any]: + assert tool_message.tool_call_id is not None, "Tool message has to have the tool call id defined in v3" + + return { + "content": self._parse_json_content(tool_message.content), + "call_id": tool_message.tool_call_id, + } + + def encode_tool_message(self, message: ToolMessage, is_before_last_user_message: bool) -> List[int]: + r"""Encode a tool message. + + Note: + Same as [V2][mistral_common.tokens.tokenizers.instruct.InstructTokenizerV2.encode_tool_message] but tools + are not wrapped in a list and the history is also tokenized. + + Args: + message: The message to encode. + is_before_last_user_message: Whether the message is before the last user message. If true, the message is + not encoded. + + Returns: + The encoded tokens. + """ + tool_result_str = json.dumps(self._prepare_tool_result(message), ensure_ascii=False) + curr_tokens = [ + self.BEGIN_TOOL_RESULTS, + *self.tokenizer.encode(tool_result_str, bos=False, eos=False), + self.END_TOOL_RESULTS, + ] + return curr_tokens + + def encode_assistant_message( + self, message: AssistantMessageType, is_before_last_user_message: bool, continue_message: bool + ) -> List[int]: + r"""Encode an assistant message. + + Note: + Same as [V2][mistral_common.tokens.tokenizers.instruct.InstructTokenizerV2.encode_assistant_message] but + always encode the tool history. + continue_message: Whether to continue the message generation. + Only use this if the assistant message is the last message. + + Args: + message: The message to encode. + is_before_last_user_message: Not used. + + Returns: + The encoded tokens. + """ + return super().encode_assistant_message(message, False, continue_message) + + @overload + def _encode_content_chunk(self, chunk: Union[str, TextChunk, ThinkChunk]) -> Tuple[List[int], None, None]: ... + @overload + def _encode_content_chunk(self, chunk: Union[ImageChunk, ImageURLChunk]) -> Tuple[List[int], np.ndarray, None]: ... + @overload + def _encode_content_chunk(self, chunk: Union[AudioChunk, AudioURLChunk]) -> Tuple[List[int], None, Audio]: ... + def _encode_content_chunk( + self, chunk: Union[str, ContentChunk] + ) -> Union[Tuple[List[int], Optional[np.ndarray], Optional[Audio]]]: + if isinstance(chunk, str): + return self.tokenizer.encode(chunk, bos=False, eos=False), None, None + elif isinstance(chunk, TextChunk): + return self.tokenizer.encode(chunk.text, bos=False, eos=False), None, None + elif isinstance(chunk, ThinkChunk): + return self.encode_think(chunk), None, None + elif isinstance(chunk, (ImageChunk, ImageURLChunk)): + assert self.image_encoder is not None, "Make sure to define a image encoder at init" + img_encoding = self.image_encoder(chunk) + + return img_encoding.tokens, img_encoding.image, None + + elif isinstance(chunk, (AudioChunk, AudioURLChunk)): + # the following is only possible for >= v7 + assert self.audio_encoder is not None, "Make sure to define a audio encoder at init" + audio_encoding = self.audio_encoder(chunk) + + return audio_encoding.tokens, None, audio_encoding.audio + else: + raise ValueError(f"Unknown chunk type: {chunk}") + + def _encode_content_chunks( + self, content: Sequence[ContentChunk] + ) -> Tuple[List[int], List[np.ndarray], List[Audio]]: + tokens: List[int] = [] + images: List[np.ndarray] = [] + audio: List[Audio] = [] + + for chunk in content: + chunk_tokens, maybe_image, maybe_audio = self._encode_content_chunk(chunk) + tokens.extend(chunk_tokens) + if maybe_image is not None: + images.append(maybe_image) + if maybe_audio is not None: + audio.append(maybe_audio) + return tokens, images, audio + + def encode_user_content( + self, + content: Union[str, List[UserContentChunk]], + is_last: bool, + system_prompt: Optional[str] = None, + force_img_first: bool = False, + ) -> Tuple[List[int], List[np.ndarray], List[Audio]]: + r"""Encode a user content. + + Args: + content: The content to encode. + is_last: Whether the message is the last one. + system_prompt: The system prompt. + force_img_first: Whether to force the image to be first. + + Returns: + The encoded tokens and the images. + """ + if isinstance(content, str): + return super().encode_user_content(content, is_last, system_prompt) + + tokens: List[int] = [] + images: List[np.ndarray] = [] + audio: List[Audio] = [] + + has_one_img_one_text_first = len(content) == 2 and isinstance(content[1], (ImageChunk, ImageURLChunk)) + if force_img_first and has_one_img_one_text_first: + # make sure that if exactly one image and text chunk are passed we force the image chunk to be first + content = [content[1], content[0]] + + first_chunk = True + for chunk in content: + content_str = "" + if first_chunk and is_last and system_prompt: + first_chunk = False + content_str = system_prompt + "\n\n" + tokens += self.tokenizer.encode(content_str, bos=False, eos=False) + + if isinstance(chunk, (AudioChunk, AudioURLChunk)): + assert not content_str, ( + f"It is not possible that `content` is non-empty when chunk is of type {type(chunk)}." + ) + chunk_tokens, _, chunk_audio = self._encode_content_chunk(chunk) + audio.append(chunk_audio) + elif isinstance(chunk, (ImageChunk, ImageURLChunk)): + chunk_tokens, chunk_image, _ = self._encode_content_chunk(chunk) + images.append(chunk_image) + else: + chunk_tokens = self._encode_content_chunk(chunk)[0] + tokens.extend(chunk_tokens) + + return tokens, images, audio + + +class InstructTokenizerV7(InstructTokenizerV3): + r"""Instruct tokenizer V7. + + The difference with V3 tokenizer is that it encodes the system prompts differently: + - in V7 the system prompts are treated as separate SystemMessages + - they are no longer prepended to the last user message + - they are printed between special tokens + + """ + + def __init__( + self, + tokenizer: Tokenizer, + image_encoder: Optional[ImageEncoder] = None, + audio_encoder: Optional[AudioEncoder] = None, + ) -> None: + r"""Initialize the tokenizer. + + Args: + tokenizer: The tokenizer to use. + image_encoder: The image encoder to use. + audio_encoder: The audio encoder to use. + """ + + super().__init__(tokenizer, image_encoder, audio_encoder) + self.BEGIN_SYSTEM = self.tokenizer.get_control_token(SpecialTokens.begin_system.value) + self.END_SYSTEM = self.tokenizer.get_control_token(SpecialTokens.end_system.value) + self.BEGIN_TOOL_CONTENT = self.tokenizer.get_control_token(SpecialTokens.begin_tool_content.value) + + self.TRANSCRIBE = None + if audio_encoder is not None: + self.TRANSCRIBE = self.tokenizer.get_control_token(SpecialTokens.transcribe.value) + + def _truncate_for_max_tokens( + self, + tokenized_messages: List[Optional[List[int]]], + messages: List[AssistantMessageType], + max_tokens: int, + last_user_message_index: int, + ) -> None: + # drop some messages to fit in max_tokens. Rules: + # - don't drop any system messages + # - when a user message is dropped, all following assistant|tool message should be dropped until the next + # user message + # - we never drop the last message + to_drop = sum(len(t) for t in tokenized_messages if t is not None) - max_tokens + + def drop(idx: int) -> None: + nonlocal to_drop + if isinstance(messages[idx], SystemMessage): + # never drop system messages + return + if idx == last_user_message_index: + # never drop the last user message + return + tok = tokenized_messages[idx] + assert tok is not None + to_drop -= len(tok) + tokenized_messages[idx] = None + + current_idx = 0 + while to_drop > 0 and current_idx < len(messages): + drop(current_idx) + current_idx += 1 + if isinstance(messages[current_idx - 1], UserMessage): + # if we just dropped a UserMessage, + # also drop everything until the next user message + while current_idx < len(messages) and not isinstance(messages[current_idx], UserMessage): + drop(current_idx) + current_idx += 1 + + if to_drop > 0: + raise TokenizerException("Input couldn't fit in truncate_at_max_token") + + def encode_system_message(self, message: SystemMessage) -> List[int]: + r"""Encode a system message. + + Args: + message: The message to encode. + + Returns: + The encoded tokens. + """ + + tokens = [self.BEGIN_SYSTEM] + if isinstance(content := message.content, str): + content = [TextChunk(text=content)] + tokens += self._encode_content_chunks(content)[0] + tokens.append(self.END_SYSTEM) + return tokens + + def encode_user_content( + self, + content: Union[str, List[UserContentChunk]], + is_last: bool, + system_prompt: Optional[str] = None, + force_img_first: bool = False, + ) -> Tuple[List[int], List[np.ndarray], List[Audio]]: + r"""Encode a user content. + + Args: + content: The content to encode. + is_last: Whether the message is the last one. + system_prompt: The system prompt. + force_img_first: Whether to force the image to be first. + + Returns: + The encoded tokens and the images. + """ + assert system_prompt is None, "in Tokenizer V7 we don't encode system prompts in user messages" + + if isinstance(content, str): + return super().encode_user_content(content, is_last, system_prompt) + + has_one_img_one_text_first = len(content) == 2 and isinstance(content[1], (ImageChunk, ImageURLChunk)) + if force_img_first and has_one_img_one_text_first: + # make sure that if exactly one image and text chunk are passed we force the image chunk to be first + content = [content[1], content[0]] + + tokens, images, audio = self._encode_content_chunks(content) + return tokens, images, audio + + def encode_user_message( + self, + message: UserMessage, + available_tools: Optional[List[Tool]], + is_last: bool, + is_first: bool, + system_prompt: Optional[str] = None, + force_img_first: bool = False, + ) -> Tuple[List[int], List[np.ndarray], List[Audio]]: + r"""Encode a user message. + + Args: + message: The message to encode. + available_tools: The list of available tools if any. + is_last: Whether the message is the last one. + is_first: Whether the message is the first one. + system_prompt: Not used. + force_img_first: Whether to force the image to be first. + + Returns: + The encoded tokens and the list of images. + """ + assert system_prompt is None, "in Tokenizer V7 we don't encode system prompts in user messages" + + tokens, images, audio = super().encode_user_message( + message, + available_tools, + is_last=is_last, + is_first=is_first, + system_prompt=None, + force_img_first=force_img_first, + ) + + return tokens, images, audio + + def encode_transcription(self, request: TranscriptionRequest) -> Tokenized: + r""" + Encodes an audio transcription request into a tokenized format. + + This method processes a transcription request containing audio data, + encodes the user message, and returns the tokenized output. + + Args: + request: The transcription request object containing + the audio data to be encoded. + + Returns: + Tokenized: The tokenized representation of the audio data, including processed audio and tokens + """ + + assert self.TRANSCRIBE is not None, f"{self.__class__.__name__} needs to have a TRANSCRIBE token" + prefix = self.start() + tokens, _, audio = self.encode_user_message( + UserMessage(content=[AudioChunk(input_audio=request.audio)]), + available_tools=[], + is_last=True, + is_first=True, + system_prompt=None, + ) + + tokens = [*prefix, *tokens] + if request.language is not None: + language_string = f"lang:{request.language}" # no space. + tokens += self.tokenizer.encode(language_string, bos=False, eos=False) + + tokens.append(self.TRANSCRIBE) + return Tokenized(tokens=tokens, text=self.tokenizer._to_string(tokens), audios=audio) + + @classmethod + def validate_messages(cls, messages: List[UATS]) -> None: + if cls._has_audio(messages): + if any(isinstance(message, SystemMessage) for message in messages): + raise ValueError("System messages are not yet allowed when audio is present") + + @staticmethod + def _has_audio(messages: List[UATS]) -> bool: + return any( + isinstance(message, UserMessage) + and isinstance(message.content, list) + and any(isinstance(chunk, AudioChunk) for chunk in message.content) + for message in messages + ) + + def encode_tool_message(self, message: ToolMessage, is_before_last_user_message: bool) -> List[int]: + r"""Encode a tool message. + + Note: + Same as [V3][mistral_common.tokens.tokenizers.instruct.InstructTokenizerV3.encode_tool_message] + but tools are not wrapped in a list and history is also tokenized + + Args: + message: The message to encode. + is_before_last_user_message: Not used. + + Returns: + The encoded tokens. + """ + assert message.tool_call_id is not None + assert isinstance(message.content, str), "Message content must be normalized" + tool_call_id_tokens = self.tokenizer.encode(message.tool_call_id, bos=False, eos=False) + tokens = self.tokenizer.encode(message.content, bos=False, eos=False) + + prefix_tokens = [ + self.BEGIN_TOOL_RESULTS, + *tool_call_id_tokens, + self.BEGIN_TOOL_CONTENT, + ] + curr_tokens = [ + *prefix_tokens, + *tokens, + self.END_TOOL_RESULTS, + ] + return curr_tokens + + def encode_assistant_message( + self, message: AssistantMessageType, is_before_last_user_message: bool, continue_message: bool + ) -> List[int]: + r"""Encode an assistant message. + + Args: + message: The message to encode. + is_before_last_user_message: Not used. + continue_message: Whether to continue the message generation. + Only use this if the assistant message is the last message. + + Returns: + The encoded tokens. + """ + if not message.content and not message.tool_calls: + raise TokenizerException(f"Invalid assistant message: {message}") + if continue_message and message.prefix: + raise InvalidAssistantMessageException( + "`continue_message` is only supported for assistant messages that have `prefix=False`." + ) + + curr_tokens: list = [] + if isinstance(message.content, str): + curr_tokens = self._encode_normal_content_assistant_message(message) + elif isinstance(message.content, list): + curr_tokens += self._encode_content_chunks(message.content)[0] + if message.tool_calls: + curr_tokens += self._encode_tool_calls_in_assistant_message(message) + if not message.prefix and not continue_message: + curr_tokens.append(self.tokenizer.eos_id) + + return curr_tokens + + +class InstructTokenizerV11(InstructTokenizerV7): + r"""Instruct tokenizer V11. + + The difference with V7 tokenizer is that it encodes tool calls differently: + Tool call results are encoded as : + - [begin tool call] call_name_tokens [call id] call_id_tokens [args] content tokens + """ + + def __init__( + self, + tokenizer: Tokenizer, + image_encoder: Optional[ImageEncoder] = None, + audio_encoder: Optional[AudioEncoder] = None, + ) -> None: + super().__init__(tokenizer, image_encoder, audio_encoder) + self.ARGS = self.tokenizer.get_control_token(SpecialTokens.args.value) + self.CALL_ID = self.tokenizer.get_control_token(SpecialTokens.call_id.value) + + def _encode_tool_calls_in_assistant_message(self, message: AssistantMessageType) -> List[int]: + assert message.tool_calls, f"Assistant message must have tool calls. Got {message}" + curr_tokens = [] + for tool_call in message.tool_calls: + prepared = self._prepare_function_call(tool_call) + + ids = [] + if "id" in prepared: + ids = [self.CALL_ID, *self.tokenizer.encode(prepared["id"], bos=False, eos=False)] + + curr_tokens += [ + self.TOOL_CALLS, + *self.tokenizer.encode(prepared["name"], bos=False, eos=False), + *ids, + self.ARGS, + *self.tokenizer.encode(json.dumps(prepared["arguments"], ensure_ascii=False), bos=False, eos=False), + ] + return curr_tokens + + +class InstructTokenizerV13(InstructTokenizerV11): + r"""Instruct tokenizer V13. + + The difference with V11 tokenizer is that it encodes tool calls differently: + - available tools are tokenized at the first user message. + - call id is no longer tokenized for tool calls or results. + """ + + _user_message_position_to_encode_tools = UserMessagePosition.first + + def __init__( + self, + tokenizer: Tokenizer, + image_encoder: Optional[ImageEncoder] = None, + audio_encoder: Optional[AudioEncoder] = None, + ) -> None: + super().__init__(tokenizer, image_encoder, audio_encoder) + assert isinstance(tokenizer, Tekkenizer), f"Tokenizer must be a Tekkenizer. Got {type(tokenizer)}" + if ( + SpecialTokens.begin_think.value in tokenizer._special_tokens_reverse_vocab + and SpecialTokens.end_think.value in tokenizer._special_tokens_reverse_vocab + ): + self.BEGIN_THINK: Optional[int] = tokenizer.get_control_token(SpecialTokens.begin_think.value) + self.END_THINK: Optional[int] = tokenizer.get_control_token(SpecialTokens.end_think.value) + else: + self.BEGIN_THINK = None + self.END_THINK = None + + def _encode_tool_calls_in_assistant_message(self, message: AssistantMessageType) -> List[int]: + assert message.tool_calls, f"Assistant message must have tool calls. Got {message}" + curr_tokens = [] + for tool_call in message.tool_calls: + assert tool_call.id and tool_call.id != "null" + prepared = self._prepare_function_call(tool_call) + + curr_tokens += [ + self.TOOL_CALLS, + *self.tokenizer.encode(prepared["name"], bos=False, eos=False), + self.ARGS, + *self.tokenizer.encode(json.dumps(prepared["arguments"], ensure_ascii=False), bos=False, eos=False), + ] + return curr_tokens + + def encode_tool_message(self, message: ToolMessage, is_before_last_user_message: bool) -> List[int]: + r"""Encode a tool message. + + Args: + message: The message to encode. + is_before_last_user_message: Not used. + Returns: + The encoded tokens. + """ + assert message.tool_call_id is not None, "Tool call id must be provided for tokenizer >= v13" + + tokens = self.tokenizer.encode(message.content, bos=False, eos=False) + curr_tokens = [ + self.BEGIN_TOOL_RESULTS, + *tokens, + self.END_TOOL_RESULTS, + ] + return curr_tokens + + def encode_think(self, chunk: ThinkChunk) -> List[int]: + r"""Encode a thinking chunk. + + Args: + chunk: The thinking chunk to encode. + Returns: + The encoded tokens. + """ + assert self.BEGIN_THINK is not None, "think tokens are not available for this tokenizer." + assert self.END_THINK is not None, "think tokens are not available for this tokenizer." + tokens = self.tokenizer.encode(chunk.thinking, bos=False, eos=False) + think_tokens = [self.BEGIN_THINK, *tokens] + if chunk.closed: + think_tokens.append(self.END_THINK) + return think_tokens diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/mistral.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/mistral.py new file mode 100644 index 0000000000000000000000000000000000000000..3b05b5ee1fe0c9cc2335ee4b89db596801b804fd --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/mistral.py @@ -0,0 +1,450 @@ +import warnings +from pathlib import Path +from typing import Any, Callable, Dict, Generic, List, Optional, Tuple, Union + +from mistral_common.exceptions import ( + TokenizerException, +) +from mistral_common.protocol.fim.request import FIMRequest +from mistral_common.protocol.instruct.messages import ( + UATS, + AssistantMessageType, + SystemMessageType, + ToolMessageType, + UserMessageType, +) +from mistral_common.protocol.instruct.normalize import InstructRequestNormalizer, normalizer_for_tokenizer_version +from mistral_common.protocol.instruct.request import ChatCompletionRequest +from mistral_common.protocol.instruct.validator import ( + MistralRequestValidator, + MistralRequestValidatorV3, + MistralRequestValidatorV5, + MistralRequestValidatorV13, + ValidationMode, +) +from mistral_common.protocol.transcription.request import TranscriptionRequest +from mistral_common.tokens.tokenizers.audio import AudioConfig, AudioEncoder, SpecialAudioIDs +from mistral_common.tokens.tokenizers.base import ( + InstructRequest, + InstructRequestType, + InstructTokenizer, + SpecialTokenPolicy, + SpecialTokens, + TokenizedType, + TokenizerVersion, +) +from mistral_common.tokens.tokenizers.image import ( + ImageConfig, + ImageEncoder, + SpecialImageIDs, +) +from mistral_common.tokens.tokenizers.instruct import ( + InstructTokenizerV1, + InstructTokenizerV2, + InstructTokenizerV3, + InstructTokenizerV7, + InstructTokenizerV11, + InstructTokenizerV13, +) +from mistral_common.tokens.tokenizers.sentencepiece import ( + SentencePieceTokenizer, + get_image_config, + is_sentencepiece, +) +from mistral_common.tokens.tokenizers.tekken import Tekkenizer, is_tekken +from mistral_common.tokens.tokenizers.utils import download_tokenizer_from_hf_hub + + +def load_image_encoder(image_config: ImageConfig, tokenizer: Union[Tekkenizer, SentencePieceTokenizer]) -> ImageEncoder: + r"""Load a image encoder from a config and a tokenizer. + + Args: + image_config: The image config. + tokenizer: The tokenizer. + + Returns: + The image encoder. + """ + special_ids = SpecialImageIDs( + img=tokenizer.get_control_token(SpecialTokens.img.value), + img_break=tokenizer.get_control_token(SpecialTokens.img_break.value), + img_end=tokenizer.get_control_token(SpecialTokens.img_end.value), + ) + return ImageEncoder(image_config, special_ids) + + +def load_audio_encoder(audio_config: AudioConfig, tokenizer: Tekkenizer) -> AudioEncoder: + r"""Load a audio encoder from a config and a tokenizer. + + Args: + audio_config: The audio config. + tokenizer: The tokenizer. + + Returns: + The audio encoder. + """ + special_ids = SpecialAudioIDs( + audio=tokenizer.get_control_token(SpecialTokens.audio.value), + begin_audio=tokenizer.get_control_token(SpecialTokens.begin_audio.value), + ) + return AudioEncoder(audio_config, special_ids) + + +class MistralTokenizer( + Generic[UserMessageType, AssistantMessageType, ToolMessageType, SystemMessageType, TokenizedType] +): + r"""Mistral tokenizer. + + This class is a wrapper around a [InstructTokenizer][mistral_common.tokens.tokenizers.base.InstructTokenizer], + a [MistralRequestValidator][mistral_common.protocol.instruct.validator.MistralRequestValidator] and a + [InstructRequestNormalizer][mistral_common.protocol.instruct.normalize.InstructRequestNormalizer]. + + It provides a convenient interface to tokenize, validate ad normalize Mistral requests. + + Attributes: + instruct_tokenizer: The instruct tokenizer to use. See + [InstructTokenizer][mistral_common.tokens.tokenizers.instruct.InstructTokenizer]. + """ + + def __init__( + self, + instruct_tokenizer: InstructTokenizer[InstructRequest, FIMRequest, TokenizedType, AssistantMessageType], + validator: MistralRequestValidator[UserMessageType, AssistantMessageType, ToolMessageType, SystemMessageType], + request_normalizer: InstructRequestNormalizer[ + UserMessageType, AssistantMessageType, ToolMessageType, SystemMessageType, InstructRequestType + ], + ): + r"""Initializes a `MistralTokenizer`. + + Args: + instruct_tokenizer: The instruct tokenizer to use. + validator: The request validator to use. + request_normalizer: The request normalizer to use. + """ + self._chat_completion_request_validator = validator + self._instruct_request_normalizer = request_normalizer + self.instruct_tokenizer: InstructTokenizer[InstructRequest, FIMRequest, TokenizedType, AssistantMessageType] = ( + instruct_tokenizer + ) + + def __reduce__(self) -> Tuple[Callable, Tuple[Any, ...]]: + """ + Provides a recipe for pickling (serializing) this object, which is necessary for use with multiprocessing. + + Returns: + A tuple of the factory function and the arguments to reconstruct the object from its source file. + """ + return MistralTokenizer.from_file, ( + self.instruct_tokenizer.tokenizer.file_path, + self._chat_completion_request_validator._mode, + ) + + @classmethod + def _data_path(cls) -> Path: + return Path(__file__).parents[2] / "data" + + @classmethod + def v1(cls) -> "MistralTokenizer": + r"""Get the Mistral tokenizer v1.""" + return cls.from_file(str(cls._data_path() / "tokenizer.model.v1"), mode=ValidationMode.test) + + @classmethod + def v2(cls) -> "MistralTokenizer": + r"""Get the Mistral tokenizer v2.""" + return cls.from_file( + str(cls._data_path() / "mistral_instruct_tokenizer_240216.model.v2"), mode=ValidationMode.test + ) + + @classmethod + def v3(cls, is_tekken: bool = False, is_mm: bool = False) -> "MistralTokenizer": + r"""Get the Mistral tokenizer v3. + + Args: + is_tekken: Whether the tokenizer is a tekken tokenizer. See + [Tekkenizer][mistral_common.tokens.tokenizers.tekken.Tekkenizer]. + is_mm: Whether to load image tokenizer. + + Returns: + The Mistral tokenizer v3. + """ + if is_tekken and is_mm: + tokenizer_name = "tekken_240911.json" + elif is_tekken and not is_mm: + tokenizer_name = "tekken_240718.json" + elif not is_tekken and is_mm: + raise ValueError("Multimodal tokenizer is currently only supported for tekken") + else: + tokenizer_name = "mistral_instruct_tokenizer_240323.model.v3" + + return cls.from_file(str(cls._data_path() / tokenizer_name), mode=ValidationMode.test) + + @classmethod + def v7(cls, is_mm: bool = False) -> "MistralTokenizer": + """Get the Mistral tokenizer v7. + + Args: + is_mm: Whether to load the image tokenizer. + + Returns: + The Mistral tokenizer v7. + """ + if is_mm: + return cls.from_file( + str(cls._data_path() / "mistral_instruct_tokenizer_241114.model.v7m1"), mode=ValidationMode.test + ) + else: + return cls.from_file( + str(cls._data_path() / "mistral_instruct_tokenizer_241114.model.v7"), mode=ValidationMode.test + ) + + @classmethod + def from_model(cls, model: str, strict: bool = False) -> "MistralTokenizer": + r"""Get the Mistral tokenizer for a given model. + + Args: + model: The model name. + strict: Whether to use strict model name matching. If `False`, the model name is matched as a substring. + This is deprecated and will be removed in `mistral_common=1.10.0`. + + Returns: + The Mistral tokenizer for the given model. + """ + if not strict: + warnings.warn( + "Calling `MistralTokenizer.from_model(..., strict=False)` is deprecated as it can lead to incorrect " + "tokenizers. It is strongly recommended to use MistralTokenizer.from_model(..., strict=True)` " + "which will become the default in `mistral_common=1.10.0`." + "If you are using `mistral_common` for open-sourced model weights, we recommend using " + "`MistralTokenizer.from_file('')` instead.", + FutureWarning, + ) + + # TODO(Delete this code in mistral_common >= 1.10.0 + # Prefix search the model name mapping + for model_name, tokenizer_cls in MODEL_NAME_TO_TOKENIZER_CLS.items(): + if model_name in model.lower(): + return tokenizer_cls() + + if model not in MODEL_NAME_TO_TOKENIZER_CLS: + raise TokenizerException(f"Unrecognized model: {model}") + + return MODEL_NAME_TO_TOKENIZER_CLS[model]() + + @staticmethod + def from_hf_hub( + repo_id: str, + token: Optional[Union[bool, str]] = None, + revision: Optional[str] = None, + force_download: bool = False, + local_files_only: bool = False, + mode: ValidationMode = ValidationMode.test, + ) -> "MistralTokenizer": + r"""Download the Mistral tokenizer for a given Hugging Face repository ID. + + See [here](https://huggingface.co/mistralai/models) for a list of our OSS models. + + Args: + repo_id: The Hugging Face repo ID. + token: The Hugging Face token to use to download the tokenizer. + revision: The revision of the model to use. If `None`, the latest revision will be used. + mode: The validation mode to use. + force_download: Whether to force the download of the tokenizer. If `True`, the tokenizer will be downloaded + even if it is already cached. + local_files_only: Whether to only use local files. If `True`, the tokenizer will be downloaded only if it is + already cached. + + Returns: + The Mistral tokenizer for the given model. + """ + tokenizer_path = download_tokenizer_from_hf_hub( + repo_id=repo_id, + token=token, + revision=revision, + force_download=force_download, + local_files_only=local_files_only, + ) + return MistralTokenizer.from_file(tokenizer_path, mode=mode) + + @classmethod + def from_file( + cls, + tokenizer_filename: Union[str, Path], + mode: ValidationMode = ValidationMode.test, + ) -> "MistralTokenizer": + r"""Loads a tokenizer from a file. + + Args: + tokenizer_filename: The path to the tokenizer file. + mode: The validation mode to use. + + Returns: + The loaded tokenizer. + """ + tokenizer: Union[SentencePieceTokenizer, Tekkenizer] + + if is_tekken(tokenizer_filename): + tokenizer = Tekkenizer.from_file(tokenizer_filename) + image_config = tokenizer.image + audio_config = tokenizer.audio + elif is_sentencepiece(tokenizer_filename): + tokenizer = SentencePieceTokenizer(tokenizer_filename) + image_config = get_image_config(tokenizer_filename) + # spm can't have audio + audio_config = None + else: + raise TokenizerException(f"Unrecognized tokenizer file: {tokenizer_filename}") + + image_encoder = load_image_encoder(image_config, tokenizer) if image_config is not None else None + + audio_encoder = None + if audio_config is not None: + assert isinstance(tokenizer, Tekkenizer), "Audio is only supported for tekken tokenizers" + audio_encoder = load_audio_encoder(audio_config, tokenizer) + + request_normalizer = normalizer_for_tokenizer_version(tokenizer.version) + + if tokenizer.version == TokenizerVersion.v1: + assert image_encoder is None, "Tokenizer version needs to be >= v3" + assert audio_encoder is None, "Tokenizer version needs to be >= v7" + return MistralTokenizer( + InstructTokenizerV1(tokenizer), + validator=MistralRequestValidator(mode=mode), + request_normalizer=request_normalizer, + ) + elif tokenizer.version == TokenizerVersion.v2: + assert image_encoder is None, "Tokenizer version needs to be >= v3" + assert audio_encoder is None, "Tokenizer version needs to be >= v7" + return MistralTokenizer( + InstructTokenizerV2(tokenizer), + validator=MistralRequestValidator(mode=mode), + request_normalizer=request_normalizer, + ) + elif tokenizer.version == TokenizerVersion.v3: + assert audio_encoder is None, "Tokenizer version needs to be >= v7" + return MistralTokenizer( + InstructTokenizerV3(tokenizer, image_encoder=image_encoder), + validator=MistralRequestValidatorV3(mode=mode), + request_normalizer=request_normalizer, + ) + elif tokenizer.version == TokenizerVersion.v7: + return MistralTokenizer( + InstructTokenizerV7(tokenizer, image_encoder=image_encoder, audio_encoder=audio_encoder), + validator=MistralRequestValidatorV5(mode=mode), + request_normalizer=request_normalizer, + ) + elif tokenizer.version == TokenizerVersion.v11: + return MistralTokenizer( + InstructTokenizerV11(tokenizer, image_encoder=image_encoder, audio_encoder=audio_encoder), + validator=MistralRequestValidatorV5(mode=mode), + request_normalizer=request_normalizer, + ) + elif tokenizer.version == TokenizerVersion.v13: + return MistralTokenizer( + InstructTokenizerV13(tokenizer, image_encoder=image_encoder), + validator=MistralRequestValidatorV13(mode=mode), + request_normalizer=request_normalizer, + ) + + raise TokenizerException(f"Unrecognized tokenizer filename: {tokenizer_filename}") + + def encode_chat_completion( + self, request: ChatCompletionRequest[UATS], max_model_input_len: Optional[int] = None + ) -> TokenizedType: + r"""Encodes a chat completion request. + + Args: + request: The chat completion request to encode. + max_model_input_len: The maximum length of the input to the model. + If `None`, the input will not be truncated. + + Returns: + The encoded chat completion request. + """ + + validated_request = self._chat_completion_request_validator.validate_request(request) + + if max_model_input_len is None and request.truncate_for_context_length: + # the max_model_input_len arg should not be optional ; + # but this function is used in many small scripts that have no use + # for truncation, and don't provide the max model len + raise TokenizerException( + "encoding a chat completion request with truncation, but no max model len was provided", + ) + + instruct_request = self._instruct_request_normalizer.from_chat_completion_request(validated_request) + + if request.truncate_for_context_length: + instruct_request.truncate_at_max_tokens = max_model_input_len + + return self.instruct_tokenizer.encode_instruct(instruct_request) + + def encode_transcription(self, request: TranscriptionRequest) -> TokenizedType: + r"""Encodes a transcription request. + + Args: + request: The transcription request to encode. + + Returns: + The encoded transcription request. + """ + return self.instruct_tokenizer.encode_transcription(request) + + def encode_fim(self, request: FIMRequest) -> TokenizedType: + r"""Encodes a fill in the middle request. + + Args: + request: The fill in the middle request to encode. + + Returns: + The encoded fill in the middle request. + """ + return self.instruct_tokenizer.encode_fim(request) + + def decode(self, tokens: List[int], special_token_policy: Optional[SpecialTokenPolicy] = None) -> str: + r"""Decodes a list of tokens into a string. + + Args: + tokens: The tokens to decode. + special_token_policy: The policy to use for special tokens. Passing `None` is deprecated and will be changed + to `SpecialTokenPolicy.IGNORE` in `mistral_common=1.10.0`. + + Returns: + The decoded string. + """ + return self.instruct_tokenizer.decode(tokens, special_token_policy=special_token_policy) + + def _to_string(self, tokens: List[int]) -> str: + return self.instruct_tokenizer._to_string(tokens) + + +MODEL_NAME_TO_TOKENIZER_CLS: Dict[str, Callable[[], MistralTokenizer]] = { + "ministral-8b-2410": lambda: MistralTokenizer.v3(is_tekken=True), + "mistral-tiny-2312": MistralTokenizer.v2, + "open-mistral-nemo-2407": lambda: MistralTokenizer.v3(is_tekken=True), + "mistral-tiny-2407": MistralTokenizer.v3, + "mistral-small-2312": MistralTokenizer.v2, + "open-mixtral-8x22b-2404": MistralTokenizer.v3, + "mistral-small-2402": MistralTokenizer.v2, + "mistral-small-2409": lambda: MistralTokenizer.v3(is_tekken=True), + "mistral-medium-2312": MistralTokenizer.v1, + "mistral-large-2402": MistralTokenizer.v2, + "mistral-large-2407": MistralTokenizer.v3, + "mistral-large-2411": MistralTokenizer.v7, + "pixtral-large-2411": lambda: MistralTokenizer.v7(is_mm=True), + "codestral-2405": MistralTokenizer.v3, + "codestral-mamba-2407": MistralTokenizer.v3, + "pixtral-12b-2409": lambda: MistralTokenizer.v3(is_tekken=True, is_mm=True), + # The following are deprecated - only left for backward comp. Delete in >= 1.10.0 + "open-mistral-7b": MistralTokenizer.v1, + "open-mixtral-8x7b": MistralTokenizer.v1, + "mistral-embed": MistralTokenizer.v1, + "mistral-small-v1": MistralTokenizer.v2, + "mistral-large-v1": MistralTokenizer.v2, + "mistral-small": MistralTokenizer.v3, + "mistral-large": MistralTokenizer.v3, + "open-mixtral-8x22b": MistralTokenizer.v3, + "codestral-22b": MistralTokenizer.v3, + "mistral-nemo": lambda: MistralTokenizer.v3(is_tekken=True), + "pixtral": lambda: MistralTokenizer.v3(is_tekken=True, is_mm=True), + "pixtral-large": lambda: MistralTokenizer.v7(is_mm=True), +} diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/multimodal.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/multimodal.py new file mode 100644 index 0000000000000000000000000000000000000000..4cddbc9b79428a64908ed10c79cd8709f820dd33 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/multimodal.py @@ -0,0 +1,3 @@ +# This file is deprecated. TODO(Patrick) - as soon as vllm & transformers have adapted +# to new naming, throw deprecation warning and remove this file. +from mistral_common.tokens.tokenizers.image import * # noqa: F403 diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/sentencepiece.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/sentencepiece.py new file mode 100644 index 0000000000000000000000000000000000000000..0710d00e058d8c9951f3a2a52e95729178e14322 --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/sentencepiece.py @@ -0,0 +1,239 @@ +import logging +import os +import warnings +from functools import cached_property +from pathlib import Path +from typing import List, Optional, Set, Union + +from sentencepiece import SentencePieceProcessor + +from mistral_common.exceptions import TokenizerException +from mistral_common.tokens.tokenizers.base import ( + SpecialTokenPolicy, + Tokenizer, + TokenizerVersion, +) +from mistral_common.tokens.tokenizers.image import ImageConfig, MultiModalVersion + + +def is_sentencepiece(path: Union[str, Path]) -> bool: + r"""Check if the given path is a SentencePiece model.""" + if isinstance(path, str): + path = Path(path) + + instruct_versions = list(TokenizerVersion.__members__) + mm_versions = list(MultiModalVersion.__members__) + [""] # allow no mm version + suffixes = [f".model.{v}{m}" for v in instruct_versions for m in mm_versions] + [".model"] + + return path.is_file() and any(path.name.endswith(suffix) for suffix in suffixes) + + +def get_spm_version(tokenizer_filename: Union[str, Path], raise_deprecated: bool = False) -> TokenizerVersion: + r"""Get the version of the tokenizer from the filename.""" + tokenizer_filename = str(tokenizer_filename) + + _version_str = tokenizer_filename.split(".")[-1] + if _version_str != "model": # filter tokenizer_filename == "/path/to/tokenizer.model" case + _version_str = _version_str.split("m")[0] + + if _version_str == "model": + if raise_deprecated: + raise TokenizerException(f"Make sure to rename your tokenizer file to end with {tokenizer_filename}.v1.") + + # tokenizer.model => tokenizer.model.v1 + return TokenizerVersion("v1") + + if _version_str not in TokenizerVersion.__members__: + raise TokenizerException(f"Unrecognized tokenizer filename: {tokenizer_filename}") + + return TokenizerVersion(_version_str) + + +def get_image_config(tokenizer_filename: Union[str, Path]) -> Optional[ImageConfig]: + r"""Get the image config from the tokenizer filename.""" + tokenizer_filename = str(tokenizer_filename) + + _version_str = tokenizer_filename.split(".")[-1] + if _version_str == "model" or "m" not in _version_str: + return None + + _mm_version_str = "m" + _version_str.split("m")[-1] + + if _mm_version_str not in MultiModalVersion.__members__: + raise TokenizerException(f"Unrecognized tokenizer filename: {tokenizer_filename}") + + return MultiModalVersion(_mm_version_str).config + + +class SentencePieceTokenizer(Tokenizer): + r"""[SentencePiece](https://github.com/google/sentencepiece) tokenizer.""" + + def __init__(self, model_path: Union[str, Path], tokenizer_version: Optional[TokenizerVersion] = None) -> None: + r"""Initialize the `SentencePieceTokenizer`. + + Args: + model_path: The path to the `SentencePiece` model. + tokenizer_version: The version of the tokenizer. If not provided, it will be inferred from the model path. + """ + self._logger = logging.getLogger(self.__class__.__name__) + # reload tokenizer + assert os.path.isfile(model_path), model_path + self._model = SentencePieceProcessor( + model_file=model_path if isinstance(model_path, str) else model_path.as_posix() + ) + + assert self._model.vocab_size() == self._model.get_piece_size() + self._vocab = [self._model.id_to_piece(i) for i in range(self.n_words)] + + self._version: TokenizerVersion = tokenizer_version or get_spm_version(model_path, raise_deprecated=False) + + self._file_path = Path(model_path) + super().__init__() + + @property + def file_path(self) -> Path: + r"""The path to the tokenizer model.""" + return self._file_path + + @property + def version(self) -> TokenizerVersion: + r"""The version of the tokenizer.""" + return self._version + + def get_control_token(self, s: str) -> int: + r"""Get the control token for the given string.""" + return self._model.piece_to_id(s) # type: ignore + + @property + def n_words(self) -> int: + r"""Vocabulary size of the tokenizer.""" + return self._model.vocab_size() # type: ignore + + def vocab(self) -> List[str]: + r"""All tokens in the vocabulary as strings.""" + return self._vocab + + @cached_property + def bos_id(self) -> int: + r"""The beginning of sentence token id.""" + return self._model.bos_id() # type: ignore + + @cached_property + def eos_id(self) -> int: + r"""The end of sentence token id.""" + return self._model.eos_id() # type: ignore + + @cached_property + def _control_tokens(self) -> Set[int]: + return {tok for tok in range(self.n_words) if self._model.IsControl(tok)} + + def encode(self, s: str, bos: bool, eos: bool) -> List[int]: + r"""Encode the given string into a list of token ids. + + Args: + s: The string to encode. + bos: Whether to add the beginning of sentence token. + eos: Whether to add the end of sentence token. + + Returns: + The list of token ids. + """ + assert isinstance(s, str) + t: List[int] = self._model.encode(s) + if bos: + t = [self.bos_id, *t] + if eos: + t = [*t, self.eos_id] + return t + + def decode(self, tokens: List[int], special_token_policy: Optional[SpecialTokenPolicy] = None) -> str: + r"""Decode the given list of token ids into a string. + + Note: + Using `special_token_policy=SpecialTokenPolicy.KEEP` will keep the special tokens and the normal tokens as + SentencePiece pieces. + + Args: + tokens: The list of token ids. + special_token_policy: The policy to use for special tokens. If `None`, the default policy + is `SpecialTokenPolicy.IGNORE`. Passing `None` is deprecated and will be changed + to `SpecialTokenPolicy.IGNORE` in `mistral_common=1.10.0`. + + Returns: + The decoded string. + """ + if special_token_policy is not None and not isinstance(special_token_policy, SpecialTokenPolicy): + raise ValueError( + f"Expected `special_token_policy` to be None or SpecialTokenPolicy, got {type(special_token_policy)}." + ) + + if special_token_policy is None: + warnings.warn( + ( + "Using the tokenizer's special token policy `None` is deprecated. " + "It will be removed in 1.10.0. " + "Please pass a special token policy explicitly. " + "Future default will be SpecialTokenPolicy.IGNORE." + ), + FutureWarning, + ) + special_token_policy = SpecialTokenPolicy.IGNORE + + if special_token_policy in [SpecialTokenPolicy.KEEP, SpecialTokenPolicy.RAISE]: + return self._decode_with_special_tokens(tokens, special_token_policy) + + return self._model.decode(tokens) # type: ignore + + def id_to_piece(self, token_id: int) -> str: + r"""Convert the given token id to a token piece.""" + return self._model.id_to_piece(token_id) # type: ignore + + def _decode_with_special_tokens(self, tokens: List[int], special_token_policy: SpecialTokenPolicy) -> str: + text = "" + curr_tokens: List[int] = [] + for tok in tokens: + if tok in self._control_tokens: + if special_token_policy == SpecialTokenPolicy.RAISE: + raise ValueError("Decoding `tokens` that contain special tokens with special_token_policy=RAISE.") + if curr_tokens: + text += "".join([self.id_to_piece(tok) for tok in curr_tokens]) + curr_tokens = [] + + text += self.id_to_piece(tok) + + else: + curr_tokens.append(tok) + + if curr_tokens: + text += "".join([self.id_to_piece(tok) for tok in curr_tokens]) + + return text + + def to_string(self, tokens: List[int]) -> str: + r"""[DEPRECATED] Converts a list of token ids into a string, keeping special tokens. + + Use `decode` with `special_token_policy=SpecialTokenPolicy.KEEP` instead. + + This is a convenient method for debugging. + """ + warnings.warn( + ( + "`to_string` is deprecated and will be removed in 1.10.0. " + "Use `decode` with `special_token_policy=SpecialTokenPolicy.KEEP` instead." + ), + FutureWarning, + ) + return self._to_string(tokens) + + def _to_string(self, tokens: List[int]) -> str: + return self.decode(tokens, special_token_policy=SpecialTokenPolicy.KEEP) + + @property + def pad_id(self) -> int: + r"""The padding token id.""" + return self._model.pad_id() # type: ignore + + @property + def unk_id(self) -> int: + r"""The unknown token id.""" + return self._model.unk_id() # type: ignore diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/tekken.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/tekken.py new file mode 100644 index 0000000000000000000000000000000000000000..dcedd45b895b7360ffc7c2655217e0e7b5b2326f --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/tekken.py @@ -0,0 +1,559 @@ +import base64 +import json +import logging +import warnings +from functools import cached_property +from itertools import groupby +from pathlib import Path +from typing import Dict, List, Optional, Type, TypedDict, Union + +import tiktoken + +from mistral_common.tokens.tokenizers.audio import AudioConfig, AudioSpectrogramConfig +from mistral_common.tokens.tokenizers.base import ( + SpecialTokenPolicy, + SpecialTokens, + Tokenizer, + TokenizerVersion, +) +from mistral_common.tokens.tokenizers.image import ImageConfig + +logger = logging.getLogger(__name__) + + +def is_tekken(path: Union[str, Path]) -> bool: + r"""Check if the given path is a tekken tokenizer file.""" + if isinstance(path, str): + path = Path(path) + return path.is_file() and "tekken" in path.name and path.suffix == ".json" + + +# Formatting specification of the JSON file +class TokenInfo(TypedDict): + r"""Token information in the JSON file. + + Attributes: + rank: The rank of the token. + token_bytes: The token in bytes, base64 encoded. + token_str: The token in string format. + """ + + rank: int + token_bytes: str # base64 encoded + token_str: Optional[str] + + +class SpecialTokenInfo(TypedDict): + r"""Special token information in the JSON file. + + Attributes: + rank: The rank of the token. + token_str: The token in string format. + is_control: Whether the token is a control token. + """ + + rank: int + token_str: str + is_control: bool + + +class TekkenConfig(TypedDict): + r"""Tekken configuration in the JSON file. + + Attributes: + pattern: The pattern of the tokenizer. + num_vocab_tokens: The number of vocabulary tokens. + default_vocab_size: The default vocabulary size. + default_num_special_tokens: The default number of special tokens. + version: The version of the tokenizer. + """ + + pattern: str + num_vocab_tokens: int + default_vocab_size: int + default_num_special_tokens: int + version: str + + +class ModelData(TypedDict): + r"""The data of the tekken tokenizer model. + + Attributes: + vocab: The vocabulary of the tokenizer. + config: The configuration of the tokenizer. + version: The version of the tokenizer. + type: The type of the tokenizer. + image: The image configuration of the tokenizer. + """ + + vocab: List[TokenInfo] + special_tokens: Optional[List[SpecialTokenInfo]] + config: TekkenConfig + version: int + type: str + image: ImageConfig + audio: AudioConfig + + +class Tekkenizer(Tokenizer): + r"""Tekken tokenizer. + + This tokenizer is based on the [tiktoken](https://github.com/openai/tiktoken) library. It fastens the tokenization + for multiple languages. + """ + + DEPRECATED_SPECIAL_TOKENS = ( + SpecialTokenInfo(rank=0, token_str=SpecialTokens.unk, is_control=True), + SpecialTokenInfo(rank=1, token_str=SpecialTokens.bos, is_control=True), + SpecialTokenInfo(rank=2, token_str=SpecialTokens.eos, is_control=True), + SpecialTokenInfo(rank=3, token_str=SpecialTokens.begin_inst, is_control=True), + SpecialTokenInfo(rank=4, token_str=SpecialTokens.end_inst, is_control=True), + SpecialTokenInfo(rank=5, token_str=SpecialTokens.begin_tools, is_control=True), + SpecialTokenInfo(rank=6, token_str=SpecialTokens.end_tools, is_control=True), + SpecialTokenInfo(rank=7, token_str=SpecialTokens.begin_tool_results, is_control=True), + SpecialTokenInfo(rank=8, token_str=SpecialTokens.end_tool_results, is_control=True), + SpecialTokenInfo(rank=9, token_str=SpecialTokens.tool_calls, is_control=True), + SpecialTokenInfo(rank=10, token_str=SpecialTokens.img, is_control=True), + SpecialTokenInfo(rank=11, token_str=SpecialTokens.pad, is_control=True), + SpecialTokenInfo(rank=12, token_str=SpecialTokens.img_break, is_control=True), + SpecialTokenInfo(rank=13, token_str=SpecialTokens.img_end, is_control=True), + SpecialTokenInfo(rank=14, token_str=SpecialTokens.prefix, is_control=True), + SpecialTokenInfo(rank=15, token_str=SpecialTokens.middle, is_control=True), + SpecialTokenInfo(rank=16, token_str=SpecialTokens.suffix, is_control=True), + SpecialTokenInfo(rank=17, token_str=SpecialTokens.begin_system, is_control=True), + SpecialTokenInfo(rank=18, token_str=SpecialTokens.end_system, is_control=True), + SpecialTokenInfo(rank=19, token_str=SpecialTokens.begin_tool_content, is_control=True), + ) + + SPECIAL_TOKEN_TEMPLATE = "" + + # # note that params has a vocab_size field, but it's not used + + def __init__( + self, + vocab: List[TokenInfo], + special_tokens: List[SpecialTokenInfo], + pattern: str, + vocab_size: int, + num_special_tokens: int, + version: TokenizerVersion, + *, + name: str = "tekkenizer", + _path: Optional[Union[str, Path]] = None, + image_config: Optional[ImageConfig] = None, + audio_config: Optional[AudioConfig] = None, + ): + r"""Initialize the tekken tokenizer. + + Args: + vocab: The vocabulary of the tokenizer. + special_tokens: The special tokens of the tokenizer. + pattern: The pattern of the tokenizer. + vocab_size: The vocabulary size of the tokenizer. + num_special_tokens: The number of special tokens of the tokenizer. + version: The version of the tokenizer. + name: The name of the tokenizer. + image_config: The image configuration of the tokenizer. + """ + assert vocab_size <= len(vocab) + num_special_tokens, ( + vocab_size, + len(vocab), + num_special_tokens, + ) + self._vocab_size = vocab_size + + # The number of special tokens defined in the tokenizer json + num_defined_special_tokens = len(set([t["token_str"] for t in special_tokens])) + + assert len(special_tokens) == num_defined_special_tokens, f"Special tokens must be unique: {special_tokens}" + assert len(special_tokens) <= num_special_tokens + + special_filler = [ + SpecialTokenInfo(rank=i, token_str=self.SPECIAL_TOKEN_TEMPLATE.format(id=i), is_control=True) + for i in range(len(special_tokens), num_special_tokens) + ] + if special_filler: + logger.info( + f"Adding special tokens {special_filler[0]['token_str']}, ..., {special_filler[-1]['token_str']}" + ) + special_tokens = special_tokens + special_filler + + assert len(set([t["token_str"] for t in special_tokens])) == len(special_tokens) == num_special_tokens, ( + special_tokens + ) + inner_vocab_size = vocab_size - num_special_tokens + + # reload vocab + self._tekken_token2id_nospecial = _reload_mergeable_ranks(vocab, max_vocab=inner_vocab_size) + assert set(range(inner_vocab_size)) == set(self._tekken_token2id_nospecial.values()), ( + inner_vocab_size, + self._tekken_token2id_nospecial, + ) + self._model = tiktoken.Encoding( + name=name, + pat_str=pattern, + mergeable_ranks=self._tekken_token2id_nospecial, + special_tokens={}, # special tokens are handled manually + ) + + self._version = version + + self._image_config = image_config + self._audio_config = audio_config + + self._all_special_tokens = special_tokens + self._special_tokens_reverse_vocab = {t["token_str"]: t["rank"] for t in special_tokens} + self._vocab = [self.id_to_piece(i) for i in range(vocab_size)] + self._special_token_policy = SpecialTokenPolicy.IGNORE + self._file_path = Path(_path) if _path is not None else None + + @property + def file_path(self) -> Path: + r"""The path to the tokenizer file.""" + if self._file_path is None: + raise ValueError("The tokenizer was not loaded from a file.") + return self._file_path + + @classmethod + def from_file(cls: Type["Tekkenizer"], path: Union[str, Path]) -> "Tekkenizer": + r"""Load the tekken tokenizer from a file. + + Args: + path: The path to the tokenizer file. + + Returns: + The tekken tokenizer. + """ + if isinstance(path, str): + path = Path(path) + assert path.exists(), path + with open(path, "r", encoding="utf-8") as f: + untyped = json.load(f) + + _version_str = untyped["config"].get("version") + if _version_str not in TokenizerVersion.__members__: + raise ValueError( + f"Unknown version: {_version_str} in {path}. " + f"Make sure to use a valid version string: {list(TokenizerVersion.__members__)}" + ) + + assert _version_str is not None + version = TokenizerVersion(_version_str) + + special_tokens_dicts: Optional[List[SpecialTokenInfo]] = untyped.get("special_tokens", None) + if special_tokens_dicts is None: + # Tokenizer > v7 should find special tokens in the tokenizer file + if version > TokenizerVersion("v7"): + raise ValueError( + f"Special tokens not found in {path}. " + "Please update your tokenizer file and include all special tokens you need." + ) + else: + special_tokens = list(Tekkenizer.DEPRECATED_SPECIAL_TOKENS) + else: + special_tokens = [token for token in special_tokens_dicts] + + untyped["special_tokens"] = special_tokens + + if mm := untyped.get("multimodal"): + # deprecated - only allowed for tokenizers <= v11 + if version > TokenizerVersion("v11"): + raise ValueError( + f"The image config has to be called 'image' in {path} for tokenizers of version {version.value}." + ) + + untyped["image"] = ImageConfig(**mm) + elif image := untyped.get("image"): + untyped["image"] = ImageConfig(**image) + + if audio := untyped.get("audio"): + encoding_config = audio.pop("audio_encoding_config") + encoding_config = AudioSpectrogramConfig(**encoding_config) + untyped["audio"] = AudioConfig(encoding_config=encoding_config, **audio) + + model_data: ModelData = untyped + + return cls( + vocab=model_data["vocab"], + special_tokens=special_tokens, + pattern=model_data["config"]["pattern"], + vocab_size=model_data["config"]["default_vocab_size"], + num_special_tokens=model_data["config"]["default_num_special_tokens"], + version=version, + name=path.name.replace(".json", ""), + image_config=model_data.get("image"), + audio_config=model_data.get("audio"), + _path=path, + ) + + @property + def image(self) -> Optional[ImageConfig]: + r"""The image configuration of the tokenizer.""" + return self._image_config + + @image.setter + def image(self, value: ImageConfig) -> None: + raise ValueError("Can only set Image config at init") + + @property + def audio(self) -> Optional[AudioConfig]: + r"""The audio configuration of the tokenizer. + + Returns: + The audio configuration object if it exists, otherwise None. + """ + return self._audio_config + + @audio.setter + def audio(self, value: AudioConfig) -> None: + raise ValueError("Can only set Audio config at init") + + @property + def num_special_tokens(self) -> int: + r"""The number of special tokens of the tokenizer.""" + return len(self._all_special_tokens) + + @property + def n_words(self) -> int: + r"""Vocabulary size of the tokenizer.""" + return self._vocab_size + + @property + def version(self) -> TokenizerVersion: + r"""The version of the tokenizer.""" + return self._version + + @property + def special_token_policy(self) -> SpecialTokenPolicy: + r"""The policy for handling special tokens.""" + return self._special_token_policy + + @special_token_policy.setter + def special_token_policy(self, policy: SpecialTokenPolicy) -> None: + r"""Set the policy for handling special tokens.""" + if not isinstance(policy, SpecialTokenPolicy): + raise ValueError(f"Expected SpecialTokenPolicy, got {type(policy)}.") + + warnings.warn( + ( + "The attributed `special_token_policy` is deprecated and will be removed in 1.10.0. " + "Please pass a special token policy explicitly to the relevant methods." + ), + FutureWarning, + ) + + self._special_token_policy = policy + + @cached_property + def bos_id(self) -> int: + r"""The beginning of sentence token id.""" + return self.get_control_token("") + + @cached_property + def eos_id(self) -> int: + r"""The end of sentence token id.""" + return self.get_control_token("") + + @cached_property + def pad_id(self) -> int: + r"""The padding token id.""" + return self.get_control_token("") + + @cached_property + def unk_id(self) -> int: + r"""The unknown token id.""" + return self.get_control_token("") + + def vocab(self) -> List[str]: + r"""All tokens in the vocabulary as strings. + + Note: + This will collapse all tokens for which we have a decoding error into + the string. This is bad and results in things like len(set(vocab)) != len(vocab)). + + Returns: + The vocabulary of the tokenizer. + """ + # when returning self._vocab this will collapse + # all tokens for which we have a decoding error into + # the string. This is bad and results in things + # like len(set(vocab)) != len(vocab)) + # be careful when using self._vocab + return self._vocab + + def encode(self, s: str, bos: bool, eos: bool) -> List[int]: + r"""Encode a string into a list of token ids. + + Args: + s: The string to encode. + bos: Whether to add the beginning of sentence token. + eos: Whether to add the end of sentence token. + + Returns: + The list of token ids. + """ + tokens: List[int] = self._model.encode(s) + tokens = [t + self.num_special_tokens for t in tokens] + if bos: + tokens = [self.bos_id, *tokens] + if eos: + tokens = [*tokens, self.eos_id] + return tokens + + def _decode_all(self, tokens: List[int], special_token_policy: SpecialTokenPolicy) -> List[str]: + # Lump special and non-special tokens together to minimize calls to decode + decoded: List[str] = [] + for is_special, group in groupby(tokens, lambda t: t < self.num_special_tokens): + if is_special: + if special_token_policy == SpecialTokenPolicy.RAISE: + raise ValueError( + f"Decoding `tokens` that contain special tokens ({list(group)}) is not allowed. \n" + "Either make sure `tokens` do not include any special tokens or, " + "if you want to decode `tokens` that includes special tokens, " + "change the tokenizer's special token policy to IGNORE or KEEP: \n" + "```\nfrom mistral_common.tokens.tokenizers.mistral import MistralTokenizer" + "\nfrom mistral_common.tokens.tokenizers.tekken import SpecialTokenPolicy" + "\n\ntokenizer = MistralTokenizer.v3(is_tekken=True)" + "\ntekken = tokenizer.instruct_tokenizer.tokenizer" + "\ntekken.special_token_policy = SpecialTokenPolicy.IGNORE # or SpecialTokenPolicy.KEEP" + "\n```" + ) + elif special_token_policy == SpecialTokenPolicy.KEEP: + decoded.extend(self._all_special_tokens[t]["token_str"] for t in group) + elif special_token_policy == SpecialTokenPolicy.IGNORE: + continue + # TODO: Could use "tokens_str" from vocab.json + # but need to handle null cases. + else: + decoded.append(self._model.decode([t - self.num_special_tokens for t in group])) + return decoded + + def is_byte(self, token_id: int) -> bool: + r"""Check if a token id is a byte token.""" + return 0 <= token_id - self.num_special_tokens < 256 + + def get_control_token(self, s: str) -> int: + r"""Get the token id of a control token.""" + if s in self._special_tokens_reverse_vocab: + return self._special_tokens_reverse_vocab[s] + else: + raise ValueError(f"Unknown control token {s}") + + def decode(self, tokens: List[int], special_token_policy: Optional[SpecialTokenPolicy] = None) -> str: + r"""Decode a list of token ids into a string. + + Args: + tokens: The list of token ids to decode. + special_token_policy: The policy for handling special tokens. + Use the tokenizer's [attribute][mistral_common.tokens.tokenizers.tekken.Tekkenizer.special_token_policy] + if `None`. Passing `None` is deprecated and will be changed + to `SpecialTokenPolicy.IGNORE` in `mistral_common=1.10.0`. + + Returns: + The decoded string. + """ + if special_token_policy is not None and not isinstance(special_token_policy, SpecialTokenPolicy): + raise ValueError( + f"Expected `special_token_policy` to be None or SpecialTokenPolicy, got {type(special_token_policy)}." + ) + + if special_token_policy is None: + warnings.warn( + ( + f"Using the tokenizer's special token policy ({self._special_token_policy}) is deprecated. " + "It will be removed in 1.10.0. " + "Please pass a special token policy explicitly. " + "Future default will be SpecialTokenPolicy.IGNORE." + ), + FutureWarning, + ) + special_token_policy = self._special_token_policy + + return "".join(self._decode_all(tokens, special_token_policy=special_token_policy)) + + def to_string(self, tokens: List[int]) -> str: + r"""[DEPRECATED] Converts a list of token ids into a string, keeping special tokens. + + Use `decode` with `special_token_policy=SpecialTokenPolicy.KEEP` instead. + + This is a convenient method for debugging. + """ + warnings.warn( + ( + "`to_string` is deprecated and will be removed in 1.10.0. " + "Use `decode` with `special_token_policy=SpecialTokenPolicy.KEEP` instead." + ), + FutureWarning, + ) + return self._to_string(tokens) + + def _to_string(self, tokens: List[int]) -> str: + return self.decode(tokens, special_token_policy=SpecialTokenPolicy.KEEP) + + def id_to_piece(self, token_id: int) -> str: + r"""Convert a token id to its string representation.""" + return self.decode([token_id], special_token_policy=SpecialTokenPolicy.KEEP) + + def id_to_byte_piece(self, token_id: int, special_token_policy: Optional[SpecialTokenPolicy] = None) -> bytes: + r"""Convert a token id to its byte representation. + + Args: + token_id: The token id to convert. + special_token_policy: The policy for handling special tokens. + Use the tokenizer's [attribute][mistral_common.tokens.tokenizers.tekken.Tekkenizer.special_token_policy] + if `None`. Passing `None` is deprecated and will be changed + to `SpecialTokenPolicy.IGNORE` in `mistral_common=1.10.0`. + + Returns: + The byte representation of the token. + """ + if special_token_policy is None: + warnings.warn( + ( + f"Using the tokenizer's special token policy ({self._special_token_policy}) is deprecated. " + "It will be removed in 1.10.0. " + "Please pass a special token policy explicitly. " + "Future default will be SpecialTokenPolicy.IGNORE." + ), + FutureWarning, + ) + special_token_policy = self._special_token_policy + + if token_id < self.num_special_tokens: + if special_token_policy == SpecialTokenPolicy.KEEP: + return self._all_special_tokens[token_id]["token_str"].encode("utf-8") + elif special_token_policy == SpecialTokenPolicy.RAISE: + raise ValueError(f"{token_id} is a special token") + elif special_token_policy == SpecialTokenPolicy.IGNORE: + return b"" + else: + raise ValueError(f"Unknown special token policy {special_token_policy}") + + return self._model.decode_single_token_bytes(token_id - self.num_special_tokens) + + +def _reload_mergeable_ranks( + vocab: List[TokenInfo], + max_vocab: Union[int, None] = None, +) -> Dict[bytes, int]: + r"""Reload our tokenizer JSON file and convert it to Tiktoken format.""" + logger.info(f"Vocab size: {len(vocab)}") + if max_vocab is not None: + assert len(vocab) >= max_vocab, (len(vocab), max_vocab) + vocab = vocab[:max_vocab] + logger.info(f"Cutting vocab to first {len(vocab)} tokens.") + + # build ranks + ranks: Dict[bytes, int] = {} + for i, x in enumerate(vocab): + assert x.keys() == {"rank", "token_bytes", "token_str"} + assert x["rank"] == i + merge = base64.b64decode(x["token_bytes"]) + assert i >= 256 or merge == bytes([i]), (i, merge) + ranks[merge] = x["rank"] + + # sanity check + assert len(ranks) == len(vocab) + assert set(ranks.values()) == set(range(len(ranks))) + + return ranks diff --git a/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/utils.py b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..40eeffc42de6ce8ff3cd0bf142fbafddaaa2311c --- /dev/null +++ b/venv/lib/python3.10/site-packages/mistral_common/tokens/tokenizers/utils.py @@ -0,0 +1,179 @@ +import logging +import os +from pathlib import Path +from typing import Iterator, List, Optional, Union + +import requests + +from mistral_common.tokens.tokenizers.base import TokenizerVersion +from mistral_common.tokens.tokenizers.image import MultiModalVersion + +_hub_installed: bool +try: + import huggingface_hub + + _hub_installed = True +except ImportError: + _hub_installed = False + +logger = logging.getLogger(__name__) + + +def _assert_hub_installed() -> None: + if not _hub_installed: + raise ImportError( + "Please install the `huggingface_hub` package to use this method.\n" + "Run `pip install mistral-common[hf-hub]` to install it." + ) + + +def chunks(lst: List[str], chunk_size: int) -> Iterator[List[str]]: + r"""Chunk a list into smaller lists of a given size. + + Args: + lst: The list to chunk. + chunk_size: The size of each chunk. + + Returns: + An iterator over the chunks. + + Examples: + >>> all_chunks = list(chunks([1, 2, 3, 4, 5], 2)) + """ + for i in range(0, len(lst), chunk_size): + yield lst[i : i + chunk_size] + + +def list_local_hf_repo_files(repo_id: str, revision: Optional[str]) -> list[str]: + r"""List the files of a local Hugging Face repo. + + Args: + repo_id: The Hugging Face repo ID. + revision: The revision of the model to use. If `None`, the latest revision will be used. + """ + _assert_hub_installed() + + repo_cache = Path(huggingface_hub.constants.HF_HUB_CACHE) / huggingface_hub.constants.REPO_ID_SEPARATOR.join( + ["models", *repo_id.split("/")] + ) + + if revision is None: + revision_file = repo_cache / "refs" / huggingface_hub.constants.DEFAULT_REVISION + if revision_file.is_file(): + with revision_file.open("r") as file: + revision = file.read() + + if revision: + revision_dir = repo_cache / "snapshots" / revision + if revision_dir.is_dir(): + return os.listdir(revision_dir) + + return [] + + +def _filter_valid_tokenizer_files(files: List[str]) -> List[str]: + r"""Filter the valid tokenizer files from a list of files.""" + valid_tokenizer_files = [] + + instruct_versions = list(TokenizerVersion.__members__) + mm_versions = list(MultiModalVersion.__members__) + [""] # allow no mm version + sentencepiece_suffixes = [f".model.{v}{m}" for v in instruct_versions for m in mm_versions] + [".model"] + + for file in files: + pathlib_repo_file = Path(file) + file_name = pathlib_repo_file.name + suffix = "".join(pathlib_repo_file.suffixes) + if file_name == "tekken.json": + valid_tokenizer_files.append(file_name) + elif suffix in sentencepiece_suffixes: + valid_tokenizer_files.append(file_name) + + return valid_tokenizer_files + + +def download_tokenizer_from_hf_hub( + repo_id: str, + cache_dir: Optional[Union[str, Path]] = None, + token: Optional[Union[bool, str]] = None, + revision: Optional[str] = None, + force_download: bool = False, + local_files_only: bool = False, +) -> str: + r"""Download the tokenizer file of a Mistral model from the Hugging Face Hub. + + See [here](https://huggingface.co/mistralai/models) for a list of our OSS models. + + Note: + You need to install the `huggingface_hub` package to use this method. + + Please run `pip install mistral-common[hf-hub]` to install it. + + Args: + repo_id: The Hugging Face repo ID. + cache_dir: The directory where the tokenizer will be cached. + token: The Hugging Face token to use to download the tokenizer. + revision: The revision of the model to use. If `None`, the latest revision will be used. + force_download: Whether to force the download of the tokenizer. If `True`, the tokenizer will be downloaded + even if it is already cached. + local_files_only: Whether to only use local files. If `True`, the tokenizer will be downloaded only if it is + already cached. + + Returns: + The downloaded tokenizer local path for the given model ID. + """ + _assert_hub_installed() + + if force_download and local_files_only: + raise ValueError("You cannot force the download of the tokenizer if you only want to use local files.") + + if not local_files_only: + try: + hf_api = huggingface_hub.HfApi() + repo_files = hf_api.list_repo_files(repo_id) + local_files_only = False + except (requests.ConnectionError, requests.HTTPError, requests.Timeout) as e: + if force_download: + raise e + + repo_files = list_local_hf_repo_files(repo_id=repo_id, revision=revision) + local_files_only = True + + logger.info("Could not connect to the Hugging Face Hub. Using local files only.") + + if len(repo_files) == 0: + raise FileNotFoundError( + f"Could not connect to the Hugging Face Hub and no local files were found for the repo ID {repo_id}" + f" and revision {revision}. Please check your internet connection and try again." + ) from e + else: + repo_files = list_local_hf_repo_files(repo_id=repo_id, revision=revision) + if len(repo_files) == 0: + raise FileNotFoundError( + f"No local files found for the repo ID {repo_id} and revision {revision}. Please check the repo ID and" + " the revision or try to download the tokenizer without setting `local_files_only` to `True`." + ) + + valid_tokenizer_files = _filter_valid_tokenizer_files(repo_files) + + if len(valid_tokenizer_files) == 0: + raise ValueError(f"No tokenizer file found for model ID: {repo_id}") + # If there are multiple tokenizer files, we use tekken.json if it exists, otherwise the versioned one. + if len(valid_tokenizer_files) > 1: + if "tekken.json" in valid_tokenizer_files: + tokenizer_file = "tekken.json" + else: + tokenizer_file = sorted(valid_tokenizer_files)[-1] + logger.warning(f"Multiple tokenizer files found for model ID: {repo_id}. Using {tokenizer_file}.") + else: + tokenizer_file = valid_tokenizer_files[0] + + tokenizer_path = huggingface_hub.hf_hub_download( + repo_id=repo_id, + cache_dir=cache_dir, + filename=tokenizer_file, + token=token, + revision=revision, + local_files_only=local_files_only, + force_download=force_download, + ) + return tokenizer_path diff --git a/venv/lib/python3.10/site-packages/ray/rllib/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c71e5328ed2e75f750f2389a0be277d9e4a4ae1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..013cc706e5a9e6db45925aefd8a4cdeded8eaefc Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actor_manager.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actor_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1858f30747d879dd9d99b9790b68e928a702ae5c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actor_manager.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actors.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actors.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54279b693948bbe2dec7051b1047de566e922a37 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/actors.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/annotations.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/annotations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3ff298132ec7775ce56ba775549a334ce7bc278 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/annotations.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/checkpoints.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/checkpoints.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c93360a4d082f02fd2afbd225455421eb3952fd Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/checkpoints.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/compression.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/compression.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3376e716ef25c8ea50302aa7bed918e49abbdd0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/compression.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8244ed5ede9ec122c1a217b01d71b0255b095f4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/deprecation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/error.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/error.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1419b2de241f3c0a139b95a5d10feca57b2331f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/error.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/filter.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/filter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77ccd7bde3718f28901b7c4b6a4b79d850aa0c59 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/filter.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/filter_manager.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/filter_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcde1d20a6bc144d2503d66c6caf5b8d13009e88 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/filter_manager.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/framework.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/framework.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72b933ddc39cc6c311d160c958afbb38a0cf0289 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/framework.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec623eb448e4e2305788da1055df5c15459df30e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/from_config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/images.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/images.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0254f12fd791f5a3bfaedf2eef122aa1cb6c1182 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/images.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/lambda_defaultdict.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/lambda_defaultdict.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfd2952a6d498e1634271521124fe3ba5feeaea9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/lambda_defaultdict.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/memory.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/memory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..304f0a78671b7d5972c6c2b271b31d3f7caaf196 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/memory.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/minibatch_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/minibatch_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c090898a0912801bdc01e61ddcb6f5c33161829e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/minibatch_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/numpy.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/numpy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcaed4fd7e4e973732e76f2b4bac42d28e6488ec Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/numpy.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/policy.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/policy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e57e0ceee040bcb3dc1e2eb6d4fbc736d8e796f5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/policy.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/serialization.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/serialization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b514b61ef9aad5151a4b567837a1c83ef97be86 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/serialization.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/sgd.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/sgd.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb93f3a87261813ccd4827ce98f5197d12b95f74 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/sgd.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tensor_dtype.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tensor_dtype.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cffd977496be2012340ce2c9c4d722a0a5e470e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tensor_dtype.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/test_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/test_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b9fc769ccb20b9e721a450b2332b10079056f73 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/test_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94a3b67807bd2e462ca768c4426cabe77343efcd Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_run_builder.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1894f804225ad317fcd4b95ebd9f52202b5ce998 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/tf_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/threading.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/threading.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56fde3a5693c6d354cd9cc0f05cd6741c16839af Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/threading.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74a046af3c883af3534866fb72536d1559bedf91 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/torch_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/typing.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/typing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6389beef652032c4e1c5c95f62a82aadc938eee9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/__pycache__/typing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/slate_soft_q.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/slate_soft_q.py new file mode 100644 index 0000000000000000000000000000000000000000..5ed2205482e51890db8d0b069e53643b790e60b5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/slate_soft_q.py @@ -0,0 +1,46 @@ +from typing import Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import TensorType +from ray.rllib.utils.exploration.soft_q import SoftQ +from ray.rllib.utils.framework import try_import_tf, try_import_torch + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class SlateSoftQ(SoftQ): + @override(SoftQ) + def get_exploration_action( + self, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True, + ): + assert ( + self.framework == "torch" + ), "ERROR: SlateSoftQ only supports torch so far!" + + cls = type(action_distribution) + + # Re-create the action distribution with the correct temperature + # applied. + action_distribution = cls( + action_distribution.inputs, self.model, temperature=self.temperature + ) + batch_size = action_distribution.inputs.size()[0] + action_logp = torch.zeros(batch_size, dtype=torch.float) + + self.last_timestep = timestep + + # Explore. + if explore: + # Return stochastic sample over (q-value) logits. + action = action_distribution.sample() + # Return the deterministic "sample" (argmax) over (q-value) logits. + else: + action = action_distribution.deterministic_sample() + + return action, action_logp diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/soft_q.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/soft_q.py new file mode 100644 index 0000000000000000000000000000000000000000..b6d6fff533733fcf74ded42ffcbcba2d8eded55a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/soft_q.py @@ -0,0 +1,55 @@ +from gymnasium.spaces import Discrete, MultiDiscrete, Space +from typing import Union, Optional + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.tf.tf_action_dist import Categorical +from ray.rllib.models.torch.torch_action_dist import TorchCategorical +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.stochastic_sampling import StochasticSampling +from ray.rllib.utils.framework import TensorType + + +@OldAPIStack +class SoftQ(StochasticSampling): + """Special case of StochasticSampling w/ Categorical and temperature param. + + Returns a stochastic sample from a Categorical parameterized by the model + output divided by the temperature. Returns the argmax iff explore=False. + """ + + def __init__( + self, + action_space: Space, + *, + framework: Optional[str], + temperature: float = 1.0, + **kwargs + ): + """Initializes a SoftQ Exploration object. + + Args: + action_space: The gym action space used by the environment. + temperature: The temperature to divide model outputs by + before creating the Categorical distribution to sample from. + framework: One of None, "tf", "torch". + """ + assert isinstance(action_space, (Discrete, MultiDiscrete)) + super().__init__(action_space, framework=framework, **kwargs) + self.temperature = temperature + + @override(StochasticSampling) + def get_exploration_action( + self, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True, + ): + cls = type(action_distribution) + assert issubclass(cls, (Categorical, TorchCategorical)) + # Re-create the action distribution with the correct temperature + # applied. + dist = cls(action_distribution.inputs, self.model, temperature=self.temperature) + # Delegate to super method. + return super().get_exploration_action( + action_distribution=dist, timestep=timestep, explore=explore + ) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/stochastic_sampling.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/stochastic_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..d083d6ddd80770ed4acc4b4a456e70794ec8eab8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/stochastic_sampling.py @@ -0,0 +1,156 @@ +import functools +import gymnasium as gym +import numpy as np +from typing import Optional, Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.exploration.random import Random +from ray.rllib.utils.framework import ( + get_variable, + try_import_tf, + try_import_torch, + TensorType, +) +from ray.rllib.utils.tf_utils import zero_logps_from_actions + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class StochasticSampling(Exploration): + """An exploration that simply samples from a distribution. + + The sampling can be made deterministic by passing explore=False into + the call to `get_exploration_action`. + Also allows for scheduled parameters for the distributions, such as + lowering stddev, temperature, etc.. over time. + """ + + def __init__( + self, + action_space: gym.spaces.Space, + *, + framework: str, + model: ModelV2, + random_timesteps: int = 0, + **kwargs + ): + """Initializes a StochasticSampling Exploration object. + + Args: + action_space: The gym action space used by the environment. + framework: One of None, "tf", "torch". + model: The ModelV2 used by the owning Policy. + random_timesteps: The number of timesteps for which to act + completely randomly. Only after this number of timesteps, + actual samples will be drawn to get exploration actions. + """ + assert framework is not None + super().__init__(action_space, model=model, framework=framework, **kwargs) + + # Create the Random exploration module (used for the first n + # timesteps). + self.random_timesteps = random_timesteps + self.random_exploration = Random( + action_space, model=self.model, framework=self.framework, **kwargs + ) + + # The current timestep value (tf-var or python int). + self.last_timestep = get_variable( + np.array(0, np.int64), + framework=self.framework, + tf_name="timestep", + dtype=np.int64, + ) + + @override(Exploration) + def get_exploration_action( + self, + *, + action_distribution: ActionDistribution, + timestep: Optional[Union[int, TensorType]] = None, + explore: bool = True + ): + if self.framework == "torch": + return self._get_torch_exploration_action( + action_distribution, timestep, explore + ) + else: + return self._get_tf_exploration_action_op( + action_distribution, timestep, explore + ) + + def _get_tf_exploration_action_op(self, action_dist, timestep, explore): + ts = self.last_timestep + 1 + + stochastic_actions = tf.cond( + pred=tf.convert_to_tensor(ts < self.random_timesteps), + true_fn=lambda: ( + self.random_exploration.get_tf_exploration_action_op( + action_dist, explore=True + )[0] + ), + false_fn=lambda: action_dist.sample(), + ) + deterministic_actions = action_dist.deterministic_sample() + + action = tf.cond( + tf.constant(explore) if isinstance(explore, bool) else explore, + true_fn=lambda: stochastic_actions, + false_fn=lambda: deterministic_actions, + ) + + logp = tf.cond( + tf.math.logical_and( + explore, tf.convert_to_tensor(ts >= self.random_timesteps) + ), + true_fn=lambda: action_dist.sampled_action_logp(), + false_fn=functools.partial(zero_logps_from_actions, deterministic_actions), + ) + + # Increment `last_timestep` by 1 (or set to `timestep`). + if self.framework == "tf2": + self.last_timestep.assign_add(1) + return action, logp + else: + assign_op = ( + tf1.assign_add(self.last_timestep, 1) + if timestep is None + else tf1.assign(self.last_timestep, timestep) + ) + with tf1.control_dependencies([assign_op]): + return action, logp + + def _get_torch_exploration_action( + self, + action_dist: ActionDistribution, + timestep: Union[TensorType, int], + explore: Union[TensorType, bool], + ): + # Set last timestep or (if not given) increase by one. + self.last_timestep = ( + timestep if timestep is not None else self.last_timestep + 1 + ) + + # Apply exploration. + if explore: + # Random exploration phase. + if self.last_timestep < self.random_timesteps: + action, logp = self.random_exploration.get_torch_exploration_action( + action_dist, explore=True + ) + # Take a sample from our distribution. + else: + action = action_dist.sample() + logp = action_dist.sampled_action_logp() + + # No exploration -> Return deterministic actions. + else: + action = action_dist.deterministic_sample() + logp = torch.zeros_like(action_dist.sampled_action_logp()) + + return action, logp diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/thompson_sampling.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/thompson_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..3d4700790edb0adb100c28b259f210c231181d80 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/thompson_sampling.py @@ -0,0 +1,46 @@ +from typing import Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.framework import ( + TensorType, + try_import_tf, +) + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class ThompsonSampling(Exploration): + @override(Exploration) + def get_exploration_action( + self, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True, + ): + if self.framework == "torch": + return self._get_torch_exploration_action(action_distribution, explore) + elif self.framework == "tf2": + return self._get_tf_exploration_action(action_distribution, explore) + else: + raise NotImplementedError + + def _get_torch_exploration_action(self, action_dist, explore): + if explore: + return action_dist.inputs.argmax(dim=-1), None + else: + scores = self.model.predict(self.model.current_obs()) + return scores.argmax(dim=-1), None + + def _get_tf_exploration_action(self, action_dist, explore): + action = tf.argmax( + tf.cond( + pred=explore, + true_fn=lambda: action_dist.inputs, + false_fn=lambda: self.model.predict(self.model.current_obs()), + ), + axis=-1, + ) + return action, None diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/upper_confidence_bound.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/upper_confidence_bound.py new file mode 100644 index 0000000000000000000000000000000000000000..7e7e71efe187db0b1c42cd875acf03b70d949b6c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/exploration/upper_confidence_bound.py @@ -0,0 +1,44 @@ +from typing import Union + +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.framework import ( + TensorType, + try_import_tf, +) + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class UpperConfidenceBound(Exploration): + @override(Exploration) + def get_exploration_action( + self, + action_distribution: ActionDistribution, + timestep: Union[int, TensorType], + explore: bool = True, + ): + if self.framework == "torch": + return self._get_torch_exploration_action(action_distribution, explore) + elif self.framework == "tf2": + return self._get_tf_exploration_action(action_distribution, explore) + else: + raise NotImplementedError + + def _get_torch_exploration_action(self, action_dist, explore): + if explore: + return action_dist.inputs.argmax(dim=-1), None + else: + scores = self.model.value_function() + return scores.argmax(dim=-1), None + + def _get_tf_exploration_action(self, action_dist, explore): + action = tf.argmax( + tf.cond( + explore, lambda: action_dist.inputs, lambda: self.model.value_function() + ), + axis=-1, + ) + return action, None diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4212ec627dd8e26c4fd770b44d2507def8843ed Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/base.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d34af3e361fbaded2ab76511375e1a6ba3ce72f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/episode_replay_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/episode_replay_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a48691e0f176e67348c1c81cf7b2dd831fbab56 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/episode_replay_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/fifo_replay_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/fifo_replay_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..557cbd55d9f97daaf46756dd9e54bac27066464d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/fifo_replay_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_episode_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_episode_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01ca2ce3a5686b12d3dd552bab1aeac640d1ff81 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_episode_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_mixin_replay_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_mixin_replay_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0925197ee0f737cbfc4e1278792fc4a8fbef5709 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_mixin_replay_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_episode_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_episode_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f41c5d4d87b5f2f48708b4b8dc582df485701ea Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_episode_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_replay_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_replay_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0270d642ce3896c1134ef3c99e848475c3a8d9bb Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_prioritized_replay_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_replay_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_replay_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6eb9ee364448e7120015b352b49717c064dd43a Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/multi_agent_replay_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_episode_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_episode_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0884c98cfd0e277e88cf8b4712ab8704d9edb349 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_episode_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_replay_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_replay_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a03d1c79351a0bfdb279451f1cc2f2af59e499ba Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/prioritized_replay_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/replay_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/replay_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a95c8834bf74260a730c9a28773e13d6c142d31 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/replay_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/reservoir_replay_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/reservoir_replay_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f857ddd40479e84af0cac96b752e52891c268219 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/reservoir_replay_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/simple_replay_buffer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/simple_replay_buffer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a6300c641a565f2c5d899057456540a1d34d643 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/simple_replay_buffer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0867ab37e750ee828d433aa35880edda87fe487 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/episode_replay_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/episode_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..317125265bbf3e1ed693c92f0e8361eb275d0d3e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/episode_replay_buffer.py @@ -0,0 +1,1475 @@ +from collections import deque +import copy +import hashlib +from typing import Any, Dict, List, Optional, Tuple, Union + +import numpy as np +import scipy + +from ray.rllib.core import DEFAULT_AGENT_ID, DEFAULT_MODULE_ID +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.env.utils.infinite_lookback_buffer import InfiniteLookbackBuffer +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.metrics import ( + ACTUAL_N_STEP, + AGENT_ACTUAL_N_STEP, + AGENT_STEP_UTILIZATION, + ENV_STEP_UTILIZATION, + MODULE_STEP_UTILIZATION, + MODULE_ACTUAL_N_STEP, + NUM_AGENT_EPISODES_STORED, + NUM_AGENT_EPISODES_ADDED, + NUM_AGENT_EPISODES_ADDED_LIFETIME, + NUM_AGENT_EPISODES_EVICTED, + NUM_AGENT_EPISODES_EVICTED_LIFETIME, + NUM_AGENT_EPISODES_PER_SAMPLE, + NUM_AGENT_RESAMPLES, + NUM_AGENT_STEPS_STORED, + NUM_AGENT_STEPS_ADDED, + NUM_AGENT_STEPS_ADDED_LIFETIME, + NUM_AGENT_STEPS_EVICTED, + NUM_AGENT_STEPS_EVICTED_LIFETIME, + NUM_AGENT_STEPS_PER_SAMPLE, + NUM_AGENT_STEPS_PER_SAMPLE_LIFETIME, + NUM_AGENT_STEPS_SAMPLED, + NUM_AGENT_STEPS_SAMPLED_LIFETIME, + NUM_ENV_STEPS_STORED, + NUM_ENV_STEPS_ADDED, + NUM_ENV_STEPS_ADDED_LIFETIME, + NUM_ENV_STEPS_EVICTED, + NUM_ENV_STEPS_EVICTED_LIFETIME, + NUM_ENV_STEPS_PER_SAMPLE, + NUM_ENV_STEPS_PER_SAMPLE_LIFETIME, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_EPISODES_STORED, + NUM_EPISODES_ADDED, + NUM_EPISODES_ADDED_LIFETIME, + NUM_EPISODES_EVICTED, + NUM_EPISODES_EVICTED_LIFETIME, + NUM_EPISODES_PER_SAMPLE, + NUM_MODULE_EPISODES_STORED, + NUM_MODULE_EPISODES_ADDED, + NUM_MODULE_EPISODES_ADDED_LIFETIME, + NUM_MODULE_EPISODES_EVICTED, + NUM_MODULE_EPISODES_EVICTED_LIFETIME, + NUM_MODULE_EPISODES_PER_SAMPLE, + NUM_MODULE_RESAMPLES, + NUM_MODULE_STEPS_ADDED, + NUM_MODULE_STEPS_ADDED_LIFETIME, + NUM_MODULE_STEPS_EVICTED, + NUM_MODULE_STEPS_EVICTED_LIFETIME, + NUM_MODULE_STEPS_PER_SAMPLE, + NUM_MODULE_STEPS_PER_SAMPLE_LIFETIME, + NUM_MODULE_STEPS_SAMPLED, + NUM_MODULE_STEPS_SAMPLED_LIFETIME, + NUM_RESAMPLES, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.replay_buffers.base import ReplayBufferInterface +from ray.rllib.utils.typing import AgentID, ModuleID, SampleBatchType, ResultDict + + +class EpisodeReplayBuffer(ReplayBufferInterface): + """Buffer that stores (completed or truncated) episodes by their ID. + + Each "row" (a slot in a deque) in the buffer is occupied by one episode. If an + incomplete episode is added to the buffer and then another chunk of that episode is + added at a later time, the buffer will automatically concatenate the new fragment to + the original episode. This way, episodes can be completed via subsequent `add` + calls. + + Sampling returns batches of size B (number of "rows"), where each row is a + trajectory of length T. Each trajectory contains consecutive timesteps from an + episode, but might not start at the beginning of that episode. Should an episode end + within such a trajectory, a random next episode (starting from its t0) will be + concatenated to that "row". Example: `sample(B=2, T=4)` -> + + 0 .. 1 .. 2 .. 3 <- T-axis + 0 e5 e6 e7 e8 + 1 f2 f3 h0 h2 + ^ B-axis + + .. where e, f, and h are different (randomly picked) episodes, the 0-index (e.g. h0) + indicates the start of an episode, and `f3` is an episode end (gym environment + returned terminated=True or truncated=True). + + 0-indexed returned timesteps contain the reset observation, a dummy 0.0 reward, as + well as the first action taken in the episode (action picked after observing + obs(0)). + The last index in an episode (e.g. f3 in the example above) contains the final + observation of the episode, the final reward received, a dummy action + (repeat the previous action), as well as either terminated=True or truncated=True. + """ + + __slots__ = ( + "capacity", + "batch_size_B", + "batch_length_T", + "episodes", + "episode_id_to_index", + "num_episodes_evicted", + "_indices", + "_num_timesteps", + "_num_timesteps_added", + "sampled_timesteps", + "rng", + ) + + def __init__( + self, + capacity: int = 10000, + *, + batch_size_B: int = 16, + batch_length_T: int = 64, + metrics_num_episodes_for_smoothing: int = 100, + **kwargs, + ): + """Initializes an EpisodeReplayBuffer instance. + + Args: + capacity: The total number of timesteps to be storable in this buffer. + Will start ejecting old episodes once this limit is reached. + batch_size_B: The number of rows in a SampleBatch returned from `sample()`. + batch_length_T: The length of each row in a SampleBatch returned from + `sample()`. + """ + self.capacity = capacity + self.batch_size_B = batch_size_B + self.batch_length_T = batch_length_T + + # The actual episode buffer. We are using a deque here for faster insertion + # (left side) and eviction (right side) of data. + self.episodes = deque() + # Maps (unique) episode IDs to the index under which to find this episode + # within our `self.episodes` deque. + # Note that even after eviction started, the indices in here will NOT be + # changed. We will therefore need to offset all indices in + # `self.episode_id_to_index` by the number of episodes that have already been + # evicted (self._num_episodes_evicted) in order to get the actual index to use + # on `self.episodes`. + self.episode_id_to_index = {} + # The number of episodes that have already been evicted from the buffer + # due to reaching capacity. + self._num_episodes_evicted = 0 + + # List storing all index tuples: (eps_idx, ts_in_eps_idx), where ... + # `eps_idx - self._num_episodes_evicted' is the index into self.episodes. + # `ts_in_eps_idx` is the timestep index within that episode + # (0 = 1st timestep, etc..). + # We sample uniformly from the set of these indices in a `sample()` + # call. + self._indices = [] + + # The size of the buffer in timesteps. + self._num_timesteps = 0 + # The number of timesteps added thus far. + self._num_timesteps_added = 0 + + # How many timesteps have been sampled from the buffer in total? + self.sampled_timesteps = 0 + + self.rng = np.random.default_rng(seed=None) + + # Initialize the metrics. + self.metrics = MetricsLogger() + self._metrics_num_episodes_for_smoothing = metrics_num_episodes_for_smoothing + + # Initialize the metrics. + self.metrics = MetricsLogger() + self._metrics_num_episodes_for_smoothing = metrics_num_episodes_for_smoothing + + @override(ReplayBufferInterface) + def __len__(self) -> int: + return self.get_num_timesteps() + + @override(ReplayBufferInterface) + def add(self, episodes: Union[List["SingleAgentEpisode"], "SingleAgentEpisode"]): + """Converts incoming SampleBatch into a number of SingleAgentEpisode objects. + + Then adds these episodes to the internal deque. + """ + episodes = force_list(episodes) + + # Set up some counters for metrics. + num_env_steps_added = 0 + agent_to_num_steps_added = {DEFAULT_AGENT_ID: 0} + module_to_num_steps_added = {DEFAULT_MODULE_ID: 0} + num_episodes_added = 0 + agent_to_num_episodes_added = {DEFAULT_AGENT_ID: 0} + module_to_num_episodes_added = {DEFAULT_MODULE_ID: 0} + num_episodes_evicted = 0 + agent_to_num_episodes_evicted = {DEFAULT_AGENT_ID: 0} + module_to_num_episodes_evicted = {DEFAULT_MODULE_ID: 0} + num_env_steps_evicted = 0 + agent_to_num_steps_evicted = {DEFAULT_AGENT_ID: 0} + module_to_num_steps_evicted = {DEFAULT_MODULE_ID: 0} + + for eps in episodes: + # Make sure we don't change what's coming in from the user. + # TODO (sven): It'd probably be better to make sure in the EnvRunner to not + # hold on to episodes (for metrics purposes only) that we are returning + # back to the user from `EnvRunner.sample()`. Then we wouldn't have to + # do any copying. Instead, either compile the metrics right away on the + # EnvRunner OR compile metrics entirely on the Algorithm side (this is + # actually preferred). + eps = copy.deepcopy(eps) + + eps_len = len(eps) + # TODO (simon): Check, if we can deprecate these two + # variables and instead peek into the metrics. + self._num_timesteps += eps_len + self._num_timesteps_added += eps_len + num_env_steps_added += eps_len + agent_to_num_steps_added[DEFAULT_AGENT_ID] += eps_len + module_to_num_steps_added[DEFAULT_MODULE_ID] += eps_len + + # Ongoing episode, concat to existing record. + if eps.id_ in self.episode_id_to_index: + eps_idx = self.episode_id_to_index[eps.id_] + existing_eps = self.episodes[eps_idx - self._num_episodes_evicted] + old_len = len(existing_eps) + self._indices.extend([(eps_idx, old_len + i) for i in range(len(eps))]) + existing_eps.concat_episode(eps) + # New episode. Add to end of our episodes deque. + else: + num_episodes_added += 1 + agent_to_num_episodes_added[DEFAULT_AGENT_ID] += 1 + module_to_num_episodes_added[DEFAULT_MODULE_ID] += 1 + self.episodes.append(eps) + eps_idx = len(self.episodes) - 1 + self._num_episodes_evicted + self.episode_id_to_index[eps.id_] = eps_idx + self._indices.extend([(eps_idx, i) for i in range(len(eps))]) + + # Eject old records from front of deque (only if we have more than 1 episode + # in the buffer). + while self._num_timesteps > self.capacity and self.get_num_episodes() > 1: + # Eject oldest episode. + evicted_eps = self.episodes.popleft() + evicted_eps_len = len(evicted_eps) + num_episodes_evicted += 1 + num_env_steps_evicted += evicted_eps_len + agent_to_num_episodes_evicted[DEFAULT_AGENT_ID] += 1 + module_to_num_episodes_evicted[DEFAULT_MODULE_ID] += 1 + agent_to_num_steps_evicted[ + DEFAULT_AGENT_ID + ] += evicted_eps.agent_steps() + module_to_num_steps_evicted[ + DEFAULT_MODULE_ID + ] += evicted_eps.agent_steps() + # Correct our size. + self._num_timesteps -= evicted_eps_len + + # Erase episode from all our indices: + # 1) Main episode index. + evicted_idx = self.episode_id_to_index[evicted_eps.id_] + del self.episode_id_to_index[evicted_eps.id_] + # 2) All timestep indices that this episode owned. + new_indices = [] # New indices that will replace self._indices. + idx_cursor = 0 + # Loop through all (eps_idx, ts_in_eps_idx)-tuples. + for i, idx_tuple in enumerate(self._indices): + # This tuple is part of the evicted episode -> Add everything + # up until here to `new_indices` (excluding this very index, b/c + # it's already part of the evicted episode). + if idx_cursor is not None and idx_tuple[0] == evicted_idx: + new_indices.extend(self._indices[idx_cursor:i]) + # Set to None to indicate we are in the eviction zone. + idx_cursor = None + # We are/have been in the eviction zone (i pointing/pointed to the + # evicted episode) .. + elif idx_cursor is None: + # ... but are now not anymore (i is now an index into a + # non-evicted episode) -> Set cursor to valid int again. + if idx_tuple[0] != evicted_idx: + idx_cursor = i + # But early-out if evicted episode was only 1 single + # timestep long. + if evicted_eps_len == 1: + break + # Early-out: We reached the end of the to-be-evicted episode. + # We can stop searching further here (all following tuples + # will NOT be in the evicted episode). + elif idx_tuple[1] == evicted_eps_len - 1: + assert self._indices[i + 1][0] != idx_tuple[0] + idx_cursor = i + 1 + break + + # Jump over (splice-out) the evicted episode if we are still in the + # eviction zone. + if idx_cursor is not None: + new_indices.extend(self._indices[idx_cursor:]) + + # Reset our `self._indices` to the newly compiled list. + self._indices = new_indices + + # Increase episode evicted counter. + self._num_episodes_evicted += 1 + + # Update the metrics. + self._update_add_metrics( + num_episodes_added=num_episodes_added, + num_env_steps_added=num_env_steps_added, + num_episodes_evicted=num_episodes_evicted, + num_env_steps_evicted=num_env_steps_evicted, + agent_to_num_episodes_added=agent_to_num_episodes_added, + agent_to_num_steps_added=agent_to_num_steps_added, + agent_to_num_episodes_evicted=agent_to_num_episodes_evicted, + agent_to_num_steps_evicted=agent_to_num_steps_evicted, + module_to_num_episodes_added=module_to_num_steps_added, + module_to_num_steps_added=module_to_num_episodes_added, + module_to_num_episodes_evicted=module_to_num_episodes_evicted, + module_to_num_steps_evicted=module_to_num_steps_evicted, + ) + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def _update_add_metrics( + self, + *, + num_episodes_added: int, + num_env_steps_added: int, + num_episodes_evicted: int, + num_env_steps_evicted: int, + agent_to_num_episodes_added: Dict[AgentID, int], + agent_to_num_steps_added: Dict[AgentID, int], + agent_to_num_episodes_evicted: Dict[AgentID, int], + agent_to_num_steps_evicted: Dict[AgentID, int], + module_to_num_steps_added: Dict[ModuleID, int], + module_to_num_episodes_added: Dict[ModuleID, int], + module_to_num_episodes_evicted: Dict[ModuleID, int], + module_to_num_steps_evicted: Dict[ModuleID, int], + **kwargs, + ) -> None: + """Updates the replay buffer's adding metrics. + + Args: + num_episodes_added: The total number of episodes added to the + buffer in the `EpisodeReplayBuffer.add` call. + num_timesteps_added: The total number of environment steps added to the + buffer in the `EpisodeReplayBuffer.add` call. + num_episodes_evicted: The total number of environment steps evicted from + the buffer in the `EpisodeReplayBuffer.add` call. Note, this + does not include the number of episodes evicted before ever + added to the buffer (i.e. can happen in case a lot of episodes + were added and the buffer's capacity is not large enough). + num_env_steps_evicted: he total number of environment steps evicted from + the buffer in the `EpisodeReplayBuffer.add` call. Note, this + does not include the number of steps evicted before ever + added to the buffer (i.e. can happen in case a lot of episodes + were added and the buffer's capacity is not large enough). + agent_to_num_episodes_added: A dictionary with the number of episodes per + agent ID added to the buffer during the `EpisodeReplayBuffer.add` call. + agent_to_num_steps_added: A dictionary with the number of agent steps per + agent ID added to the buffer during the `EpisodeReplayBuffer.add` call. + agent_to_num_episodes_evicted: A dictionary with the number of episodes per + agent ID evicted to the buffer during the `EpisodeReplayBuffer.add` call. + agent_to_num_steps_evicted: A dictionary with the number of agent steps per + agent ID evicted to the buffer during the `EpisodeReplayBuffer.add` call. + module_to_num_episodes_added: A dictionary with the number of episodes per + module ID added to the buffer during the `EpisodeReplayBuffer.add` call. + module_to_num_steps_added: A dictionary with the number of agent steps per + module ID added to the buffer during the `EpisodeReplayBuffer.add` call. + module_to_num_episodes_evicted: A dictionary with the number of episodes per + module ID evicted to the buffer during the `EpisodeReplayBuffer.add` call. + module_to_num_steps_evicted: A dictionary with the number of agent steps per + module ID evicted to the buffer during the `EpisodeReplayBuffer.add` call. + """ + # Whole buffer episode metrics. + self.metrics.log_value( + NUM_EPISODES_STORED, + self.get_num_episodes(), + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + # Number of new episodes added. Note, this metric could + # be zero when ongoing episodes were logged. + self.metrics.log_value( + NUM_EPISODES_ADDED, + num_episodes_added, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_EPISODES_ADDED_LIFETIME, + num_episodes_added, + reduce="sum", + ) + self.metrics.log_value( + NUM_EPISODES_EVICTED, + num_episodes_evicted, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_EPISODES_EVICTED_LIFETIME, + num_episodes_evicted, + reduce="sum", + ) + # Whole buffer step metrics. + self.metrics.log_value( + NUM_ENV_STEPS_STORED, + self.get_num_timesteps(), + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + self.metrics.log_value( + NUM_ENV_STEPS_ADDED, + num_env_steps_added, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_ENV_STEPS_ADDED_LIFETIME, + num_env_steps_added, + reduce="sum", + ) + self.metrics.log_value( + NUM_ENV_STEPS_EVICTED, + num_env_steps_evicted, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_ENV_STEPS_EVICTED_LIFETIME, + num_env_steps_evicted, + reduce="sum", + ) + + # Log per-agent metrics. + for aid in agent_to_num_episodes_added: + # Number of new episodes added. Note, this metric could + # be zero. + self.metrics.log_value( + (NUM_AGENT_EPISODES_ADDED, aid), + agent_to_num_episodes_added[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_EPISODES_ADDED_LIFETIME, aid), + agent_to_num_episodes_added[aid], + reduce="sum", + ) + # Number of new agent steps added. Note, this metric could + # be zero, too. + self.metrics.log_value( + (NUM_AGENT_STEPS_ADDED, aid), + agent_to_num_steps_added[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_ADDED_LIFETIME, aid), + agent_to_num_steps_added[aid], + reduce="sum", + ) + for aid in agent_to_num_episodes_evicted: + # Number of agent episodes evicted. Note, values could be zero. + self.metrics.log_value( + (NUM_AGENT_EPISODES_EVICTED, aid), + agent_to_num_episodes_evicted[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_EPISODES_EVICTED_LIFETIME, aid), + agent_to_num_episodes_evicted[aid], + reduce="sum", + ) + # Number of agent steps evicted. Note, values could be zero. + self.metrics.log_value( + (NUM_AGENT_STEPS_EVICTED, aid), + agent_to_num_steps_evicted[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_EVICTED_LIFETIME, aid), + agent_to_num_steps_evicted[aid], + reduce="sum", + ) + # Note, we need to loop through the metrics here to receive + # metrics for all agents (not only the ones that steps). + for aid in self.metrics.stats[NUM_AGENT_STEPS_ADDED_LIFETIME]: + # Add default metrics for evicted episodes if not existent. + if aid not in agent_to_num_episodes_evicted: + self.metrics.log_value( + (NUM_AGENT_EPISODES_EVICTED, aid), + 0, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_EPISODES_EVICTED_LIFETIME, aid), + 0, + reduce="sum", + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_EVICTED, aid), + 0, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_EVICTED_LIFETIME, aid), + 0, + reduce="sum", + ) + # Number of episodes in the buffer. + agent_episodes_stored = self.metrics.peek( + (NUM_AGENT_EPISODES_ADDED_LIFETIME, aid) + ) - self.metrics.peek((NUM_AGENT_EPISODES_EVICTED_LIFETIME, aid)) + self.metrics.log_value( + (NUM_AGENT_EPISODES_STORED, aid), + agent_episodes_stored, + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + # Number of agent steps in the buffer. + agent_steps_stored = self.metrics.peek( + (NUM_AGENT_STEPS_ADDED_LIFETIME, aid) + ) - self.metrics.peek((NUM_AGENT_EPISODES_EVICTED_LIFETIME, aid)) + + self.metrics.log_value( + (NUM_AGENT_STEPS_STORED, aid), + agent_steps_stored, + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + + # Log per-module metrics. + for mid in module_to_num_episodes_added: + # Number of new episodes added. Note, this metric could + # be zero. + self.metrics.log_value( + (NUM_MODULE_EPISODES_ADDED, mid), + module_to_num_episodes_added[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_EPISODES_ADDED_LIFETIME, mid), + module_to_num_episodes_added[mid], + reduce="sum", + ) + # Number of new module steps added. Note, this metric could + # be zero, too. + self.metrics.log_value( + (NUM_MODULE_STEPS_ADDED, mid), + module_to_num_steps_added[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_ADDED_LIFETIME, mid), + module_to_num_steps_added[mid], + reduce="sum", + ) + for mid in module_to_num_episodes_evicted: + # Number of module episodes evicted. Note, values could be zero. + self.metrics.log_value( + (NUM_MODULE_EPISODES_EVICTED, mid), + module_to_num_episodes_evicted[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_EPISODES_EVICTED_LIFETIME, mid), + module_to_num_episodes_evicted[mid], + reduce="sum", + ) + # Number of module steps evicted. Note, values could be zero. + self.metrics.log_value( + (NUM_MODULE_STEPS_EVICTED, mid), + module_to_num_steps_evicted[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_EVICTED_LIFETIME, mid), + module_to_num_steps_evicted[mid], + reduce="sum", + ) + # Note, we need to loop through the metrics here to receive + # metrics for all agents (not only the ones that steps). + for mid in self.metrics.stats[NUM_MODULE_STEPS_ADDED_LIFETIME]: + # Number of episodes in the buffer. + if mid not in module_to_num_episodes_evicted: + self.metrics.log_value( + (NUM_MODULE_EPISODES_EVICTED, mid), + 0, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_EPISODES_EVICTED_LIFETIME, mid), + 0, + reduce="sum", + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_EVICTED, mid), + 0, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_EVICTED_LIFETIME, mid), + 0, + reduce="sum", + ) + module_episodes_stored = self.metrics.peek( + (NUM_MODULE_EPISODES_ADDED_LIFETIME, mid) + ) - self.metrics.peek((NUM_MODULE_EPISODES_EVICTED_LIFETIME, mid)) + self.metrics.log_value( + (NUM_MODULE_EPISODES_STORED, mid), + module_episodes_stored, + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + + @override(ReplayBufferInterface) + def sample( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + n_step: Optional[Union[int, Tuple]] = None, + beta: float = 0.0, + gamma: float = 0.99, + include_infos: bool = False, + include_extra_model_outputs: bool = False, + sample_episodes: Optional[bool] = False, + to_numpy: bool = False, + # TODO (simon): Check, if we need here 1 as default. + lookback: int = 0, + min_batch_length_T: int = 0, + **kwargs, + ) -> Union[SampleBatchType, SingleAgentEpisode]: + """Samples from a buffer in a randomized way. + + Each sampled item defines a transition of the form: + + `(o_t, a_t, sum(r_(t+1:t+n+1)), o_(t+n), terminated_(t+n), truncated_(t+n))` + + where `o_t` is drawn by randomized sampling.`n` is defined by the `n_step` + applied. + + If requested, `info`s of a transitions last timestep `t+n` and respective + extra model outputs (e.g. action log-probabilities) are added to + the batch. + + Args: + num_items: Number of items (transitions) to sample from this + buffer. + batch_size_B: The number of rows (transitions) to return in the + batch + batch_length_T: THe sequence length to sample. At this point in time + only sequences of length 1 are possible. + n_step: The n-step to apply. For the default the batch contains in + `"new_obs"` the observation and in `"obs"` the observation `n` + time steps before. The reward will be the sum of rewards + collected in between these two observations and the action will + be the one executed n steps before such that we always have the + state-action pair that triggered the rewards. + If `n_step` is a tuple, it is considered as a range to sample + from. If `None`, we use `n_step=1`. + gamma: The discount factor to be used when applying n-step calculations. + The default of `0.99` should be replaced by the `Algorithm`s + discount factor. + include_infos: A boolean indicating, if `info`s should be included in + the batch. This could be of advantage, if the `info` contains + values from the environment important for loss computation. If + `True`, the info at the `"new_obs"` in the batch is included. + include_extra_model_outputs: A boolean indicating, if + `extra_model_outputs` should be included in the batch. This could be + of advantage, if the `extra_mdoel_outputs` contain outputs from the + model important for loss computation and only able to compute with the + actual state of model e.g. action log-probabilities, etc.). If `True`, + the extra model outputs at the `"obs"` in the batch is included (the + timestep at which the action is computed). + to_numpy: If episodes should be numpy'ized. + lookback: A desired lookback. Any non-negative integer is valid. + min_batch_length_T: An optional minimal length when sampling sequences. It + ensures that sampled sequences are at least `min_batch_length_T` time + steps long. This can be used to prevent empty sequences during + learning, when using a burn-in period for stateful `RLModule`s. In rare + cases, such as when episodes are very short early in training, this may + result in longer sampling times. + + Returns: + Either a batch with transitions in each row or (if `return_episodes=True`) + a list of 1-step long episodes containing all basic episode data and if + requested infos and extra model outputs. + """ + + if sample_episodes: + return self._sample_episodes( + num_items=num_items, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + n_step=n_step, + beta=beta, + gamma=gamma, + include_infos=include_infos, + include_extra_model_outputs=include_extra_model_outputs, + to_numpy=to_numpy, + lookback=lookback, + min_batch_length_T=min_batch_length_T, + ) + else: + return self._sample_batch( + num_items=num_items, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + ) + + def _sample_batch( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + ) -> SampleBatchType: + """Returns a batch of size B (number of "rows"), where each row has length T. + + Each row contains consecutive timesteps from an episode, but might not start + at the beginning of that episode. Should an episode end within such a + row (trajectory), a random next episode (starting from its t0) will be + concatenated to that row. For more details, see the docstring of the + EpisodeReplayBuffer class. + + Args: + num_items: See `batch_size_B`. For compatibility with the + `ReplayBufferInterface` abstract base class. + batch_size_B: The number of rows (trajectories) to return in the batch. + batch_length_T: The length of each row (in timesteps) to return in the + batch. + + Returns: + The sampled batch (observations, actions, rewards, terminateds, truncateds) + of dimensions [B, T, ...]. + """ + if num_items is not None: + assert batch_size_B is None, ( + "Cannot call `sample()` with both `num_items` and `batch_size_B` " + "provided! Use either one." + ) + batch_size_B = num_items + + # Use our default values if no sizes/lengths provided. + batch_size_B = batch_size_B or self.batch_size_B + batch_length_T = batch_length_T or self.batch_length_T + + # Rows to return. + observations = [[] for _ in range(batch_size_B)] + actions = [[] for _ in range(batch_size_B)] + rewards = [[] for _ in range(batch_size_B)] + is_first = [[False] * batch_length_T for _ in range(batch_size_B)] + is_last = [[False] * batch_length_T for _ in range(batch_size_B)] + is_terminated = [[False] * batch_length_T for _ in range(batch_size_B)] + is_truncated = [[False] * batch_length_T for _ in range(batch_size_B)] + + # Store the unique episode buffer indices to determine sample variation. + sampled_episode_idxs = set() + # Store the unique env step buffer indices to determine sample variation + sampled_env_step_idxs = set() + + B = 0 + T = 0 + while B < batch_size_B: + # Pull a new uniform random index tuple: (eps_idx, ts_in_eps_idx). + index_tuple = self._indices[self.rng.integers(len(self._indices))] + + # Compute the actual episode index (offset by the number of + # already evicted episodes). + episode_idx, episode_ts = ( + index_tuple[0] - self._num_episodes_evicted, + index_tuple[1], + ) + episode = self.episodes[episode_idx] + + # Starting a new chunk, set is_first to True. + is_first[B][T] = True + + # Begin of new batch item (row). + if len(rewards[B]) == 0: + # And we are at the start of an episode: Set reward to 0.0. + if episode_ts == 0: + rewards[B].append(0.0) + # We are in the middle of an episode: Set reward to the previous + # timestep's values. + else: + rewards[B].append(episode.rewards[episode_ts - 1]) + # We are in the middle of a batch item (row). Concat next episode to this + # row from the next episode's beginning. In other words, we never concat + # a middle of an episode to another truncated one. + else: + episode_ts = 0 + rewards[B].append(0.0) + + observations[B].extend(episode.observations[episode_ts:]) + # Repeat last action to have the same number of actions than observations. + actions[B].extend(episode.actions[episode_ts:]) + actions[B].append(episode.actions[-1]) + # Number of rewards are also the same as observations b/c we have the + # initial 0.0 one. + rewards[B].extend(episode.rewards[episode_ts:]) + assert len(observations[B]) == len(actions[B]) == len(rewards[B]) + + T = min(len(observations[B]), batch_length_T) + + # Set is_last=True. + is_last[B][T - 1] = True + # If episode is terminated and we have reached the end of it, set + # is_terminated=True. + if episode.is_terminated and T == len(observations[B]): + is_terminated[B][T - 1] = True + # If episode is truncated and we have reached the end of it, set + # is_truncated=True. + elif episode.is_truncated and T == len(observations[B]): + is_truncated[B][T - 1] = True + + # We are done with this batch row. + if T == batch_length_T: + # We may have overfilled this row: Clip trajectory at the end. + observations[B] = observations[B][:batch_length_T] + actions[B] = actions[B][:batch_length_T] + rewards[B] = rewards[B][:batch_length_T] + # Start filling the next row. + B += 1 + T = 0 + # Add the episode buffer index to the set of episode indexes. + sampled_episode_idxs.add(episode_idx) + # Add the unique hashcode for the timestep. + sampled_env_step_idxs.add( + hashlib.sha256(f"{episode.id_}-{episode_ts}".encode()).hexdigest() + ) + + # Update our sampled counter. + self.sampled_timesteps += batch_size_B * batch_length_T + + # Update the sample metrics. + num_env_steps_sampled = batch_size_B * batch_length_T + num_episodes_per_sample = len(sampled_episode_idxs) + num_env_steps_per_sample = len(sampled_env_step_idxs) + num_resamples = 0 + agent_to_sample_size = {DEFAULT_AGENT_ID: num_env_steps_sampled} + agent_to_num_episodes_per_sample = {DEFAULT_AGENT_ID: num_episodes_per_sample} + agent_to_num_steps_per_sample = {DEFAULT_AGENT_ID: num_env_steps_per_sample} + agent_to_num_resamples = {DEFAULT_AGENT_ID: num_resamples} + module_to_num_steps_sampled = {DEFAULT_MODULE_ID: num_env_steps_sampled} + module_to_num_episodes_per_sample = {DEFAULT_MODULE_ID: num_episodes_per_sample} + module_to_num_steps_per_sample = {DEFAULT_MODULE_ID: num_env_steps_per_sample} + module_to_num_resamples = {DEFAULT_MODULE_ID: num_resamples} + self._update_sample_metrics( + num_env_steps_sampled=num_env_steps_sampled, + num_episodes_per_sample=num_episodes_per_sample, + num_env_steps_per_sample=num_env_steps_per_sample, + num_resamples=num_resamples, + sampled_n_step=None, + agent_to_num_steps_sampled=agent_to_sample_size, + agent_to_num_episodes_per_sample=agent_to_num_episodes_per_sample, + agent_to_num_steps_per_sample=agent_to_num_steps_per_sample, + agent_to_num_resamples=agent_to_num_resamples, + agent_to_sampled_n_step=None, + module_to_num_steps_sampled=module_to_num_steps_sampled, + module_to_num_episodes_per_sample=module_to_num_episodes_per_sample, + module_to_num_steps_per_sample=module_to_num_steps_per_sample, + module_to_num_resamples=module_to_num_resamples, + module_to_sampled_n_step=None, + ) + + # TODO: Return SampleBatch instead of this simpler dict. + ret = { + "obs": np.array(observations), + "actions": np.array(actions), + "rewards": np.array(rewards), + "is_first": np.array(is_first), + "is_last": np.array(is_last), + "is_terminated": np.array(is_terminated), + "is_truncated": np.array(is_truncated), + } + + return ret + + def _sample_episodes( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + n_step: Optional[Union[int, Tuple]] = None, + gamma: float = 0.99, + include_infos: bool = False, + include_extra_model_outputs: bool = False, + to_numpy: bool = False, + lookback: int = 1, + min_batch_length_T: int = 0, + **kwargs, + ) -> List[SingleAgentEpisode]: + """Samples episodes from a buffer in a randomized way. + + Each sampled item defines a transition of the form: + + `(o_t, a_t, sum(r_(t+1:t+n+1)), o_(t+n), terminated_(t+n), truncated_(t+n))` + + where `o_t` is drawn by randomized sampling.`n` is defined by the `n_step` + applied. + + If requested, `info`s of a transitions last timestep `t+n` and respective + extra model outputs (e.g. action log-probabilities) are added to + the batch. + + Args: + num_items: Number of items (transitions) to sample from this + buffer. + batch_size_B: The number of rows (transitions) to return in the + batch + batch_length_T: The sequence length to sample. Can be either `None` + (the default) or any positive integer. + n_step: The n-step to apply. For the default the batch contains in + `"new_obs"` the observation and in `"obs"` the observation `n` + time steps before. The reward will be the sum of rewards + collected in between these two observations and the action will + be the one executed n steps before such that we always have the + state-action pair that triggered the rewards. + If `n_step` is a tuple, it is considered as a range to sample + from. If `None`, we use `n_step=1`. + gamma: The discount factor to be used when applying n-step calculations. + The default of `0.99` should be replaced by the `Algorithm`s + discount factor. + include_infos: A boolean indicating, if `info`s should be included in + the batch. This could be of advantage, if the `info` contains + values from the environment important for loss computation. If + `True`, the info at the `"new_obs"` in the batch is included. + include_extra_model_outputs: A boolean indicating, if + `extra_model_outputs` should be included in the batch. This could be + of advantage, if the `extra_mdoel_outputs` contain outputs from the + model important for loss computation and only able to compute with the + actual state of model e.g. action log-probabilities, etc.). If `True`, + the extra model outputs at the `"obs"` in the batch is included (the + timestep at which the action is computed). + to_numpy: If episodes should be numpy'ized. + lookback: A desired lookback. Any non-negative integer is valid. + min_batch_length_T: An optional minimal length when sampling sequences. It + ensures that sampled sequences are at least `min_batch_length_T` time + steps long. This can be used to prevent empty sequences during + learning, when using a burn-in period for stateful `RLModule`s. In rare + cases, such as when episodes are very short early in training, this may + result in longer sampling times. + + Returns: + A list of 1-step long episodes containing all basic episode data and if + requested infos and extra model outputs. + """ + if num_items is not None: + assert batch_size_B is None, ( + "Cannot call `sample()` with both `num_items` and `batch_size_B` " + "provided! Use either one." + ) + batch_size_B = num_items + + # Use our default values if no sizes/lengths provided. + batch_size_B = batch_size_B or self.batch_size_B + + assert n_step is not None, ( + "When sampling episodes, `n_step` must be " + "provided, but `n_step` is `None`." + ) + # If no sequence should be sampled, we sample n-steps. + if not batch_length_T: + # Sample the `n_step`` itself, if necessary. + actual_n_step = n_step + random_n_step = isinstance(n_step, tuple) + # Otherwise we use an n-step of 1. + else: + assert ( + not isinstance(n_step, tuple) and n_step == 1 + ), "When sampling sequences n-step must be 1." + actual_n_step = n_step + + # Keep track of the indices that were sampled last for updating the + # weights later (see `ray.rllib.utils.replay_buffer.utils. + # update_priorities_in_episode_replay_buffer`). + self._last_sampled_indices = [] + + sampled_episodes = [] + # Record all the env step buffer indices that are contained in the sample. + sampled_env_step_idxs = set() + # Record all the episode buffer indices that are contained in the sample. + sampled_episode_idxs = set() + # Record all n-steps that have been used. + sampled_n_steps = [] + # Record all the env step buffer indices that are contained in the sample. + sampled_env_step_idxs = set() + # Record all the episode buffer indices that are contained in the sample. + sampled_episode_idxs = set() + # Record all n-steps that have been used. + sampled_n_steps = [] + + B = 0 + while B < batch_size_B: + # Pull a new uniform random index tuple: (eps_idx, ts_in_eps_idx). + index_tuple = self._indices[self.rng.integers(len(self._indices))] + + # Compute the actual episode index (offset by the number of + # already evicted episodes). + episode_idx, episode_ts = ( + index_tuple[0] - self._num_episodes_evicted, + index_tuple[1], + ) + episode = self.episodes[episode_idx] + + # If we use random n-step sampling, draw the n-step for this item. + if not batch_length_T and random_n_step: + actual_n_step = int(self.rng.integers(n_step[0], n_step[1])) + + # Skip, if we are too far to the end and `episode_ts` + n_step would go + # beyond the episode's end. + if min_batch_length_T > 0 and episode_ts + min_batch_length_T >= len( + episode + ): + continue + if episode_ts + (batch_length_T or 0) + (actual_n_step - 1) > len(episode): + actual_length = len(episode) + else: + actual_length = episode_ts + (batch_length_T or 0) + (actual_n_step - 1) + + # If no sequence should be sampled, we sample here the n-step. + if not batch_length_T: + sampled_episode = episode.slice( + slice( + episode_ts, + episode_ts + actual_n_step, + ) + ) + # Note, this will be the reward after executing action + # `a_(episode_ts-n_step+1)`. For `n_step>1` this will be the discounted + # sum of all discounted rewards that were collected over the last n + # steps. + raw_rewards = sampled_episode.get_rewards() + + rewards = scipy.signal.lfilter( + [1], [1, -gamma], raw_rewards[::-1], axis=0 + )[-1] + + sampled_episode = SingleAgentEpisode( + id_=sampled_episode.id_, + agent_id=sampled_episode.agent_id, + module_id=sampled_episode.module_id, + observation_space=sampled_episode.observation_space, + action_space=sampled_episode.action_space, + observations=[ + sampled_episode.get_observations(0), + sampled_episode.get_observations(-1), + ], + actions=[sampled_episode.get_actions(0)], + rewards=[rewards], + infos=[ + sampled_episode.get_infos(0), + sampled_episode.get_infos(-1), + ], + terminated=sampled_episode.is_terminated, + truncated=sampled_episode.is_truncated, + extra_model_outputs={ + **( + { + k: [episode.get_extra_model_outputs(k, 0)] + for k in episode.extra_model_outputs.keys() + } + if include_extra_model_outputs + else {} + ), + }, + t_started=episode_ts, + len_lookback_buffer=0, + ) + # Otherwise we simply slice the episode. + else: + sampled_episode = episode.slice( + slice( + episode_ts, + actual_length, + ), + len_lookback_buffer=lookback, + ) + # Record a has for the episode ID and timestep inside of the episode. + sampled_env_step_idxs.add( + hashlib.sha256(f"{episode.id_}-{episode_ts}".encode()).hexdigest() + ) + # Record a has for the episode ID and timestep inside of the episode. + sampled_env_step_idxs.add( + hashlib.sha256(f"{episode.id_}-{episode_ts}".encode()).hexdigest() + ) + # Remove reference to sampled episode. + del episode + + # Add the actually chosen n-step in this episode. + sampled_episode.extra_model_outputs["n_step"] = InfiniteLookbackBuffer( + np.full((len(sampled_episode) + lookback,), actual_n_step), + lookback=lookback, + ) + # Some loss functions need `weights` - which are only relevant when + # prioritizing. + sampled_episode.extra_model_outputs["weights"] = InfiniteLookbackBuffer( + np.ones((len(sampled_episode) + lookback,)), lookback=lookback + ) + + # Append the sampled episode. + sampled_episodes.append(sampled_episode) + sampled_episode_idxs.add(episode_idx) + sampled_n_steps.append(actual_n_step) + + # Increment counter. + B += (actual_length - episode_ts - (actual_n_step - 1) + 1) or 1 + + # Update the metric. + self.sampled_timesteps += batch_size_B + + # Update the sample metrics. + num_env_steps_sampled = batch_size_B + num_episodes_per_sample = len(sampled_episode_idxs) + num_env_steps_per_sample = len(sampled_env_step_idxs) + sampled_n_step = sum(sampled_n_steps) / batch_size_B + num_resamples = 0 + agent_to_num_steps_sampled = {DEFAULT_AGENT_ID: num_env_steps_sampled} + agent_to_num_episodes_per_sample = {DEFAULT_AGENT_ID: num_episodes_per_sample} + agent_to_num_steps_per_sample = {DEFAULT_AGENT_ID: num_env_steps_per_sample} + agent_to_sampled_n_step = {DEFAULT_AGENT_ID: sampled_n_step} + agent_to_num_resamples = {DEFAULT_AGENT_ID: num_resamples} + module_to_num_steps_sampled = {DEFAULT_MODULE_ID: num_env_steps_sampled} + module_to_num_episodes_per_sample = {DEFAULT_MODULE_ID: num_episodes_per_sample} + module_to_num_steps_per_sample = {DEFAULT_MODULE_ID: num_env_steps_per_sample} + module_to_sampled_n_step = {DEFAULT_MODULE_ID: sampled_n_step} + module_to_num_resamples = {DEFAULT_MODULE_ID: num_resamples} + self._update_sample_metrics( + num_env_steps_sampled=num_env_steps_sampled, + num_episodes_per_sample=num_episodes_per_sample, + num_env_steps_per_sample=num_env_steps_per_sample, + sampled_n_step=sampled_n_step, + num_resamples=num_resamples, + agent_to_num_steps_sampled=agent_to_num_steps_sampled, + agent_to_num_episodes_per_sample=agent_to_num_episodes_per_sample, + agent_to_num_steps_per_sample=agent_to_num_steps_per_sample, + agent_to_sampled_n_step=agent_to_sampled_n_step, + agent_to_num_resamples=agent_to_num_resamples, + module_to_num_steps_sampled=module_to_num_steps_sampled, + module_to_num_episodes_per_sample=module_to_num_episodes_per_sample, + module_to_num_steps_per_sample=module_to_num_steps_per_sample, + module_to_sampled_n_step=module_to_sampled_n_step, + module_to_num_resamples=module_to_num_resamples, + ) + + return sampled_episodes + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def _update_sample_metrics( + self, + *, + num_env_steps_sampled: int, + num_episodes_per_sample: int, + num_env_steps_per_sample: int, + sampled_n_step: Optional[float], + num_resamples: int, + agent_to_num_steps_sampled: Dict[AgentID, int], + agent_to_num_episodes_per_sample: Dict[AgentID, int], + agent_to_num_steps_per_sample: Dict[AgentID, int], + agent_to_sampled_n_step: Dict[AgentID, float], + agent_to_num_resamples: Dict[AgentID, int], + module_to_num_steps_sampled: Dict[ModuleID, int], + module_to_num_episodes_per_sample: Dict[ModuleID, int], + module_to_num_steps_per_sample: Dict[ModuleID, int], + module_to_sampled_n_step: Dict[ModuleID, float], + module_to_num_resamples: Dict[ModuleID, int], + **kwargs: Dict[str, Any], + ) -> None: + """Updates the replay buffer's sample metrics. + + Args: + num_env_steps_sampled: The number of environment steps sampled + this iteration in the `sample` method. + num_episodes_per_sample: The number of unique episodes in the + sample. + num_env_steps_per_sample: The number of unique environment steps + in the sample. + sampled_n_step: The mean n-step used in the sample. Note, this + is constant, if the n-step is not sampled. + num_resamples: The number of resamples in a single call to + `PrioritizedEpisodeReplayBuffer.sample`. A resampling is triggered + when the sampled timestep is to near to the episode end to cover the + required n-step. + agent_to_num_steps_sampled: A dictionary with the number of agent + steps per agent ID sampled during the `EpisodeReplayBuffer.sample` + call. + agent_to_num_episodes_per_sample: A dictionary with the number of + unique episodes per agent ID contained in the sample returned by + the `EpisodeReplayBuffer.sample` call. + agent_to_num_steps_per_sample: A dictionary with the number of + unique agent steps per agent ID contained in the sample returned by + the `EpisodeReplayBuffer.sample` call. + agent_to_sampled_n_step: A dictionary with the mean n-step per agent ID + used in the sample returned by the `EpisodeReplayBuffer.sample` call. + agent_to_num_resamples: A dictionary with the number of resamples per + agent ID in a single call to `PrioritizedEpisodeReplayBuffer.sample`. + A resampling is triggered when the sampled timestep is to near to the + episode end to cover the required n-step. + module_to_num_steps_sampled: A dictionary with the number of module + steps per module ID sampled during the `EpisodeReplayBuffer.sample` + call. + module_to_num_episodes_per_sample: A dictionary with the number of + unique episodes per module ID contained in the sample returned by + the `EpisodeReplayBuffer.sample` call. + module_to_num_steps_per_sample: A dictionary with the number of + unique module steps per module ID contained in the sample returned by + the `EpisodeReplayBuffer.sample` call. + module_to_sampled_n_step: A dictionary with the mean n-step per module ID + used in the sample returned by the `EpisodeReplayBuffer.sample` call. + module_to_num_resamples: A dictionary with the number of resamples per + module ID in a single call to `PrioritizedEpisodeReplayBuffer.sample`. + A resampling is triggered when the sampled timestep is to near to the + episode end to cover the required n-step. + """ + # Whole buffer sampled env steps metrics. + self.metrics.log_value( + NUM_EPISODES_PER_SAMPLE, + num_episodes_per_sample, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_ENV_STEPS_PER_SAMPLE, + num_env_steps_per_sample, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_ENV_STEPS_PER_SAMPLE_LIFETIME, + num_env_steps_per_sample, + reduce="sum", + ) + self.metrics.log_value( + NUM_ENV_STEPS_SAMPLED, + num_env_steps_sampled, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_ENV_STEPS_SAMPLED_LIFETIME, + num_env_steps_sampled, + reduce="sum", + ) + self.metrics.log_value( + ENV_STEP_UTILIZATION, + self.metrics.peek(NUM_ENV_STEPS_PER_SAMPLE_LIFETIME) + / self.metrics.peek(NUM_ENV_STEPS_SAMPLED_LIFETIME), + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + if sampled_n_step: + self.metrics.log_value( + ACTUAL_N_STEP, + sampled_n_step, + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + for aid in agent_to_sampled_n_step: + self.metrics.log_value( + (AGENT_ACTUAL_N_STEP, aid), + agent_to_sampled_n_step[aid], + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + for mid in module_to_sampled_n_step: + self.metrics.log_value( + (MODULE_ACTUAL_N_STEP, mid), + module_to_sampled_n_step[mid], + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + + self.metrics.log_value( + NUM_RESAMPLES, + num_resamples, + reduce="sum", + clear_on_reduce=True, + ) + + # Add per-agent metrics. + for aid in agent_to_num_steps_sampled: + self.metrics.log_value( + (NUM_AGENT_STEPS_SAMPLED, aid), + agent_to_num_steps_sampled[aid], + reduce="sum", + clear_on_reduce=True, + ) + # TODO (simon): Check, if we can then deprecate + # self.sampled_timesteps. + self.metrics.log_value( + (NUM_AGENT_STEPS_SAMPLED_LIFETIME, aid), + agent_to_num_steps_sampled[aid], + reduce="sum", + ) + self.metrics.log_value( + (NUM_AGENT_EPISODES_PER_SAMPLE, aid), + agent_to_num_episodes_per_sample[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_PER_SAMPLE, aid), + agent_to_num_steps_per_sample[aid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_PER_SAMPLE_LIFETIME, aid), + agent_to_num_steps_per_sample[aid], + reduce="sum", + ) + self.metrics.log_value( + (AGENT_STEP_UTILIZATION, aid), + self.metrics.peek((NUM_AGENT_STEPS_PER_SAMPLE_LIFETIME, aid)) + / self.metrics.peek((NUM_AGENT_STEPS_SAMPLED_LIFETIME, aid)), + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + self.metrics.log_value( + (NUM_AGENT_RESAMPLES, aid), + agent_to_num_resamples[aid], + reduce="sum", + clear_on_reduce=True, + ) + # Add per-module metrics. + for mid in module_to_num_steps_sampled: + self.metrics.log_value( + (NUM_MODULE_STEPS_SAMPLED, mid), + module_to_num_steps_sampled[mid], + reduce="sum", + clear_on_reduce=True, + ) + # TODO (simon): Check, if we can then deprecate + # self.sampled_timesteps. + self.metrics.log_value( + (NUM_MODULE_STEPS_SAMPLED_LIFETIME, mid), + module_to_num_steps_sampled[mid], + reduce="sum", + ) + self.metrics.log_value( + (NUM_MODULE_EPISODES_PER_SAMPLE, mid), + module_to_num_episodes_per_sample[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_PER_SAMPLE, mid), + module_to_num_steps_per_sample[mid], + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_PER_SAMPLE_LIFETIME, mid), + module_to_num_steps_per_sample[mid], + reduce="sum", + ) + self.metrics.log_value( + (MODULE_STEP_UTILIZATION, mid), + self.metrics.peek((NUM_MODULE_STEPS_PER_SAMPLE_LIFETIME, mid)) + / self.metrics.peek((NUM_MODULE_STEPS_SAMPLED_LIFETIME, mid)), + reduce="mean", + window=self._metrics_num_episodes_for_smoothing, + ) + self.metrics.log_value( + (NUM_MODULE_RESAMPLES, mid), + module_to_num_resamples[mid], + reduce="sum", + clear_on_reduce=True, + ) + + # TODO (simon): Check, if we can instead peek into the metrics + # and deprecate all variables. + def get_num_episodes(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of episodes (completed or truncated) stored in the buffer.""" + return len(self.episodes) + + def get_num_episodes_evicted(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of episodes that have been evicted from the buffer.""" + return self._num_episodes_evicted + + def get_num_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of individual timesteps stored in the buffer.""" + return len(self._indices) + + def get_sampled_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of timesteps that have been sampled in buffer's lifetime.""" + return self.sampled_timesteps + + def get_added_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of timesteps that have been added in buffer's lifetime.""" + return self._num_timesteps_added + + def get_metrics(self) -> ResultDict: + """Returns the metrics of the buffer and reduces them.""" + return self.metrics.reduce() + + @override(ReplayBufferInterface) + def get_state(self) -> Dict[str, Any]: + """Gets a pickable state of the buffer. + + This is used for checkpointing the buffer's state. It is specifically helpful, + for example, when a trial is paused and resumed later on. The buffer's state + can be saved to disk and reloaded when the trial is resumed. + + Returns: + A dict containing all necessary information to restore the buffer's state. + """ + return { + "episodes": [eps.get_state() for eps in self.episodes], + "episode_id_to_index": list(self.episode_id_to_index.items()), + "_num_episodes_evicted": self._num_episodes_evicted, + "_indices": self._indices, + "_num_timesteps": self._num_timesteps, + "_num_timesteps_added": self._num_timesteps_added, + "sampled_timesteps": self.sampled_timesteps, + } + + @override(ReplayBufferInterface) + def set_state(self, state) -> None: + """Sets the state of a buffer from a previously stored state. + + See `get_state()` for more information on what is stored in the state. This + method is used to restore the buffer's state from a previously stored state. + It is specifically helpful, for example, when a trial is paused and resumed + later on. The buffer's state can be saved to disk and reloaded when the trial + is resumed. + + Args: + state: The state to restore the buffer from. + """ + self._set_episodes(state) + self.episode_id_to_index = dict(state["episode_id_to_index"]) + self._num_episodes_evicted = state["_num_episodes_evicted"] + self._indices = state["_indices"] + self._num_timesteps = state["_num_timesteps"] + self._num_timesteps_added = state["_num_timesteps_added"] + self.sampled_timesteps = state["sampled_timesteps"] + + def _set_episodes(self, state) -> None: + """Sets the episodes from the state. + + Note, this method is used for class inheritance purposes. It is specifically + helpful when a subclass of this class wants to override the behavior of how + episodes are set from the state. By default, it sets `SingleAgentEpuisode`s, + but subclasses can override this method to set episodes of a different type. + """ + if not self.episodes: + self.episodes = deque( + [ + SingleAgentEpisode.from_state(eps_data) + for eps_data in state["episodes"] + ] + ) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/fifo_replay_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/fifo_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..53fbff25344ccaee729101963e1afb35d8ed229b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/fifo_replay_buffer.py @@ -0,0 +1,109 @@ +import numpy as np +from typing import Any, Dict, Optional + +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.replay_buffers.replay_buffer import ReplayBuffer, StorageUnit +from ray.rllib.utils.typing import SampleBatchType +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class FifoReplayBuffer(ReplayBuffer): + """This replay buffer implements a FIFO queue. + + Sometimes, e.g. for offline use cases, it may be desirable to use + off-policy algorithms without a Replay Buffer. + This FifoReplayBuffer can be used in-place to achieve the same effect + without having to introduce separate algorithm execution branches. + + For simplicity and efficiency reasons, this replay buffer stores incoming + sample batches as-is, and returns them one at time. + This is to avoid any additional load when this replay buffer is used. + """ + + def __init__(self, *args, **kwargs): + """Initializes a FifoReplayBuffer. + + Args: + ``*args`` : Forward compatibility args. + ``**kwargs``: Forward compatibility kwargs. + """ + # Completely by-passing underlying ReplayBuffer by setting its + # capacity to 1 (lowest allowed capacity). + ReplayBuffer.__init__(self, 1, StorageUnit.FRAGMENTS, **kwargs) + + self._queue = [] + + @DeveloperAPI + @override(ReplayBuffer) + def add(self, batch: SampleBatchType, **kwargs) -> None: + return self._queue.append(batch) + + @DeveloperAPI + @override(ReplayBuffer) + def sample(self, *args, **kwargs) -> Optional[SampleBatchType]: + """Sample a saved training batch from this buffer. + + Args: + ``*args`` : Forward compatibility args. + ``**kwargs``: Forward compatibility kwargs. + + Returns: + A single training batch from the queue. + """ + if len(self._queue) <= 0: + # Return empty SampleBatch if queue is empty. + return MultiAgentBatch({}, 0) + batch = self._queue.pop(0) + # Equal weights of 1.0. + batch["weights"] = np.ones(len(batch)) + return batch + + @DeveloperAPI + def update_priorities(self, *args, **kwargs) -> None: + """Update priorities of items at given indices. + + No-op for this replay buffer. + + Args: + ``*args`` : Forward compatibility args. + ``**kwargs``: Forward compatibility kwargs. + """ + pass + + @DeveloperAPI + @override(ReplayBuffer) + def stats(self, debug: bool = False) -> Dict: + """Returns the stats of this buffer. + + Args: + debug: If true, adds sample eviction statistics to the returned stats dict. + + Returns: + A dictionary of stats about this buffer. + """ + # As if this replay buffer has never existed. + return {} + + @DeveloperAPI + @override(ReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Returns all local state. + + Returns: + The serializable local state. + """ + # Pass through replay buffer does not save states. + return {} + + @DeveloperAPI + @override(ReplayBuffer) + def set_state(self, state: Dict[str, Any]) -> None: + """Restores all local state to the provided `state`. + + Args: + state: The new state to set this buffer. Can be obtained by calling + `self.get_state()`. + """ + pass diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_episode_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_episode_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..391fc0ff955e3c97e8c439b9717cbc33b5413430 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_episode_buffer.py @@ -0,0 +1,1179 @@ +import copy +from collections import defaultdict, deque +from gymnasium.core import ActType, ObsType +import hashlib +import numpy as np +import scipy +from typing import Any, Dict, List, Optional, Set, Tuple, Union + +from ray.rllib.core.columns import Columns +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.utils.replay_buffers.episode_replay_buffer import EpisodeReplayBuffer +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import ( + DeveloperAPI, + override, +) +from ray.rllib.utils.spaces.space_utils import batch +from ray.rllib.utils.typing import AgentID, ModuleID, SampleBatchType + + +@DeveloperAPI +class MultiAgentEpisodeReplayBuffer(EpisodeReplayBuffer): + """Multi-agent episode replay buffer that stores episodes by their IDs. + + This class implements a replay buffer as used in "playing Atari with Deep + Reinforcement Learning" (Mnih et al., 2013) for multi-agent reinforcement + learning, + + Each "row" (a slot in a deque) in the buffer is occupied by one episode. If an + incomplete episode is added to the buffer and then another chunk of that episode is + added at a later time, the buffer will automatically concatenate the new fragment to + the original episode. This way, episodes can be completed via subsequent `add` + calls. + + Sampling returns a size `B` episode list (number of 'rows'), where each episode + holds a tuple tuple of the form + + `(o_t, a_t, sum(r_t+1:t+n), o_t+n)` + + where `o_t` is the observation in `t`, `a_t` the action chosen at observation `o_t`, + `o_t+n` is the observation `n` timesteps later and `sum(r_t+1:t+n)` is the sum of + all rewards collected over the time steps between `t+1` and `t+n`. The `n`-step can + be chosen freely when sampling and defaults to `1`. If `n_step` is a tuple it is + sampled uniformly across the interval defined by the tuple (for each row in the + batch). + + Each episode contains - in addition to the data tuples presented above - two further + elements in its `extra_model_outputs`, namely `n_steps` and `weights`. The former + holds the `n_step` used for the sampled timesteps in the episode and the latter the + corresponding (importance sampling) weight for the transition. + + .. testcode:: + + import gymnasium as gym + + from ray.rllib.env.multi_agent_episode import MultiAgentEpisode + from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole + from ray.rllib.utils.replay_buffers import MultiAgentEpisodeReplayBuffer + + + # Create the environment. + env = MultiAgentCartPole({"num_agents": 2}) + + # Set up the loop variables + agent_ids = env.agents + agent_ids.append("__all__") + terminateds = {aid: False for aid in agent_ids} + truncateds = {aid: False for aid in agent_ids} + num_timesteps = 10000 + episodes = [] + + # Initialize the first episode entries. + eps = MultiAgentEpisode() + obs, infos = env.reset() + eps.add_env_reset(observations=obs, infos=infos) + + # Sample 10,000 env timesteps. + for i in range(num_timesteps): + # If terminated we create a new episode. + if eps.is_done: + episodes.append(eps.to_numpy()) + eps = MultiAgentEpisode() + terminateds = {aid: False for aid in agent_ids} + truncateds = {aid: False for aid in agent_ids} + obs, infos = env.reset() + eps.add_env_reset(observations=obs, infos=infos) + + # Sample a random action for all agents that should step in the episode + # next. + actions = { + aid: env.get_action_space(aid).sample() + for aid in eps.get_agents_to_act() + } + obs, rewards, terminateds, truncateds, infos = env.step(actions) + eps.add_env_step( + obs, + actions, + rewards, + infos, + terminateds=terminateds, + truncateds=truncateds + ) + + # Add the last (truncated) episode to the list of episodes. + if not eps.is_done: + episodes.append(eps) + + # Create the buffer. + buffer = MultiAgentEpisodeReplayBuffer() + # Add the list of episodes sampled. + buffer.add(episodes) + + # Pull a sample from the buffer using an `n-step` of 3. + sample = buffer.sample(num_items=256, gamma=0.95, n_step=3) + """ + + def __init__( + self, + capacity: int = 10000, + *, + batch_size_B: int = 16, + batch_length_T: int = 1, + metrics_num_episodes_for_smoothing: int = 100, + **kwargs, + ): + """Initializes a multi-agent episode replay buffer. + + Args: + capacity: The total number of timesteps to be storable in this buffer. + Will start ejecting old episodes once this limit is reached. + batch_size_B: The number of episodes returned from `sample()`. + batch_length_T: The length of each episode in the episode list returned from + `sample()`. + """ + # Initialize the base episode replay buffer. + super().__init__( + capacity=capacity, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + metrics_num_episodes_for_smoothing=metrics_num_episodes_for_smoothing, + **kwargs, + ) + + # Stores indices of module (single-agent) timesteps. Each index is a tuple + # of the form: + # `(ma_episode_idx, agent_id, timestep)`. + # This information is stored for each timestep of an episode and is used in + # the `"independent"`` sampling process. The multi-agent episode index amd the + # agent ID are used to retrieve the single-agent episode. The timestep is then + # needed to retrieve the corresponding timestep data from that single-agent + # episode. + self._module_to_indices: Dict[ + ModuleID, List[Tuple[int, AgentID, int]] + ] = defaultdict(list) + + # Stores the number of single-agent timesteps in the buffer. + self._num_agent_timesteps: int = 0 + # Stores the number of single-agent timesteps per module. + self._num_module_timesteps: Dict[ModuleID, int] = defaultdict(int) + + # Stores the number of added single-agent timesteps over the + # lifetime of the buffer. + self._num_agent_timesteps_added: int = 0 + # Stores the number of added single-agent timesteps per module + # over the lifetime of the buffer. + self._num_module_timesteps_added: Dict[ModuleID, int] = defaultdict(int) + + self._num_module_episodes: Dict[ModuleID, int] = defaultdict(int) + # Stores the number of module episodes evicted. Note, this is + # important for indexing. + self._num_module_episodes_evicted: Dict[ModuleID, int] = defaultdict(int) + + # Stores hte number of module timesteps sampled. + self.sampled_timesteps_per_module: Dict[ModuleID, int] = defaultdict(int) + + @override(EpisodeReplayBuffer) + def add( + self, + episodes: Union[List["MultiAgentEpisode"], "MultiAgentEpisode"], + ) -> None: + """Adds episodes to the replay buffer. + + Note, if the incoming episodes' time steps cause the buffer to overflow, + older episodes are evicted. Because episodes usually come in chunks and + not complete, this could lead to edge cases (e.g. with very small capacity + or very long episode length) where the first part of an episode is evicted + while the next part just comes in. + To defend against such case, the complete episode is evicted, including + the new chunk, unless the episode is the only one in the buffer. In the + latter case the buffer will be allowed to overflow in a temporary fashion, + i.e. during the next addition of samples to the buffer an attempt is made + to fall below capacity again. + + The user is advised to select a large enough buffer with regard to the maximum + expected episode length. + + Args: + episodes: The multi-agent episodes to add to the replay buffer. Can be a + single episode or a list of episodes. + """ + episodes: List["MultiAgentEpisode"] = force_list(episodes) + + new_episode_ids: Set[str] = {eps.id_ for eps in episodes} + total_env_timesteps = sum([eps.env_steps() for eps in episodes]) + self._num_timesteps += total_env_timesteps + self._num_timesteps_added += total_env_timesteps + + # Set up some counters for metrics. + num_env_steps_added = 0 + agent_to_num_steps_added = defaultdict(int) + module_to_num_steps_added = defaultdict(int) + num_episodes_added = 0 + agent_to_num_episodes_added = defaultdict(int) + module_to_num_episodes_added = defaultdict(int) + num_episodes_evicted = 0 + agent_to_num_episodes_evicted = defaultdict(int) + module_to_num_episodes_evicted = defaultdict(int) + num_env_steps_evicted = 0 + agent_to_num_steps_evicted = defaultdict(int) + module_to_num_steps_evicted = defaultdict(int) + + # Evict old episodes. + eps_evicted_ids: Set[Union[str, int]] = set() + eps_evicted_idxs: Set[int] = set() + while ( + self._num_timesteps > self.capacity + and self._num_remaining_episodes(new_episode_ids, eps_evicted_ids) != 1 + ): + # Evict episode. + evicted_episode = self.episodes.popleft() + eps_evicted_ids.add(evicted_episode.id_) + eps_evicted_idxs.add(self.episode_id_to_index.pop(evicted_episode.id_)) + # If this episode has a new chunk in the new episodes added, + # we subtract it again. + # TODO (sven, simon): Should we just treat such an episode chunk + # as a new episode? + if evicted_episode.id_ in new_episode_ids: + idx = next( + i + for i, eps in enumerate(episodes) + if eps.id_ == evicted_episode.id_ + ) + new_eps_to_evict = episodes.pop(idx) + self._num_timesteps -= new_eps_to_evict.env_steps() + self._num_timesteps_added -= new_eps_to_evict.env_steps() + # Remove the timesteps of the evicted episode from the counter. + self._num_timesteps -= evicted_episode.env_steps() + self._num_agent_timesteps -= evicted_episode.agent_steps() + self._num_episodes_evicted += 1 + # Increase the counters. + num_episodes_evicted += 1 + num_env_steps_evicted += evicted_episode.env_steps() + for aid, a_eps in evicted_episode.agent_episodes.items(): + mid = evicted_episode._agent_to_module_mapping[aid] + agent_to_num_episodes_evicted[aid] += 1 + module_to_num_episodes_evicted[mid] += 1 + agent_to_num_steps_evicted[aid] += a_eps.agent_steps() + module_to_num_steps_evicted[mid] += a_eps.agent_steps() + # Remove the module timesteps of the evicted episode from the counters. + self._evict_module_episodes(evicted_episode) + del evicted_episode + + # Add agent and module steps. + for eps in episodes: + self._num_agent_timesteps += eps.agent_steps() + self._num_agent_timesteps_added += eps.agent_steps() + # Update the module counters by the module timesteps. + self._update_module_counters(eps) + + # Remove corresponding indices, if episodes were evicted. + if eps_evicted_idxs: + # If the episode is not evicted, we keep the index. + # Note, each index 2-tuple is of the form (ma_episode_idx, timestep) + # and refers to a certain environment timestep in a certain + # multi-agent episode. + self._indices = [ + idx_tuple + for idx_tuple in self._indices + if idx_tuple[0] not in eps_evicted_idxs + ] + # Also remove corresponding module indices. + for module_id, module_indices in self._module_to_indices.items(): + # Each index 3-tuple is of the form + # (ma_episode_idx, agent_id, timestep) and refers to a certain + # agent timestep in a certain multi-agent episode. + self._module_to_indices[module_id] = [ + idx_triplet + for idx_triplet in module_indices + if idx_triplet[0] not in eps_evicted_idxs + ] + + for eps in episodes: + eps = copy.deepcopy(eps) + # If the episode is part of an already existing episode, concatenate. + if eps.id_ in self.episode_id_to_index: + eps_idx = self.episode_id_to_index[eps.id_] + existing_eps = self.episodes[eps_idx - self._num_episodes_evicted] + existing_len = len(existing_eps) + self._indices.extend( + [ + ( + eps_idx, + existing_len + i, + ) + for i in range(len(eps)) + ] + ) + # Add new module indices. + self._add_new_module_indices(eps, eps_idx, True) + # Concatenate the episode chunk. + existing_eps.concat_episode(eps) + # Otherwise, create a new entry. + else: + # New episode. + self.episodes.append(eps) + # Update the counters + num_episodes_added += 1 + for aid, a_eps in eps.agent_episodes.items(): + mid = eps._agent_to_module_mapping[aid] + agent_to_num_episodes_added[aid] += 1 + module_to_num_episodes_added[mid] += 1 + eps_idx = len(self.episodes) - 1 + self._num_episodes_evicted + self.episode_id_to_index[eps.id_] = eps_idx + self._indices.extend([(eps_idx, i) for i in range(len(eps))]) + # Add new module indices. + self._add_new_module_indices(eps, eps_idx, False) + # Update the step counters. + num_env_steps_added += eps.env_steps() + for aid, e_eps in eps.agent_episodes.items(): + mid = eps._agent_to_module_mapping[aid] + agent_to_num_steps_added[aid] += e_eps.agent_steps() + module_to_num_steps_added[mid] += e_eps.agent_steps() + + # Update the adding metrics. + self._update_add_metrics( + num_episodes_added=num_episodes_added, + num_env_steps_added=num_env_steps_added, + num_episodes_evicted=num_episodes_evicted, + num_env_steps_evicted=num_env_steps_evicted, + agent_to_num_episodes_added=agent_to_num_episodes_added, + agent_to_num_steps_added=agent_to_num_steps_added, + agent_to_num_episodes_evicted=agent_to_num_episodes_evicted, + agent_to_num_steps_evicted=agent_to_num_steps_evicted, + module_to_num_episodes_added=module_to_num_steps_added, + module_to_num_steps_added=module_to_num_episodes_added, + module_to_num_episodes_evicted=module_to_num_episodes_evicted, + module_to_num_steps_evicted=module_to_num_steps_evicted, + ) + + @override(EpisodeReplayBuffer) + def sample( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + n_step: Optional[Union[int, Tuple]] = 1, + gamma: float = 0.99, + include_infos: bool = False, + include_extra_model_outputs: bool = False, + replay_mode: str = "independent", + modules_to_sample: Optional[List[ModuleID]] = None, + **kwargs, + ) -> Union[List["MultiAgentEpisode"], List["SingleAgentEpisode"]]: + """Samples a batch of multi-agent transitions. + + Multi-agent transitions can be sampled either `"independent"` or + `"synchronized"` with the former sampling for each module independent agent + steps and the latter sampling agent transitions from the same environment step. + + The n-step parameter can be either a single integer or a tuple of two integers. + In the former case, the n-step is fixed to the given integer and in the latter + case, the n-step is sampled uniformly from the given range. Large n-steps could + potentially lead to a many retries because not all samples might have a full + n-step transition. + + Sampling returns batches of size B (number of 'rows'), where each row is a tuple + of the form + + `(o_t, a_t, sum(r_t+1:t+n), o_t+n)` + + where `o_t` is the observation in `t`, `a_t` the action chosen at observation + `o_t`, `o_t+n` is the observation `n` timesteps later and `sum(r_t+1:t+n)` is + the sum of all rewards collected over the time steps between `t+1` and `t+n`. + The n`-step can be chosen freely when sampling and defaults to `1`. If `n_step` + is a tuple it is sampled uniformly across the interval defined by the tuple (for + each row in the batch). + + Each batch contains - in addition to the data tuples presented above - two + further columns, namely `n_steps` and `weigths`. The former holds the `n_step` + used for each row in the batch and the latter a (default) weight of `1.0` for + each row in the batch. This weight is used for weighted loss calculations in + the training process. + + Args: + num_items: The number of items to sample. If provided, `batch_size_B` + should be `None`. + batch_size_B: The batch size to sample. If provided, `num_items` + should be `None`. + batch_length_T: The length of the sampled batch. If not provided, the + default batch length is used. This feature is not yet implemented. + n_step: The n-step to sample. If the n-step is a tuple, the n-step is + sampled uniformly from the given range. If not provided, the default + n-step of `1` is used. + gamma: The discount factor for the n-step reward calculation. + include_infos: Whether to include the infos in the sampled batch. + include_extra_model_outputs: Whether to include the extra model outputs + in the sampled batch. + replay_mode: The replay mode to use for sampling. Either `"independent"` + or `"synchronized"`. + modules_to_sample: A list of module IDs to sample from. If not provided, + transitions for aall modules are sampled. + + Returns: + A dictionary of the form `ModuleID -> SampleBatchType` containing the + sampled data for each module or each module in `modules_to_sample`, + if provided. + """ + if num_items is not None: + assert batch_size_B is None, ( + "Cannot call `sample()` with both `num_items` and `batch_size_B` " + "provided! Use either one." + ) + batch_size_B = num_items + + # Use our default values if no sizes/lengths provided. + batch_size_B = batch_size_B or self.batch_size_B + # TODO (simon): Implement trajectory sampling for RNNs. + batch_length_T = batch_length_T or self.batch_length_T + + # Sample for each module independently. + if replay_mode == "independent": + return self._sample_independent( + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + n_step=n_step, + gamma=gamma, + include_infos=include_infos, + include_extra_model_outputs=include_extra_model_outputs, + modules_to_sample=modules_to_sample, + ) + else: + return self._sample_synchonized( + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + n_step=n_step, + gamma=gamma, + include_infos=include_infos, + include_extra_model_outputs=include_extra_model_outputs, + modules_to_sample=modules_to_sample, + ) + + def get_added_agent_timesteps(self) -> int: + """Returns number of agent timesteps that have been added in buffer's lifetime. + + Note, this could be more than the `get_added_timesteps` returns as an + environment timestep could contain multiple agent timesteps (for eaxch agent + one). + """ + return self._num_agent_timesteps_added + + def get_module_ids(self) -> List[ModuleID]: + """Returns a list of module IDs stored in the buffer.""" + return list(self._module_to_indices.keys()) + + def get_num_agent_timesteps(self) -> int: + """Returns number of agent timesteps stored in the buffer. + + Note, this could be more than the `num_timesteps` as an environment timestep + could contain multiple agent timesteps (for eaxch agent one). + """ + return self._num_agent_timesteps + + @override(EpisodeReplayBuffer) + def get_num_episodes(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of episodes stored for a module in the buffer. + + Note, episodes could be either complete or truncated. + + Args: + module_id: The ID of the module to query. If not provided, the number of + episodes for all modules is returned. + + Returns: + The number of episodes stored for the module or all modules. + """ + return ( + self._num_module_episodes[module_id] + if module_id + else super().get_num_episodes() + ) + + @override(EpisodeReplayBuffer) + def get_num_episodes_evicted(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of episodes evicted for a module in the buffer.""" + return ( + self._num_module_episodes_evicted[module_id] + if module_id + else super().get_num_episodes_evicted() + ) + + @override(EpisodeReplayBuffer) + def get_num_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of individual timesteps for a module stored in the buffer. + + Args: + module_id: The ID of the module to query. If not provided, the number of + timesteps for all modules are returned. + + Returns: + The number of timesteps stored for the module or all modules. + """ + return ( + self._num_module_timesteps[module_id] + if module_id + else super().get_num_timesteps() + ) + + @override(EpisodeReplayBuffer) + def get_sampled_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns number of timesteps that have been sampled for a module. + + Args: + module_id: The ID of the module to query. If not provided, the number of + sampled timesteps for all modules are returned. + + Returns: + The number of timesteps sampled for the module or all modules. + """ + return ( + self.sampled_timesteps_per_module[module_id] + if module_id + else super().get_sampled_timesteps() + ) + + @override(EpisodeReplayBuffer) + def get_added_timesteps(self, module_id: Optional[ModuleID] = None) -> int: + """Returns the number of timesteps added in buffer's lifetime for given module. + + Args: + module_id: The ID of the module to query. If not provided, the total number + of timesteps ever added. + + Returns: + The number of timesteps added for `module_id` (or all modules if `module_id` + is None). + """ + return ( + self._num_module_timesteps_added[module_id] + if module_id + else super().get_added_timesteps() + ) + + @override(EpisodeReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Gets a pickable state of the buffer. + + This is used for checkpointing the buffer's state. It is specifically helpful, + for example, when a trial is paused and resumed later on. The buffer's state + can be saved to disk and reloaded when the trial is resumed. + + Returns: + A dict containing all necessary information to restore the buffer's state. + """ + return super().get_state() | { + "_module_to_indices": list(self._module_to_indices.items()), + "_num_agent_timesteps": self._num_agent_timesteps, + "_num_agent_timesteps_added": self._num_agent_timesteps_added, + "_num_module_timesteps": list(self._num_module_timesteps.items()), + "_num_module_timesteps_added": list( + self._num_module_timesteps_added.items() + ), + "_num_module_episodes": list(self._num_module_episodes.items()), + "_num_module_episodes_evicted": list( + self._num_module_episodes_evicted.items() + ), + "sampled_timesteps_per_module": list( + self.sampled_timesteps_per_module.items() + ), + } + + @override(EpisodeReplayBuffer) + def set_state(self, state) -> None: + """Sets the state of a buffer from a previously stored state. + + See `get_state()` for more information on what is stored in the state. This + method is used to restore the buffer's state from a previously stored state. + It is specifically helpful, for example, when a trial is paused and resumed + later on. The buffer's state can be saved to disk and reloaded when the trial + is resumed. + + Args: + state: The state to restore the buffer from. + """ + # Set the episodes. + self._set_episodes(state) + # Set the super's state. + super().set_state(state) + # Now set the remaining attributes. + self._module_to_indices = defaultdict(list, dict(state["_module_to_indices"])) + self._num_agent_timesteps = state["_num_agent_timesteps"] + self._num_agent_timesteps_added = state["_num_agent_timesteps_added"] + self._num_module_timesteps = defaultdict( + int, dict(state["_num_module_timesteps"]) + ) + self._num_module_timesteps_added = defaultdict( + int, dict(state["_num_module_timesteps_added"]) + ) + self._num_module_episodes = defaultdict( + int, dict(state["_num_module_episodes"]) + ) + self._num_module_episodes_evicted = defaultdict( + int, dict(state["_num_module_episodes_evicted"]) + ) + self.sampled_timesteps_per_module = defaultdict( + list, dict(state["sampled_timesteps_per_module"]) + ) + + def _set_episodes(self, state: Dict[str, Any]) -> None: + """Sets the episodes from the state.""" + if not self.episodes: + self.episodes = deque( + [ + MultiAgentEpisode.from_state(eps_data) + for eps_data in state["episodes"] + ] + ) + + def _sample_independent( + self, + batch_size_B: Optional[int], + batch_length_T: Optional[int], + n_step: Optional[Union[int, Tuple[int, int]]], + gamma: float, + include_infos: bool, + include_extra_model_outputs: bool, + modules_to_sample: Optional[Set[ModuleID]], + ) -> List["SingleAgentEpisode"]: + """Samples a batch of independent multi-agent transitions.""" + + actual_n_step = n_step or 1 + # Sample the n-step if necessary. + random_n_step = isinstance(n_step, (tuple, list)) + + sampled_episodes = [] + # Record the number of samples per module/agent/total. + num_env_steps_sampled = 0 + agent_to_num_steps_sampled = defaultdict(int) + module_to_num_steps_sampled = defaultdict(int) + # Record all the env step buffer indices that are contained in the sample. + sampled_env_step_idxs = set() + agent_to_sampled_env_step_idxs = defaultdict(set) + module_to_sampled_env_step_idxs = defaultdict(set) + # Record all the episode buffer indices that are contained in the sample. + sampled_episode_idxs = set() + agent_to_sampled_episode_idxs = defaultdict(set) + module_to_sampled_episode_idxs = defaultdict(set) + # Record all n-steps that have been used. + sampled_n_steps = [] + agent_to_sampled_n_steps = defaultdict(list) + module_to_sampled_n_steps = defaultdict(list) + # Record the number of times a sample needs to be resampled. + num_resamples = 0 + agent_to_num_resamples = defaultdict(int) + module_to_num_resamples = defaultdict(int) + + # TODO (simon): Ensure that the module has data and if not, skip it. + # TODO (sven): Should we then error out or skip? I think the Learner + # should handle this case when a module has no train data. + modules_to_sample = modules_to_sample or set(self._module_to_indices.keys()) + for module_id in modules_to_sample: + module_indices = self._module_to_indices[module_id] + B = 0 + while B < batch_size_B: + # Now sample from the single-agent timesteps. + index_tuple = module_indices[self.rng.integers(len(module_indices))] + + # This will be an agent timestep (not env timestep). + # TODO (simon, sven): Maybe deprecate sa_episode_idx (_) in the index + # quads. Is there any need for it? + ma_episode_idx, agent_id, sa_episode_ts = ( + index_tuple[0] - self._num_episodes_evicted, + index_tuple[1], + index_tuple[2], + ) + + # Get the multi-agent episode. + ma_episode = self.episodes[ma_episode_idx] + # Retrieve the single-agent episode for filtering. + sa_episode = ma_episode.agent_episodes[agent_id] + + # If we use random n-step sampling, draw the n-step for this item. + if random_n_step: + actual_n_step = int(self.rng.integers(n_step[0], n_step[1])) + # If we cannnot make the n-step, we resample. + if sa_episode_ts + actual_n_step > len(sa_episode): + num_resamples += 1 + agent_to_num_resamples[agent_id] += 1 + module_to_num_resamples[module_id] += 1 + continue + # Note, this will be the reward after executing action + # `a_(episode_ts)`. For `n_step>1` this will be the discounted sum + # of all rewards that were collected over the last n steps. + sa_raw_rewards = sa_episode.get_rewards( + slice(sa_episode_ts, sa_episode_ts + actual_n_step) + ) + sa_rewards = scipy.signal.lfilter( + [1], [1, -gamma], sa_raw_rewards[::-1], axis=0 + )[-1] + + sampled_sa_episode = SingleAgentEpisode( + id_=sa_episode.id_, + # Provide the IDs for the learner connector. + agent_id=sa_episode.agent_id, + module_id=sa_episode.module_id, + multi_agent_episode_id=ma_episode.id_, + # Ensure that each episode contains a tuple of the form: + # (o_t, a_t, sum(r_(t:t+n_step)), o_(t+n_step)) + # Two observations (t and t+n). + observations=[ + sa_episode.get_observations(sa_episode_ts), + sa_episode.get_observations(sa_episode_ts + actual_n_step), + ], + observation_space=sa_episode.observation_space, + infos=( + [ + sa_episode.get_infos(sa_episode_ts), + sa_episode.get_infos(sa_episode_ts + actual_n_step), + ] + if include_infos + else None + ), + actions=[sa_episode.get_actions(sa_episode_ts)], + action_space=sa_episode.action_space, + rewards=[sa_rewards], + # If the sampled single-agent episode is the single-agent episode's + # last time step, check, if the single-agent episode is terminated + # or truncated. + terminated=( + sa_episode_ts + actual_n_step >= len(sa_episode) + and sa_episode.is_terminated + ), + truncated=( + sa_episode_ts + actual_n_step >= len(sa_episode) + and sa_episode.is_truncated + ), + extra_model_outputs={ + "weights": [1.0], + "n_step": [actual_n_step], + **( + { + k: [ + sa_episode.get_extra_model_outputs(k, sa_episode_ts) + ] + for k in sa_episode.extra_model_outputs.keys() + } + if include_extra_model_outputs + else {} + ), + }, + # TODO (sven): Support lookback buffers. + len_lookback_buffer=0, + t_started=sa_episode_ts, + ) + # Append single-agent episode to the list of sampled episodes. + sampled_episodes.append(sampled_sa_episode) + # Add the episode indices. + sampled_episode_idxs.add(ma_episode_idx) + agent_to_sampled_episode_idxs[sa_episode.agent_id].add(sa_episode.id_) + module_to_sampled_episode_idxs[module_id].add(sa_episode.id_) + # Add the unique step hashes. + # Get the corresponding index in the `env_to_agent_t` mapping. + # TODO (simon, sven): This has complexity O(n) and could become + # expensive when the episode is large. Note, however, that conversion + # from list to `numpy.ndarray` is also complexity O(n) and we do this + # at many places - also in the `MultiAgentEpisode`s. + ma_episode_ts = ma_episode.env_t_to_agent_t[agent_id].data.index( + sa_episode_ts + ) + sampled_env_step_idxs.add( + hashlib.sha256( + f"{ma_episode.id_}-{ma_episode_ts}".encode() + ).hexdigest() + ) + hashed_agent_step = hashlib.sha256( + f"{sa_episode.id_}-{sa_episode_ts}".encode() + ).hexdigest() + agent_to_sampled_env_step_idxs[agent_id].add(hashed_agent_step) + module_to_sampled_env_step_idxs[module_id].add(hashed_agent_step) + # Add the actual n-step used in generating this sample. + sampled_n_steps.append(actual_n_step) + agent_to_sampled_n_steps[agent_id].append(actual_n_step) + module_to_sampled_n_steps[module_id].append(actual_n_step) + + # Increase counter. + B += 1 + + # Increase the per module timesteps counter. + self.sampled_timesteps_per_module[module_id] += B + # Increase the counter metrics. + num_env_steps_sampled += B + agent_to_num_steps_sampled[agent_id] += B + module_to_num_steps_sampled[module_id] += B + + # Increase the counter for environment timesteps. + self.sampled_timesteps += batch_size_B + + # Update the sample metrics. + num_episodes_per_sample = len(sampled_episode_idxs) + num_env_steps_per_sample = len(sampled_env_step_idxs) + sampled_n_step = sum(sampled_n_steps) / batch_size_B + agent_to_num_episodes_per_sample = { + aid: len(l) for aid, l in agent_to_sampled_episode_idxs.items() + } + module_to_num_episodes_per_sample = { + mid: len(l) for mid, l in module_to_sampled_episode_idxs.items() + } + agent_to_num_steps_per_sample = { + aid: len(l) for aid, l in agent_to_sampled_env_step_idxs.items() + } + module_to_num_steps_per_sample = { + mid: len(l) for mid, l in module_to_sampled_env_step_idxs.items() + } + agent_to_sampled_n_step = { + aid: sum(l) / len(l) for aid, l in agent_to_sampled_n_steps.items() + } + module_to_sampled_n_step = { + mid: sum(l) / len(l) for mid, l in module_to_sampled_n_steps.items() + } + self._update_sample_metrics( + num_env_steps_sampled=num_env_steps_sampled, + num_episodes_per_sample=num_episodes_per_sample, + num_env_steps_per_sample=num_env_steps_per_sample, + sampled_n_step=sampled_n_step, + num_resamples=num_resamples, + agent_to_num_steps_sampled=agent_to_num_steps_sampled, + agent_to_num_episodes_per_sample=agent_to_num_episodes_per_sample, + agent_to_num_steps_per_sample=agent_to_num_steps_per_sample, + agent_to_sampled_n_step=agent_to_sampled_n_step, + agent_to_num_resamples=agent_to_num_resamples, + module_to_num_steps_sampled=module_to_num_steps_sampled, + module_to_num_episodes_per_sample=module_to_num_episodes_per_sample, + module_to_num_steps_per_sample=module_to_num_steps_per_sample, + module_to_sampled_n_step=module_to_sampled_n_step, + module_to_num_resamples=module_to_num_resamples, + ) + + # Return multi-agent dictionary. + return sampled_episodes + + def _sample_synchonized( + self, + batch_size_B: Optional[int], + batch_length_T: Optional[int], + n_step: Optional[Union[int, Tuple]], + gamma: float, + include_infos: bool, + include_extra_model_outputs: bool, + modules_to_sample: Optional[List[ModuleID]], + ) -> SampleBatchType: + """Samples a batch of synchronized multi-agent transitions.""" + # Sample the n-step if necessary. + if isinstance(n_step, tuple): + # Use random n-step sampling. + random_n_step = True + else: + actual_n_step = n_step or 1 + random_n_step = False + + # Containers for the sampled data. + observations: Dict[ModuleID, List[ObsType]] = defaultdict(list) + next_observations: Dict[ModuleID, List[ObsType]] = defaultdict(list) + actions: Dict[ModuleID, List[ActType]] = defaultdict(list) + rewards: Dict[ModuleID, List[float]] = defaultdict(list) + is_terminated: Dict[ModuleID, List[bool]] = defaultdict(list) + is_truncated: Dict[ModuleID, List[bool]] = defaultdict(list) + weights: Dict[ModuleID, List[float]] = defaultdict(list) + n_steps: Dict[ModuleID, List[int]] = defaultdict(list) + # If `info` should be included, construct also a container for them. + if include_infos: + infos: Dict[ModuleID, List[Dict[str, Any]]] = defaultdict(list) + # If `extra_model_outputs` should be included, construct a container for them. + if include_extra_model_outputs: + extra_model_outputs: Dict[ModuleID, List[Dict[str, Any]]] = defaultdict( + list + ) + + B = 0 + while B < batch_size_B: + index_tuple = self._indices[self.rng.integers(len(self._indices))] + + # This will be an env timestep (not agent timestep) + ma_episode_idx, ma_episode_ts = ( + index_tuple[0] - self._num_episodes_evicted, + index_tuple[1], + ) + # If we use random n-step sampling, draw the n-step for this item. + if random_n_step: + actual_n_step = int(self.rng.integers(n_step[0], n_step[1])) + # If we are at the end of an episode, continue. + # Note, priority sampling got us `o_(t+n)` and we need for the loss + # calculation in addition `o_t`. + # TODO (simon): Maybe introduce a variable `num_retries` until the + # while loop should break when not enough samples have been collected + # to make n-step possible. + if ma_episode_ts - actual_n_step < 0: + continue + + # Retrieve the multi-agent episode. + ma_episode = self.episodes[ma_episode_idx] + + # Ensure that each row contains a tuple of the form: + # (o_t, a_t, sum(r_(t:t+n_step)), o_(t+n_step)) + # TODO (simon): Implement version for sequence sampling when using RNNs. + eps_observation = ma_episode.get_observations( + slice(ma_episode_ts - actual_n_step, ma_episode_ts + 1), + return_list=True, + ) + # Note, `MultiAgentEpisode` stores the action that followed + # `o_t` with `o_(t+1)`, therefore, we need the next one. + # TODO (simon): This gets the wrong action as long as the getters are not + # fixed. + eps_actions = ma_episode.get_actions(ma_episode_ts - actual_n_step) + # Make sure that at least a single agent should have full transition. + # TODO (simon): Filter for the `modules_to_sample`. + agents_to_sample = self._agents_with_full_transitions( + eps_observation, + eps_actions, + ) + # If not, we resample. + if not agents_to_sample: + continue + # TODO (simon, sven): Do we need to include the common agent rewards? + # Note, the reward that is collected by transitioning from `o_t` to + # `o_(t+1)` is stored in the next transition in `MultiAgentEpisode`. + eps_rewards = ma_episode.get_rewards( + slice(ma_episode_ts - actual_n_step, ma_episode_ts), + return_list=True, + ) + # TODO (simon, sven): Do we need to include the common infos? And are + # there common extra model outputs? + if include_infos: + # If infos are included we include the ones from the last timestep + # as usually the info contains additional values about the last state. + eps_infos = ma_episode.get_infos(ma_episode_ts) + if include_extra_model_outputs: + # If `extra_model_outputs` are included we include the ones from the + # first timestep as usually the `extra_model_outputs` contain additional + # values from the forward pass that produced the action at the first + # timestep. + # Note, we extract them into single row dictionaries similar to the + # infos, in a connector we can then extract these into single batch + # rows. + eps_extra_model_outputs = { + k: ma_episode.get_extra_model_outputs( + k, ma_episode_ts - actual_n_step + ) + for k in ma_episode.extra_model_outputs.keys() + } + # If the sampled time step is the episode's last time step check, if + # the episode is terminated or truncated. + episode_terminated = False + episode_truncated = False + if ma_episode_ts == ma_episode.env_t: + episode_terminated = ma_episode.is_terminated + episode_truncated = ma_episode.is_truncated + # TODO (simon): Filter for the `modules_to_sample`. + # TODO (sven, simon): We could here also sample for all agents in the + # `modules_to_sample` and then adapt the `n_step` for agents that + # have not a full transition. + for agent_id in agents_to_sample: + # Map our agent to the corresponding module we want to + # train. + module_id = ma_episode._agent_to_module_mapping[agent_id] + # Sample only for the modules in `modules_to_sample`. + if module_id not in ( + modules_to_sample or self._module_to_indices.keys() + ): + continue + # TODO (simon, sven): Here we could skip for modules not + # to be sampled in `modules_to_sample`. + observations[module_id].append(eps_observation[0][agent_id]) + next_observations[module_id].append(eps_observation[-1][agent_id]) + # Fill missing rewards with zeros. + agent_rewards = [r[agent_id] or 0.0 for r in eps_rewards] + rewards[module_id].append( + scipy.signal.lfilter([1], [1, -gamma], agent_rewards[::-1], axis=0)[ + -1 + ] + ) + # Note, this should exist, as we filtered for agents with full + # transitions. + actions[module_id].append(eps_actions[agent_id]) + if include_infos: + infos[module_id].append(eps_infos[agent_id]) + if include_extra_model_outputs: + extra_model_outputs[module_id].append( + { + k: eps_extra_model_outputs[agent_id][k] + for k in eps_extra_model_outputs[agent_id].keys() + } + ) + # If sampled observation is terminal for the agent. Either MAE + # episode is truncated/terminated or SAE episode is truncated/ + # terminated at this ts. + # TODO (simon, sven): Add method agent_alive(ts) to MAE. + # or add slicing to get_terminateds(). + agent_ts = ma_episode.env_t_to_agent_t[agent_id][ma_episode_ts] + agent_eps = ma_episode.agent_episodes[agent_id] + agent_terminated = agent_ts == agent_eps.t and agent_eps.is_terminated + agent_truncated = ( + agent_ts == agent_eps.t + and agent_eps.is_truncated + and not agent_eps.is_terminated + ) + if episode_terminated or agent_terminated: + is_terminated[module_id].append(True) + is_truncated[module_id].append(False) + elif episode_truncated or agent_truncated: + is_truncated[module_id].append(True) + is_terminated[module_id].append(False) + else: + is_terminated[module_id].append(False) + is_truncated[module_id].append(False) + # Increase the per module counter. + self.sampled_timesteps_per_module[module_id] += 1 + + # Increase counter. + B += 1 + # Increase the counter for environment timesteps. + self.sampled_timesteps += batch_size_B + + # Should be convertible to MultiAgentBatch. + ret = { + **{ + module_id: { + Columns.OBS: batch(observations[module_id]), + Columns.ACTIONS: batch(actions[module_id]), + Columns.REWARDS: np.array(rewards[module_id]), + Columns.NEXT_OBS: batch(next_observations[module_id]), + Columns.TERMINATEDS: np.array(is_terminated[module_id]), + Columns.TRUNCATEDS: np.array(is_truncated[module_id]), + "weights": np.array(weights[module_id]), + "n_step": np.array(n_steps[module_id]), + } + for module_id in observations.keys() + } + } + + # Return multi-agent dictionary. + return ret + + def _num_remaining_episodes(self, new_eps, evicted_eps): + """Calculates the number of remaining episodes. + + When adding episodes and evicting them in the `add()` method + this function calculates iteratively the number of remaining + episodes. + + Args: + new_eps: List of new episode IDs. + evicted_eps: List of evicted episode IDs. + + Returns: + Number of episodes remaining after evicting the episodes in + `evicted_eps` and adding the episode in `new_eps`. + """ + return len( + set(self.episode_id_to_index.keys()).union(set(new_eps)) - set(evicted_eps) + ) + + def _evict_module_episodes(self, ma_episode: MultiAgentEpisode) -> None: + """Evicts the module episodes from the buffer adn updates all counters. + + Args: + multi_agent_eps: The multi-agent episode to evict from the buffer. + """ + + # Note we need to take the agent ids from the evicted episode because + # different episodes can have different agents and module mappings. + for agent_id in ma_episode.agent_episodes: + # Retrieve the corresponding module ID and module episode. + module_id = ma_episode._agent_to_module_mapping[agent_id] + module_eps = ma_episode.agent_episodes[agent_id] + # Update all counters. + self._num_module_timesteps[module_id] -= module_eps.env_steps() + self._num_module_episodes[module_id] -= 1 + self._num_module_episodes_evicted[module_id] += 1 + + def _update_module_counters(self, ma_episode: MultiAgentEpisode) -> None: + """Updates the module counters after adding an episode. + + Args: + multi_agent_episode: The multi-agent episode to update the module counters + for. + """ + for agent_id in ma_episode.agent_ids: + agent_steps = ma_episode.agent_episodes[agent_id].env_steps() + # Only add if the agent has stepped in the episode (chunk). + if agent_steps > 0: + # Receive the corresponding module ID. + module_id = ma_episode.module_for(agent_id) + self._num_module_timesteps[module_id] += agent_steps + self._num_module_timesteps_added[module_id] += agent_steps + # if ma_episode.agent_episodes[agent_id].is_done: + # # TODO (simon): Check, if we do not count the same episode + # # multiple times. + # # Also add to the module episode counter. + # self._num_module_episodes[module_id] += 1 + + def _add_new_module_indices( + self, + ma_episode: MultiAgentEpisode, + episode_idx: int, + ma_episode_exists: bool = True, + ) -> None: + """Adds the module indices for new episode chunks. + + Args: + ma_episode: The multi-agent episode to add the module indices for. + episode_idx: The index of the episode in the `self.episodes`. + ma_episode_exists: Whether `ma_episode` is already in this buffer (with a + predecessor chunk to which we'll concatenate `ma_episode` later). + """ + existing_ma_episode = None + if ma_episode_exists: + existing_ma_episode = self.episodes[ + self.episode_id_to_index[ma_episode.id_] - self._num_episodes_evicted + ] + + # Note, we iterate through the agent episodes b/c we want to store records + # and some agents could not have entered the environment. + for agent_id in ma_episode.agent_episodes: + # Get the corresponding module id. + module_id = ma_episode.module_for(agent_id) + # Get the module episode. + module_eps = ma_episode.agent_episodes[agent_id] + + # Is the agent episode already in the buffer's existing `ma_episode`? + if ma_episode_exists and agent_id in existing_ma_episode.agent_episodes: + existing_sa_eps_len = len(existing_ma_episode.agent_episodes[agent_id]) + # Otherwise, it is a new single-agent episode and we increase the counter. + else: + existing_sa_eps_len = 0 + self._num_module_episodes[module_id] += 1 + + # Add new module indices. + self._module_to_indices[module_id].extend( + [ + ( + # Keep the MAE index for sampling + episode_idx, + agent_id, + existing_sa_eps_len + i, + ) + for i in range(len(module_eps)) + ] + ) + + def _agents_with_full_transitions( + self, observations: Dict[AgentID, ObsType], actions: Dict[AgentID, ActType] + ): + """Filters for agents that have full transitions. + + Args: + observations: The observations of the episode. + actions: The actions of the episode. + + Returns: + List of agent IDs that have full transitions. + """ + agents_to_sample = [] + for agent_id in observations[0].keys(): + # Only if the agent has an action at the first and an observation + # at the first and last timestep of the n-step transition, we can sample it. + if agent_id in actions and agent_id in observations[-1]: + agents_to_sample.append(agent_id) + return agents_to_sample diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_mixin_replay_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_mixin_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..4c406f36ed081a03b4df01db8edb48c114adb55f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_mixin_replay_buffer.py @@ -0,0 +1,404 @@ +import collections +import logging +import random +from typing import Any, Dict, Optional + +import numpy as np + +from ray.rllib.policy.rnn_sequencing import timeslice_along_seq_lens_with_overlap +from ray.rllib.policy.sample_batch import ( + DEFAULT_POLICY_ID, + SampleBatch, + concat_samples_into_ma_batch, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.replay_buffers.multi_agent_prioritized_replay_buffer import ( + MultiAgentPrioritizedReplayBuffer, +) +from ray.rllib.utils.replay_buffers.multi_agent_replay_buffer import ( + MultiAgentReplayBuffer, + ReplayMode, + merge_dicts_with_warning, +) +from ray.rllib.utils.replay_buffers.replay_buffer import _ALL_POLICIES, StorageUnit +from ray.rllib.utils.typing import PolicyID, SampleBatchType +from ray.util.annotations import DeveloperAPI +from ray.util.debug import log_once + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class MultiAgentMixInReplayBuffer(MultiAgentPrioritizedReplayBuffer): + """This buffer adds replayed samples to a stream of new experiences. + + - Any newly added batch (`add()`) is immediately returned upon + the next `sample` call (close to on-policy) as well as being moved + into the buffer. + - Additionally, a certain number of old samples is mixed into the + returned sample according to a given "replay ratio". + - If >1 calls to `add()` are made without any `sample()` calls + in between, all newly added batches are returned (plus some older samples + according to the "replay ratio"). + + .. testcode:: + :skipif: True + + # replay ratio 0.66 (2/3 replayed, 1/3 new samples): + buffer = MultiAgentMixInReplayBuffer(capacity=100, + replay_ratio=0.66) + buffer.add() + buffer.add() + buffer.sample(1) + + .. testoutput:: + + ..[, , ] + + .. testcode:: + :skipif: True + + buffer.add() + buffer.sample(1) + + .. testoutput:: + + [, , ] + or: [, , ], [, , ] or [, , ], + but always as it is the newest sample + + .. testcode:: + :skipif: True + + buffer.add() + buffer.sample(1) + + .. testoutput:: + + [, , ] + or [, , ], [, , ] or [, , ], etc.. + but always as it is the newest sample + + .. testcode:: + :skipif: True + + # replay proportion 0.0 -> replay disabled: + buffer = MixInReplay(capacity=100, replay_ratio=0.0) + buffer.add() + buffer.sample() + + .. testoutput:: + + [] + + .. testcode:: + :skipif: True + + buffer.add() + buffer.sample() + + .. testoutput:: + + [] + """ + + def __init__( + self, + capacity: int = 10000, + storage_unit: str = "timesteps", + num_shards: int = 1, + replay_mode: str = "independent", + replay_sequence_override: bool = True, + replay_sequence_length: int = 1, + replay_burn_in: int = 0, + replay_zero_init_states: bool = True, + replay_ratio: float = 0.66, + underlying_buffer_config: dict = None, + prioritized_replay_alpha: float = 0.6, + prioritized_replay_beta: float = 0.4, + prioritized_replay_eps: float = 1e-6, + **kwargs, + ): + """Initializes MultiAgentMixInReplayBuffer instance. + + Args: + capacity: The capacity of the buffer, measured in `storage_unit`. + storage_unit: Either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. If they + are stored in episodes, replay_sequence_length is ignored. + num_shards: The number of buffer shards that exist in total + (including this one). + replay_mode: One of "independent" or "lockstep". Determines, + whether batches are sampled independently or to an equal + amount. + replay_sequence_override: If True, ignore sequences found in incoming + batches, slicing them into sequences as specified by + `replay_sequence_length` and `replay_sequence_burn_in`. This only has + an effect if storage_unit is `sequences`. + replay_sequence_length: The sequence length (T) of a single + sample. If > 1, we will sample B x T from this buffer. This + only has an effect if storage_unit is 'timesteps'. + replay_burn_in: The burn-in length in case + `replay_sequence_length` > 0. This is the number of timesteps + each sequence overlaps with the previous one to generate a + better internal state (=state after the burn-in), instead of + starting from 0.0 each RNN rollout. + replay_zero_init_states: Whether the initial states in the + buffer (if replay_sequence_length > 0) are alwayas 0.0 or + should be updated with the previous train_batch state outputs. + replay_ratio: Ratio of replayed samples in the returned + batches. E.g. a ratio of 0.0 means only return new samples + (no replay), a ratio of 0.5 means always return newest sample + plus one old one (1:1), a ratio of 0.66 means always return + the newest sample plus 2 old (replayed) ones (1:2), etc... + underlying_buffer_config: A config that contains all necessary + constructor arguments and arguments for methods to call on + the underlying buffers. This replaces the standard behaviour + of the underlying PrioritizedReplayBuffer. The config + follows the conventions of the general + replay_buffer_config. kwargs for subsequent calls of methods + may also be included. Example: + "replay_buffer_config": {"type": PrioritizedReplayBuffer, + "capacity": 10, "storage_unit": "timesteps", + prioritized_replay_alpha: 0.5, prioritized_replay_beta: 0.5, + prioritized_replay_eps: 0.5} + prioritized_replay_alpha: Alpha parameter for a prioritized + replay buffer. Use 0.0 for no prioritization. + prioritized_replay_beta: Beta parameter for a prioritized + replay buffer. + prioritized_replay_eps: Epsilon parameter for a prioritized + replay buffer. + **kwargs: Forward compatibility kwargs. + """ + if not 0 <= replay_ratio <= 1: + raise ValueError("Replay ratio must be within [0, 1]") + + MultiAgentPrioritizedReplayBuffer.__init__( + self, + capacity=capacity, + storage_unit=storage_unit, + num_shards=num_shards, + replay_mode=replay_mode, + replay_sequence_override=replay_sequence_override, + replay_sequence_length=replay_sequence_length, + replay_burn_in=replay_burn_in, + replay_zero_init_states=replay_zero_init_states, + underlying_buffer_config=underlying_buffer_config, + prioritized_replay_alpha=prioritized_replay_alpha, + prioritized_replay_beta=prioritized_replay_beta, + prioritized_replay_eps=prioritized_replay_eps, + **kwargs, + ) + + self.replay_ratio = replay_ratio + + self.last_added_batches = collections.defaultdict(list) + + @DeveloperAPI + @override(MultiAgentPrioritizedReplayBuffer) + def add(self, batch: SampleBatchType, **kwargs) -> None: + """Adds a batch to the appropriate policy's replay buffer. + + Turns the batch into a MultiAgentBatch of the DEFAULT_POLICY_ID if + it is not a MultiAgentBatch. Subsequently, adds the individual policy + batches to the storage. + + Args: + batch: The batch to be added. + **kwargs: Forward compatibility kwargs. + """ + # Make a copy so the replay buffer doesn't pin plasma memory. + batch = batch.copy() + # Handle everything as if multi-agent. + batch = batch.as_multi_agent() + + kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs) + + pids_and_batches = self._maybe_split_into_policy_batches(batch) + + # We need to split batches into timesteps, sequences or episodes + # here already to properly keep track of self.last_added_batches + # underlying buffers should not split up the batch any further + with self.add_batch_timer: + if self.storage_unit == StorageUnit.TIMESTEPS: + for policy_id, sample_batch in pids_and_batches.items(): + timeslices = sample_batch.timeslices(1) + for time_slice in timeslices: + self.replay_buffers[policy_id].add(time_slice, **kwargs) + self.last_added_batches[policy_id].append(time_slice) + + elif self.storage_unit == StorageUnit.SEQUENCES: + for policy_id, sample_batch in pids_and_batches.items(): + timeslices = timeslice_along_seq_lens_with_overlap( + sample_batch=sample_batch, + seq_lens=sample_batch.get(SampleBatch.SEQ_LENS) + if self.replay_sequence_override + else None, + zero_pad_max_seq_len=self.replay_sequence_length, + pre_overlap=self.replay_burn_in, + zero_init_states=self.replay_zero_init_states, + ) + for slice in timeslices: + self.replay_buffers[policy_id].add(slice, **kwargs) + self.last_added_batches[policy_id].append(slice) + + elif self.storage_unit == StorageUnit.EPISODES: + for policy_id, sample_batch in pids_and_batches.items(): + for eps in sample_batch.split_by_episode(): + # Only add full episodes to the buffer + if eps.get(SampleBatch.T)[0] == 0 and ( + eps.get(SampleBatch.TERMINATEDS, [True])[-1] + or eps.get(SampleBatch.TRUNCATEDS, [False])[-1] + ): + self.replay_buffers[policy_id].add(eps, **kwargs) + self.last_added_batches[policy_id].append(eps) + else: + if log_once("only_full_episodes"): + logger.info( + "This buffer uses episodes as a storage " + "unit and thus allows only full episodes " + "to be added to it. Some samples may be " + "dropped." + ) + elif self.storage_unit == StorageUnit.FRAGMENTS: + for policy_id, sample_batch in pids_and_batches.items(): + self.replay_buffers[policy_id].add(sample_batch, **kwargs) + self.last_added_batches[policy_id].append(sample_batch) + + self._num_added += batch.count + + @DeveloperAPI + @override(MultiAgentReplayBuffer) + def sample( + self, num_items: int, policy_id: PolicyID = DEFAULT_POLICY_ID, **kwargs + ) -> Optional[SampleBatchType]: + """Samples a batch of size `num_items` from a specified buffer. + + Concatenates old samples to new ones according to + self.replay_ratio. If not enough new samples are available, mixes in + less old samples to retain self.replay_ratio on average. Returns + an empty batch if there are no items in the buffer. + + Args: + num_items: Number of items to sample from this buffer. + policy_id: ID of the policy that produced the experiences to be + sampled. + **kwargs: Forward compatibility kwargs. + + Returns: + Concatenated MultiAgentBatch of items. + """ + # Merge kwargs, overwriting standard call arguments + kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs) + + def mix_batches(_policy_id): + """Mixes old with new samples. + + Tries to mix according to self.replay_ratio on average. + If not enough new samples are available, mixes in less old samples + to retain self.replay_ratio on average. + """ + + def round_up_or_down(value, ratio): + """Returns an integer averaging to value*ratio.""" + product = value * ratio + ceil_prob = product % 1 + if random.uniform(0, 1) < ceil_prob: + return int(np.ceil(product)) + else: + return int(np.floor(product)) + + max_num_new = round_up_or_down(num_items, 1 - self.replay_ratio) + # if num_samples * self.replay_ratio is not round, + # we need one more sample with a probability of + # (num_items*self.replay_ratio) % 1 + + _buffer = self.replay_buffers[_policy_id] + output_batches = self.last_added_batches[_policy_id][:max_num_new] + self.last_added_batches[_policy_id] = self.last_added_batches[_policy_id][ + max_num_new: + ] + + # No replay desired + if self.replay_ratio == 0.0: + return concat_samples_into_ma_batch(output_batches) + # Only replay desired + elif self.replay_ratio == 1.0: + return _buffer.sample(num_items, **kwargs) + + num_new = len(output_batches) + + if np.isclose(num_new, num_items * (1 - self.replay_ratio)): + # The optimal case, we can mix in a round number of old + # samples on average + num_old = num_items - max_num_new + else: + # We never want to return more elements than num_items + num_old = min( + num_items - max_num_new, + round_up_or_down( + num_new, self.replay_ratio / (1 - self.replay_ratio) + ), + ) + + output_batches.append(_buffer.sample(num_old, **kwargs)) + # Depending on the implementation of underlying buffers, samples + # might be SampleBatches + output_batches = [batch.as_multi_agent() for batch in output_batches] + return concat_samples_into_ma_batch(output_batches) + + def check_buffer_is_ready(_policy_id): + if ( + (len(self.replay_buffers[policy_id]) == 0) and self.replay_ratio > 0.0 + ) or ( + len(self.last_added_batches[_policy_id]) == 0 + and self.replay_ratio < 1.0 + ): + return False + return True + + with self.replay_timer: + samples = [] + + if self.replay_mode == ReplayMode.LOCKSTEP: + assert ( + policy_id is None + ), "`policy_id` specifier not allowed in `lockstep` mode!" + if check_buffer_is_ready(_ALL_POLICIES): + samples.append(mix_batches(_ALL_POLICIES).as_multi_agent()) + elif policy_id is not None: + if check_buffer_is_ready(policy_id): + samples.append(mix_batches(policy_id).as_multi_agent()) + else: + for policy_id, replay_buffer in self.replay_buffers.items(): + if check_buffer_is_ready(policy_id): + samples.append(mix_batches(policy_id).as_multi_agent()) + + return concat_samples_into_ma_batch(samples) + + @DeveloperAPI + @override(MultiAgentPrioritizedReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Returns all local state. + + Returns: + The serializable local state. + """ + data = { + "last_added_batches": self.last_added_batches, + } + parent = MultiAgentPrioritizedReplayBuffer.get_state(self) + parent.update(data) + return parent + + @DeveloperAPI + @override(MultiAgentPrioritizedReplayBuffer) + def set_state(self, state: Dict[str, Any]) -> None: + """Restores all local state to the provided `state`. + + Args: + state: The new state to set this buffer. Can be obtained by + calling `self.get_state()`. + """ + self.last_added_batches = state["last_added_batches"] + MultiAgentPrioritizedReplayBuffer.set_state(state) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_episode_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_episode_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..6b0d9247bbe5440077f081d499f2fee3a67267d8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_episode_buffer.py @@ -0,0 +1,1078 @@ +import copy +import hashlib +import numpy as np +import scipy + +from collections import defaultdict, deque +from numpy.typing import NDArray +from typing import Dict, List, Optional, Set, Tuple, Union +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import override +from ray.rllib.utils.replay_buffers.multi_agent_episode_buffer import ( + MultiAgentEpisodeReplayBuffer, +) +from ray.rllib.utils.replay_buffers.prioritized_episode_buffer import ( + PrioritizedEpisodeReplayBuffer, +) +from ray.rllib.utils.typing import ModuleID +from ray.rllib.execution.segment_tree import MinSegmentTree, SumSegmentTree + + +class MultiAgentPrioritizedEpisodeReplayBuffer( + MultiAgentEpisodeReplayBuffer, PrioritizedEpisodeReplayBuffer +): + """Multi-agent episode replay buffer that stores episodes by their IDs. + + This class implements a replay buffer as used in "Prioritized Experience + Replay" (Schaul et al., 2016) for multi-agent reinforcement learning, + + Each "row" (a slot in a deque) in the buffer is occupied by one episode. If an + incomplete episode is added to the buffer and then another chunk of that episode is + added at a later time, the buffer will automatically concatenate the new fragment to + the original episode. This way, episodes can be completed via subsequent `add` + calls. + + Sampling returns a size `B` episode list (number of 'rows'), where each episode + holds a tuple tuple of the form + + `(o_t, a_t, sum(r_t+1:t+n), o_t+n)` + + where `o_t` is the observation in `t`, `a_t` the action chosen at observation `o_t`, + `o_t+n` is the observation `n` timesteps later and `sum(r_t+1:t+n)` is the sum of + all rewards collected over the time steps between `t+1` and `t+n`. The `n`-step can + be chosen freely when sampling and defaults to `1`. If `n_step` is a tuple it is + sampled uniformly across the interval defined by the tuple (for each row in the + batch). + + Each episode contains - in addition to the data tuples presented above - two further + elements in its `extra_model_outputs`, namely `n_steps` and `weights`. The former + holds the `n_step` used for the sampled timesteps in the episode and the latter the + corresponding (importance sampling) weight for the transition. + + After sampling priorities can be updated (for the last sampled episode list) with + `self.update_priorities`. This method assigns the new priorities automatically to + the last sampled timesteps. Note, this implies that sampling timesteps and updating + their corresponding priorities needs to alternate (e.g. sampling several times and + then updating the priorities would not work because the buffer caches the last + sampled timestep indices). + + .. testcode:: + + import gymnasium as gym + + from ray.rllib.env.multi_agent_episode import MultiAgentEpisode + from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole + from ray.rllib.utils.replay_buffers import ( + MultiAgentPrioritizedEpisodeReplayBuffer, + ) + + + # Create the environment. + env = MultiAgentCartPole({"num_agents": 2}) + + # Set up the loop variables + agent_ids = env.agents + agent_ids.append("__all__") + terminateds = {aid: False for aid in agent_ids} + truncateds = {aid: False for aid in agent_ids} + num_timesteps = 10000 + episodes = [] + + # Initialize the first episode entries. + eps = MultiAgentEpisode() + obs, infos = env.reset() + eps.add_env_reset(observations=obs, infos=infos) + + # Sample 10,000 env timesteps. + for i in range(num_timesteps): + # If terminated we create a new episode. + if eps.is_done: + episodes.append(eps.to_numpy()) + eps = MultiAgentEpisode() + terminateds = {aid: False for aid in agent_ids} + truncateds = {aid: False for aid in agent_ids} + obs, infos = env.reset() + eps.add_env_reset(observations=obs, infos=infos) + + # Sample a random action for all agents that should step in the episode + # next. + actions = { + aid: env.get_action_space(aid).sample() + for aid in eps.get_agents_to_act() + } + obs, rewards, terminateds, truncateds, infos = env.step(actions) + eps.add_env_step( + obs, + actions, + rewards, + infos, + terminateds=terminateds, + truncateds=truncateds + ) + + # Add the last (truncated) episode to the list of episodes. + if not eps.is_done: + episodes.append(eps) + + # Create the buffer. + buffer = MultiAgentPrioritizedEpisodeReplayBuffer() + # Add the list of episodes sampled. + buffer.add(episodes) + + # Pull a sample from the buffer using an `n-step` of 3. + sample = buffer.sample(num_items=256, gamma=0.95, n_step=3, beta=0.5) + """ + + def __init__( + self, + capacity: int = 10000, + *, + batch_size_B: int = 16, + batch_length_T: int = 1, + alpha: float = 1.0, + metrics_num_episodes_for_smoothing: int = 100, + **kwargs, + ): + """Initializes a `MultiAgentPrioritizedEpisodeReplayBuffer` object + + Args: + capacity: The total number of timesteps to be storable in this buffer. + Will start ejecting old episodes once this limit is reached. + batch_size_B: The number of episodes returned from `sample()`. + batch_length_T: The length of each episode in the episode list returned from + `sample()`. + alpha: The amount of prioritization to be used: `alpha=1.0` means full + prioritization, `alpha=0.0` means no prioritization. + """ + # Initialize the parents. + MultiAgentEpisodeReplayBuffer.__init__( + self, + capacity=capacity, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + metrics_num_episodes_for_smoothing=metrics_num_episodes_for_smoothing, + **kwargs, + ) + PrioritizedEpisodeReplayBuffer.__init__( + self, + capacity=capacity, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + alpha=alpha, + metrics_num_episodes_for_smoothing=metrics_num_episodes_for_smoothing, + **kwargs, + ) + + # TODO (simon): If not needed in synchronized sampling, remove. + # Maps indices from samples to their corresponding tree index. + self._sample_idx_to_tree_idx = {} + # Initialize segment trees for the priority weights per module. Note, b/c + # the trees are binary we need for them a capacity that is an exponential + # of 2. Double it to enable temporary buffer overflow (we need then free + # nodes in the trees). + tree_capacity = int(2 ** np.ceil(np.log2(self.capacity))) + + # Each module receives its own segment trees for independent sampling. + self._module_to_max_priority: Dict[ModuleID, float] = defaultdict(lambda: 1.0) + self._module_to_sum_segment: Dict[ModuleID, "SumSegmentTree"] = defaultdict( + lambda: SumSegmentTree(2 * tree_capacity) + ) + self._module_to_min_segment: Dict[ModuleID, "MinSegmentTree"] = defaultdict( + lambda: MinSegmentTree(2 * tree_capacity) + ) + # At initialization all nodes are free. + self._module_to_free_nodes: Dict[ModuleID, "deque"] = defaultdict( + lambda: deque(list(range(2 * tree_capacity)), maxlen=2 * tree_capacity) + ) + # Keep track of the maximum index used from the trees. This helps + # to not traverse the complete trees. + self._module_to_max_idx: Dict[ModuleID, int] = defaultdict(lambda: 0) + # Map from tree indices to sample indices (i.e. `self._indices`). + self._module_to_tree_idx_to_sample_idx: Dict[ModuleID, dict] = defaultdict( + lambda: {} + ) + # Map from module ID to the last sampled indices to update priorities. + self._module_to_last_sampled_indices: Dict[ModuleID, list] = defaultdict( + lambda: [] + ) + + @override(MultiAgentEpisodeReplayBuffer) + def add( + self, + episodes: Union[List["MultiAgentEpisode"], "MultiAgentEpisode"], + weight: Optional[Union[float, Dict[ModuleID, float]]] = None, + ) -> None: + """Adds incoming episodes to the replay buffer. + + Note, if the incoming episodes' time steps cause the buffer to overflow, + older episodes are evicted. Because episodes usually come in chunks and + not complete, this could lead to edge cases (e.g. with very small capacity + or very long episode length) where the first part of an episode is evicted + while the next part just comes in. + To defend against such case, the complete episode is evicted, including + the new chunk, unless the episode is the only one in the buffer. In the + latter case the buffer will be allowed to overflow in a temporary fashion, + i.e. during the next addition of samples to the buffer an attempt is made + to fall below capacity again. + + The user is advised to select a large enough buffer with regard to the maximum + expected episode length. + + Args: + episodes: A list of `SingleAgentEpisode`s that contain the episode data. + weight: A starting priority for the time steps in `episodes`. If `None` + the maximum priority is used, i.e. 1.0 (as suggested in the original + paper we scale weights to the interval [0.0, 1.0]). If a dictionary + is provided, it must contain the weights for each module. + + """ + # Define the weights. + weight_per_module = {} + # If no weight is provided, use the maximum priority. + if weight is None: + weight = self._max_priority + # If `weight` is a dictionary, use the module weights. + elif isinstance(dict, weight): + weight_per_module = weight + # Define the weight as the mean of the module weights. + weight = np.mean(list(weight.values())) + + episodes: List["MultiAgentEpisode"] = force_list(episodes) + + new_episode_ids: List[str] = [eps.id_ for eps in episodes] + # Calculate the total number of environment timesteps in the new episodes. + # Note, we need the potential new sum of timesteps to decide whether to + # evict episodes. + total_env_timesteps = sum([eps.env_steps() for eps in episodes]) + self._num_timesteps += total_env_timesteps + self._num_timesteps_added += total_env_timesteps + + # Set up some counters for metrics. + num_env_steps_added = 0 + agent_to_num_steps_added = defaultdict(int) + module_to_num_steps_added = defaultdict(int) + num_episodes_added = 0 + agent_to_num_episodes_added = defaultdict(int) + module_to_num_episodes_added = defaultdict(int) + num_episodes_evicted = 0 + agent_to_num_episodes_evicted = defaultdict(int) + module_to_num_episodes_evicted = defaultdict(int) + num_env_steps_evicted = 0 + agent_to_num_steps_evicted = defaultdict(int) + module_to_num_steps_evicted = defaultdict(int) + + # Evict old episodes. + eps_evicted_ids: Set[Union[str, int]] = set() + eps_evicted_idxs: Set[int] = set() + # Only evict episodes if the buffer is full and there is more than one + + while ( + self._num_timesteps > self.capacity + and self._num_remaining_episodes(new_episode_ids, eps_evicted_ids) != 1 + ): + # Evict episode. + evicted_episode = self.episodes.popleft() + eps_evicted_ids.add(evicted_episode.id_) + eps_evicted_idxs.add(self.episode_id_to_index.pop(evicted_episode.id_)) + # If this episode has a new chunk in the new episodes added, + # we subtract it again. + # TODO (sven, simon): Should we just treat such an episode chunk + # as a new episode? + if evicted_episode.id_ in new_episode_ids: + idx = next( + i + for i, eps in enumerate(episodes) + if eps.id_ == evicted_episode.id_ + ) + new_eps_to_evict = episodes.pop(idx) + # Remove the timesteps of the evicted new episode from the counter. + self._num_timesteps -= new_eps_to_evict.env_steps() + self._num_timesteps_added -= new_eps_to_evict.env_steps() + # Remove the timesteps of the evicted old episode from the counter. + self._num_timesteps -= evicted_episode.env_steps() + self._num_agent_timesteps -= evicted_episode.agent_steps() + self._num_episodes_evicted += 1 + # Increase the counters. + num_episodes_evicted += 1 + num_env_steps_evicted += evicted_episode.env_steps() + for aid, a_eps in evicted_episode.agent_episodes.items(): + mid = evicted_episode._agent_to_module_mapping[aid] + agent_to_num_episodes_evicted[aid] += 1 + module_to_num_episodes_evicted[mid] += 1 + agent_to_num_steps_evicted[aid] += a_eps.agent_steps() + module_to_num_steps_evicted[mid] += a_eps.agent_steps() + # Remove the module timesteps of the evicted episode from the counters. + self._evict_module_episodes(evicted_episode) + del evicted_episode + + # Add agent and module steps. + for eps in episodes: + self._num_agent_timesteps += eps.agent_steps() + self._num_agent_timesteps_added += eps.agent_steps() + # Update the module counters by the module timesteps. + self._update_module_counters(eps) + + # Remove corresponding indices, if episodes were evicted. + if eps_evicted_idxs: + new_indices = [] + # Each index 2-tuple is of the form (ma_episode_idx, timestep) and + # refers to a certain environment timestep in a certain multi-agent + # episode. + i = 0 + for idx_tuple in self._indices: + # If episode index is from an evicted episode, remove it from the + # indices and clean up. + if idx_tuple[0] in eps_evicted_idxs: + # Here we need the index of a multi-agent sample in the segment + # tree. + self._free_nodes.appendleft(idx_tuple[2]) + # Remove also the potentially maximum index. + self._max_idx -= 1 if self._max_idx == idx_tuple[2] else 0 + # Reset to defaults. + self._sum_segment[idx_tuple[2]] = 0.0 + self._min_segment[idx_tuple[2]] = float("inf") + sample_idx = self._tree_idx_to_sample_idx[idx_tuple[2]] + self._tree_idx_to_sample_idx.pop(idx_tuple[2]) + self._sample_idx_to_tree_idx.pop(sample_idx) + # Otherwise, keep the index. + else: + new_indices.append(idx_tuple) + self._tree_idx_to_sample_idx[idx_tuple[2]] = i + self._sample_idx_to_tree_idx[i] = idx_tuple[2] + i += 1 + # Assign the new list of indices. + self._indices = new_indices + # Also remove corresponding module indices. + for module_id, module_indices in self._module_to_indices.items(): + new_module_indices = [] + # Each index 4-tuple is of the form + # (ma_episode_idx, agent_id, timestep, segtree_idx) and refers to a + # certain agent timestep in a certain multi-agent episode. + i = 0 + for idx_quadlet in module_indices: + # If episode index is from an evicted episode, remove it from the + # indices and clean up. + if idx_quadlet[0] in eps_evicted_idxs: + # Here we need the index of a multi-agent sample in the segment + # tree. + self._module_to_free_nodes[module_id].appendleft(idx_quadlet[3]) + # Remove also the potentially maximum index per module. + self._module_to_max_idx[module_id] -= ( + 1 + if self._module_to_max_idx[module_id] == idx_quadlet[3] + else 0 + ) + # Set to defaults. + self._module_to_sum_segment[module_id][idx_quadlet[3]] = 0.0 + self._module_to_min_segment[module_id][idx_quadlet[3]] = float( + "inf" + ) + self._module_to_tree_idx_to_sample_idx[module_id].pop( + idx_quadlet[3] + ) + # Otherwise, keep the index. + else: + new_module_indices.append(idx_quadlet) + self._module_to_tree_idx_to_sample_idx[module_id][ + idx_quadlet[3] + ] = i + i += 1 + # Assign the new list of indices for the module. + self._module_to_indices[module_id] = new_module_indices + + j = len(self._indices) + for eps in episodes: + eps = copy.deepcopy(eps) + # If the episode is part of an already existing episode, concatenate. + if eps.id_ in self.episode_id_to_index: + eps_idx = self.episode_id_to_index[eps.id_] + existing_eps = self.episodes[eps_idx - self._num_episodes_evicted] + existing_len = len(existing_eps) + self._indices.extend( + [ + ( + eps_idx, + existing_len + i, + # Get the index in the segment trees. + self._get_free_node_and_assign(j + i, weight), + ) + for i in range(len(eps)) + ] + ) + # Add new module indices. + self._add_new_module_indices(eps, eps_idx, True, weight_per_module) + # Concatenate the episode chunk. + existing_eps.concat_episode(eps) + # Otherwise, create a new entry. + else: + # New episode. + self.episodes.append(eps) + # Update the counters. + num_episodes_added += 1 + for aid, a_eps in eps.agent_episodes.items(): + mid = eps._agent_to_module_mapping[aid] + agent_to_num_episodes_added[aid] += 1 + module_to_num_episodes_added[mid] += 1 + eps_idx = len(self.episodes) - 1 + self._num_episodes_evicted + self.episode_id_to_index[eps.id_] = eps_idx + self._indices.extend( + [ + (eps_idx, i, self._get_free_node_and_assign(j + i, weight)) + for i in range(len(eps)) + ] + ) + # Add new module indices. + self._add_new_module_indices(eps, eps_idx, False, weight_per_module) + + # Update the step counters. + num_env_steps_added += eps.env_steps() + for aid, e_eps in eps.agent_episodes.items(): + mid = eps._agent_to_module_mapping[aid] + agent_to_num_steps_added[aid] += e_eps.agent_steps() + module_to_num_steps_added[mid] += e_eps.agent_steps() + # Increase index to the new length of `self._indices`. + j = len(self._indices) + + # Update the adding metrics. + # Update the adding metrics. + self._update_add_metrics( + num_episodes_added=num_episodes_added, + num_env_steps_added=num_env_steps_added, + num_episodes_evicted=num_episodes_evicted, + num_env_steps_evicted=num_env_steps_evicted, + agent_to_num_episodes_added=agent_to_num_episodes_added, + agent_to_num_steps_added=agent_to_num_steps_added, + agent_to_num_episodes_evicted=agent_to_num_episodes_evicted, + agent_to_num_steps_evicted=agent_to_num_steps_evicted, + module_to_num_episodes_added=module_to_num_steps_added, + module_to_num_steps_added=module_to_num_episodes_added, + module_to_num_episodes_evicted=module_to_num_episodes_evicted, + module_to_num_steps_evicted=module_to_num_steps_evicted, + ) + + @override(MultiAgentEpisodeReplayBuffer) + def sample( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + n_step: Optional[Union[int, Tuple]] = 1, + gamma: float = 0.99, + include_infos: bool = False, + include_extra_model_outputs: bool = False, + replay_mode: str = "independent", + modules_to_sample: Optional[List[ModuleID]] = None, + beta: float = 0.0, + **kwargs, + ) -> Union[List["MultiAgentEpisode"], List["SingleAgentEpisode"]]: + """Samples a list of episodes with multi-agent transitions. + + This sampling method also adds (importance sampling) weights to the returned + batch. See for prioritized sampling Schaul et al. (2016). + + Multi-agent transitions can be sampled either `"independent"` or + `"synchronized"` with the former sampling for each module independent agent + steps and the latter sampling agent transitions from the same environment step. + + The n-step parameter can be either a single integer or a tuple of two integers. + In the former case, the n-step is fixed to the given integer and in the latter + case, the n-step is sampled uniformly from the given range. Large n-steps could + potentially lead to many retries because not all samples might have a full + n-step transition. + + Sampling returns episode lists of size B (number of 'rows'), where each episode + holds a transition of the form + + `(o_t, a_t, sum(r_t+1:t+n), o_t+n, terminated_t+n, truncated_t+n)` + + where `o_t` is the observation in `t`, `a_t` the action chosen at observation + `o_t`, `o_t+n` is the observation `n` timesteps later and `sum(r_t+1:t+n)` is + the sum of all rewards collected over the time steps between `t+1` and `t+n`. + The `n`-step can be chosen freely when sampling and defaults to `1`. If `n_step` + is a tuple it is sampled uniformly across the interval defined by the tuple (for + each row in the batch), i.e. from the interval `[n_step[0], n_step[1]]`. + + If requested, `info`s of a transition's first and last timestep `t+n` and/or + `extra_model_outputs` from the first timestep (e.g. log-probabilities, etc.) are + added to the batch. + + Each episode contains - in addition to the data tuples presented above - two + further entries in its `extra_model_outputs`, namely `n_steps` and `weigths`. + The former holds the `n_step` used for each transition and the latter the + (importance sampling) weight of `1.0` for each row in the batch. This weight + is used for weighted loss calculations in the training process. + + Args: + num_items: The number of items to sample. If provided, `batch_size_B` + should be `None`. + batch_size_B: The batch size to sample. If provided, `num_items` + should be `None`. + batch_length_T: The length of the sampled batch. If not provided, the + default batch length is used. This feature is not yet implemented. + n_step: The n-step to sample. If the n-step is a tuple, the n-step is + sampled uniformly from the given range. If not provided, the default + n-step of `1` is used. + gamma: The discount factor for the n-step reward calculation. + include_infos: Whether to include the infos in the sampled episodes. + include_extra_model_outputs: Whether to include the extra model outputs + in the sampled episodes. + replay_mode: The replay mode to use for sampling. Either `"independent"` + or `"synchronized"`. + modules_to_sample: A list of module IDs to sample from. If not provided, + transitions for aall modules are sampled. + beta: The exponent of the importance sampling weight (see Schaul et + al. (2016)). A `beta=0.0` does not correct for the bias introduced + by prioritized replay and `beta=1.0` fully corrects for it. + + Returns: + A list of 1-step long single-agent episodes containing all basic episode + data and if requested infos and extra model outputs. In addition extra model + outputs hold the (importance sampling) weights and the n-step used for each + transition. + """ + assert beta >= 0.0 + + if num_items is not None: + assert batch_size_B is None, ( + "Cannot call `sample()` with both `num_items` and `batch_size_B` " + "provided! Use either one." + ) + batch_size_B = num_items + + # Use our default values if no sizes/lengths provided. + batch_size_B = batch_size_B or self.batch_size_B + # TODO (simon): Implement trajectory sampling for RNNs. + batch_length_T = batch_length_T or self.batch_length_T + + # Sample for each module independently. + if replay_mode == "independent": + return self._sample_independent( + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + n_step=n_step, + gamma=gamma, + include_infos=include_infos, + include_extra_model_outputs=include_extra_model_outputs, + modules_to_sample=modules_to_sample, + beta=beta, + ) + # Otherwise, sample synchronized. + else: + return self._sample_synchonized( + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + n_step=n_step, + gamma=gamma, + include_infos=include_infos, + include_extra_model_outputs=include_extra_model_outputs, + modules_to_sample=modules_to_sample, + ) + + @override(PrioritizedEpisodeReplayBuffer) + def update_priorities( + self, + priorities: Union[NDArray, Dict[ModuleID, NDArray]], + module_id: ModuleID, + ) -> None: + """Update the priorities of items at corresponding indices. + + Usually, incoming priorities are TD-errors. + + Args: + priorities: Numpy array containing the new priorities to be used + in sampling for the items in the last sampled batch. + """ + + assert len(priorities) == len(self._module_to_last_sampled_indices[module_id]) + + for idx, priority in zip( + self._module_to_last_sampled_indices[module_id], priorities + ): + # sample_idx = self._module_to_tree_idx_to_sample_idx[module_id][idx] + # ma_episode_idx = ( + # self._module_to_indices[module_id][sample_idx][0] + # - self._num_episodes_evicted + # ) + + # ma_episode_indices.append(ma_episode_idx) + # Note, TD-errors come in as absolute values or results from + # cross-entropy loss calculations. + # assert priority > 0, f"priority was {priority}" + priority = max(priority, 1e-12) + assert 0 <= idx < self._module_to_sum_segment[module_id].capacity + # TODO (simon): Create metrics. + # delta = priority**self._alpha - self._sum_segment[idx] + # Update the priorities in the segment trees. + self._module_to_sum_segment[module_id][idx] = priority**self._alpha + self._module_to_min_segment[module_id][idx] = priority**self._alpha + # Update the maximal priority. + self._module_to_max_priority[module_id] = max( + self._module_to_max_priority[module_id], priority + ) + # Clear the corresponding index list for the module. + self._module_to_last_sampled_indices[module_id].clear() + + # TODO (simon): Use this later for synchronized sampling. + # for ma_episode_idx in ma_episode_indices: + # ma_episode_tree_idx = self._sample_idx_to_tree_idx(ma_episode_idx) + # ma_episode_idx = + + # # Update the weights + # self._sum_segment[tree_idx] = sum( + # self._module_to_sum_segment[module_id][idx] + # for module_id, idx in self._tree_idx_to_sample_idx[tree_idx] + # ) + # self._min_segment[tree_idx] = min( + # self._module_to_min_segment[module_id][idx] + # for module_id, idx in self._tree_idx_to_sample_idx[tree_idx] + # ) + + @override(MultiAgentEpisodeReplayBuffer) + def get_state(self): + return ( + MultiAgentEpisodeReplayBuffer.get_state(self) + | PrioritizedEpisodeReplayBuffer.get_state(self) + | { + "_module_to_max_priority": list(self._module_to_max_priority.items()), + "_module_to_sum_segment": list(self._module_to_sum_segment.items()), + "_module_to_min_segment": list(self._module_to_min_segment.items()), + "_module_to_free_nodes": list(self._module_to_free_nodes.items()), + "_module_to_max_idx": list(self._module_to_max_idx.items()), + "_module_to_tree_idx_to_sample_idx": list( + self._module_to_tree_idx_to_sample_idx.items() + ), + "_module_to_last_sampled_indices": list( + self._module_to_last_sampled_indices.items() + ), + } + ) + + @override(MultiAgentEpisodeReplayBuffer) + def set_state(self, state) -> None: + MultiAgentEpisodeReplayBuffer.set_state(self, state) + PrioritizedEpisodeReplayBuffer.set_state(self, state) + self._module_to_max_priority = defaultdict( + lambda: 1.0, dict(state["_module_to_max_priority"]) + ) + tree_capacity = int(2 ** np.ceil(np.log2(self.capacity))) + self._module_to_sum_segment = defaultdict( + lambda: SumSegmentTree(2 * tree_capacity), + dict(state["_module_to_sum_segment"]), + ) + self._module_to_min_segment = defaultdict( + lambda: SumSegmentTree(2 * tree_capacity), + dict(state["_module_to_min_segment"]), + ) + self._module_to_free_nodes = defaultdict( + lambda: deque(list(range(2 * tree_capacity)), maxlen=2 * tree_capacity), + dict(state["_module_to_free_nodes"]), + ) + self._module_to_max_idx = defaultdict( + lambda: 0, dict(state["_module_to_max_idx"]) + ) + self._module_to_tree_idx_to_sample_idx = defaultdict( + lambda: {}, dict(state["_module_to_tree_idx_to_sample_idx"]) + ) + self._module_to_last_sampled_indices = defaultdict( + lambda: [], dict(state["_module_to_last_sampled_indices"]) + ) + + @override(MultiAgentEpisodeReplayBuffer) + def _add_new_module_indices( + self, + ma_episode: MultiAgentEpisode, + ma_episode_idx: int, + ma_episode_exists: bool = True, + weight: Optional[Union[float, Dict[ModuleID, float]]] = None, + ) -> None: + """Adds the module indices for new episode chunks. + + Args: + multi_agent_episode: The multi-agent episode to add the module indices for. + episode_idx: The index of the episode in the `self.episodes`. + """ + existing_ma_episode = None + if ma_episode_exists: + existing_ma_episode = self.episodes[ + self.episode_id_to_index[ma_episode.id_] - self._num_episodes_evicted + ] + + for agent_id in ma_episode.agent_ids: + # Get the corresponding module id. + module_id = ma_episode.module_for(agent_id) + # Get the module episode. + module_eps = ma_episode.agent_episodes[agent_id] + + # Is the agent episode already in the buffer's existing `ma_episode`? + if ma_episode_exists and agent_id in existing_ma_episode.agent_episodes: + existing_sa_eps_len = len(existing_ma_episode.agent_episodes[agent_id]) + # Otherwise, it is a new single-agent episode and we increase the counter. + else: + existing_sa_eps_len = 0 + self._num_module_episodes[module_id] += 1 + + # Add new module indices. + module_weight = weight.get( + module_id, self._module_to_max_priority[module_id] + ) + j = len(self._module_to_indices[module_id]) + self._module_to_indices[module_id].extend( + [ + ( + # Keep the MAE index for sampling. + ma_episode_idx, + agent_id, + existing_sa_eps_len + i, + # Get the index in the segment trees. + self._get_free_node_per_module_and_assign( + module_id, + j + i, + module_weight, + ), + ) + for i in range(len(module_eps)) + ] + ) + + @override(PrioritizedEpisodeReplayBuffer) + def _get_free_node_and_assign(self, sample_index, weight: float = 1.0) -> int: + """Gets the next free node in the segment trees. + + In addition the initial priorities for a new transition are added + to the segment trees and the index of the nodes is added to the + index mapping. + + Args: + sample_index: The index of the sample in the `self._indices` list. + weight: The initial priority weight to be used in sampling for + the item at index `sample_index`. + + Returns: + The index in the segment trees `self._sum_segment` and + `self._min_segment` for the item at index `sample_index` in + ``self._indices`. + """ + # Get an index from the free nodes in the segment trees. + idx = self._free_nodes.popleft() + self._max_idx = idx if idx > self._max_idx else self._max_idx + # Add the weight to the segments. + self._sum_segment[idx] = weight**self._alpha + self._min_segment[idx] = weight**self._alpha + # Map the index in the trees to the index in `self._indices`. + self._tree_idx_to_sample_idx[idx] = sample_index + self._sample_idx_to_tree_idx[sample_index] = idx + # Return the index. + return idx + + def _get_free_node_per_module_and_assign( + self, module_id: ModuleID, sample_index, weight: float = 1.0 + ) -> int: + """Gets the next free node in the segment trees. + + In addition the initial priorities for a new transition are added + to the segment trees and the index of the nodes is added to the + index mapping. + + Args: + sample_index: The index of the sample in the `self._indices` list. + weight: The initial priority weight to be used in sampling for + the item at index `sample_index`. + + Returns: + The index in the segment trees `self._sum_segment` and + `self._min_segment` for the item at index `sample_index` in + ``self._indices`. + """ + # Get an index from the free nodes in the segment trees. + idx = self._module_to_free_nodes[module_id].popleft() + self._module_to_max_idx[module_id] = ( + idx + if idx > self._module_to_max_idx[module_id] + else self._module_to_max_idx[module_id] + ) + # Add the weight to the segments. + # TODO (simon): Allow alpha to be chosen per module. + self._module_to_sum_segment[module_id][idx] = weight**self._alpha + self._module_to_min_segment[module_id][idx] = weight**self._alpha + # Map the index in the trees to the index in `self._indices`. + self._module_to_tree_idx_to_sample_idx[module_id][idx] = sample_index + # Return the index. + return idx + + @override(MultiAgentEpisodeReplayBuffer) + def _sample_independent( + self, + batch_size_B: Optional[int], + batch_length_T: Optional[int], + n_step: Optional[Union[int, Tuple]], + gamma: float, + include_infos: bool, + include_extra_model_outputs: bool, + modules_to_sample: Optional[List[ModuleID]], + beta: Optional[float], + ) -> List["SingleAgentEpisode"]: + """Samples a single-agent episode list with independent transitions. + + Note, independent sampling means that each module samples its transitions + independently from the replay buffer. This is the default sampling mode. + In contrast, synchronized sampling samples transitions from the same + environment step. + """ + + actual_n_step = n_step or 1 + # Sample the n-step if necessary. + random_n_step = isinstance(n_step, tuple) + + # Keep track of the indices that were sampled last for updating the + # weights later (see `ray.rllib.utils.replay_buffer.utils. + # update_priorities_in_episode_replay_buffer`). + # self._last_sampled_indices = defaultdict(lambda: []) + + sampled_episodes = [] + # Record the number of samples per module/agent/total. + num_env_steps_sampled = 0 + agent_to_num_steps_sampled = defaultdict(int) + module_to_num_steps_sampled = defaultdict(int) + # Record all the env step buffer indices that are contained in the sample. + sampled_env_step_idxs = set() + agent_to_sampled_env_step_idxs = defaultdict(set) + module_to_sampled_env_step_idxs = defaultdict(set) + # Record all the episode buffer indices that are contained in the sample. + sampled_episode_idxs = set() + agent_to_sampled_episode_idxs = defaultdict(set) + module_to_sampled_episode_idxs = defaultdict(set) + # Record all n-steps that have been used. + sampled_n_steps = [] + agent_to_sampled_n_steps = defaultdict(list) + module_to_sampled_n_steps = defaultdict(list) + # Record the number of times a sample needs to be resampled. + num_resamples = 0 + agent_to_num_resamples = defaultdict(int) + module_to_num_resamples = defaultdict(int) + + # TODO (simon): Ensure that the module has data and if not, skip it. + # TODO (sven): Should we then error out or skip? I think the Learner + # should handle this case when a module has no train data. + modules_to_sample = modules_to_sample or set(self._module_to_indices.keys()) + for module_id in modules_to_sample: + # Sample proportionally from the replay buffer's module segments using the + # respective weights. + module_total_segment_sum = self._module_to_sum_segment[module_id].sum() + module_p_min = ( + self._module_to_min_segment[module_id].min() / module_total_segment_sum + ) + # TODO (simon): Allow individual betas per module. + module_max_weight = (module_p_min * self.get_num_timesteps(module_id)) ** ( + -beta + ) + B = 0 + while B < batch_size_B: + # First, draw a random sample from Uniform(0, sum over all weights). + # Note, transitions with higher weight get sampled more often (as + # more random draws fall into larger intervals). + module_random_sum = ( + self.rng.random() * self._module_to_sum_segment[module_id].sum() + ) + # Get the highest index in the sum-tree for which the sum is + # smaller or equal the random sum sample. + # Note, in contrast to Schaul et al. (2018) (who sample + # `o_(t + n_step)`, Algorithm 1) we sample `o_t`. + module_idx = self._module_to_sum_segment[module_id].find_prefixsum_idx( + module_random_sum + ) + # Get the theoretical probability mass for drawing this sample. + module_p_sample = ( + self._module_to_sum_segment[module_id][module_idx] + / module_total_segment_sum + ) + # Compute the importance sampling weight. + module_weight = ( + module_p_sample * self.get_num_timesteps(module_id) + ) ** (-beta) + # Now, get the transition stored at this index. + index_quadlet = self._module_to_indices[module_id][ + self._module_to_tree_idx_to_sample_idx[module_id][module_idx] + ] + + # This will be an agent timestep (not env timestep). + # TODO (simon, sven): Maybe deprecate sa_episode_idx (_) in the index + # quads. Is there any need for it? + ma_episode_idx, agent_id, sa_episode_ts = ( + index_quadlet[0] - self._num_episodes_evicted, + index_quadlet[1], + index_quadlet[2], + ) + + # Get the multi-agent episode. + ma_episode = self.episodes[ma_episode_idx] + # Retrieve the single-agent episode for filtering. + sa_episode = ma_episode.agent_episodes[agent_id] + + # If we use random n-step sampling, draw the n-step for this item. + if random_n_step: + actual_n_step = int(self.rng.integers(n_step[0], n_step[1])) + # If we cannnot make the n-step, we resample. + if sa_episode_ts + actual_n_step > len(sa_episode): + num_resamples += 1 + agent_to_num_resamples[agent_id] += 1 + module_to_num_resamples[module_id] += 1 + continue + # Note, this will be the reward after executing action + # `a_(episode_ts)`. For `n_step>1` this will be the discounted sum + # of all rewards that were collected over the last n steps. + sa_raw_rewards = sa_episode.get_rewards( + slice(sa_episode_ts, sa_episode_ts + actual_n_step) + ) + sa_rewards = scipy.signal.lfilter( + [1], [1, -gamma], sa_raw_rewards[::-1], axis=0 + )[-1] + + sampled_sa_episode = SingleAgentEpisode( + id_=sa_episode.id_, + # Provide the IDs for the learner connector. + agent_id=sa_episode.agent_id, + module_id=sa_episode.module_id, + multi_agent_episode_id=ma_episode.id_, + # Ensure that each episode contains a tuple of the form: + # (o_t, a_t, sum(r_(t:t+n_step)), o_(t+n_step)) + # Two observations (t and t+n). + observations=[ + sa_episode.get_observations(sa_episode_ts), + sa_episode.get_observations(sa_episode_ts + actual_n_step), + ], + observation_space=sa_episode.observation_space, + infos=( + [ + sa_episode.get_infos(sa_episode_ts), + sa_episode.get_infos(sa_episode_ts + actual_n_step), + ] + if include_infos + else None + ), + actions=[sa_episode.get_actions(sa_episode_ts)], + action_space=sa_episode.action_space, + rewards=[sa_rewards], + # If the sampled single-agent episode is the single-agent episode's + # last time step, check, if the single-agent episode is terminated + # or truncated. + terminated=( + sa_episode_ts + actual_n_step >= len(sa_episode) + and sa_episode.is_terminated + ), + truncated=( + sa_episode_ts + actual_n_step >= len(sa_episode) + and sa_episode.is_truncated + ), + extra_model_outputs={ + "weights": [ + module_weight / module_max_weight * 1 + ], # actual_size=1 + "n_step": [actual_n_step], + **( + { + k: [ + sa_episode.get_extra_model_outputs(k, sa_episode_ts) + ] + for k in sa_episode.extra_model_outputs.keys() + } + if include_extra_model_outputs + else {} + ), + }, + # TODO (sven): Support lookback buffers. + len_lookback_buffer=0, + t_started=sa_episode_ts, + ) + # Append single-agent episode to the list of sampled episodes. + sampled_episodes.append(sampled_sa_episode) + # Add the episode indices. + sampled_episode_idxs.add(ma_episode_idx) + agent_to_sampled_episode_idxs[sa_episode.agent_id].add(sa_episode.id_) + module_to_sampled_episode_idxs[module_id].add(sa_episode.id_) + # Get the corresponding index in the `env_to_agent_t` mapping. + # TODO (simon, sven): This has complexity O(n) and could become + # expensive when the episode is large. Note, however, that conversion + # from list to `numpy.ndarray` is also complexity O(n) and we do this + # at many places - also in the `MultiAgentEpisode`s. + ma_episode_ts = ma_episode.env_t_to_agent_t[agent_id].data.index( + sa_episode_ts + ) + # Add the unique step hashes. + sampled_env_step_idxs.add( + hashlib.sha256( + f"{ma_episode.id_}-{ma_episode_ts}".encode() + ).hexdigest() + ) + # Add the unique agent step hashes. + hashed_agent_step = hashlib.sha256( + f"{sa_episode.id_}-{sa_episode_ts}".encode() + ).hexdigest() + agent_to_sampled_env_step_idxs[agent_id].add(hashed_agent_step) + # Add the unique module step hashes. + module_to_sampled_env_step_idxs[module_id].add(hashed_agent_step) + # Add the actual n-step used in generating this sample. + sampled_n_steps.append(actual_n_step) + agent_to_sampled_n_steps[agent_id].append(actual_n_step) + module_to_sampled_n_steps[module_id].append(actual_n_step) + + # Increase counter. + B += 1 + # Keep track of sampled indices for updating priorities later for each + # module. + self._module_to_last_sampled_indices[module_id].append(module_idx) + + # Increase the per module timesteps counter. + self.sampled_timesteps_per_module[module_id] += B + # Increase the counter metrics. + num_env_steps_sampled += B + agent_to_num_steps_sampled[agent_id] += B + module_to_num_steps_sampled[module_id] += B + + # Increase the counter for environment timesteps. + self.sampled_timesteps += batch_size_B + + # Update the sample metrics. + num_episodes_per_sample = len(sampled_episode_idxs) + num_env_steps_per_sample = len(sampled_env_step_idxs) + sampled_n_step = sum(sampled_n_steps) / batch_size_B + agent_to_num_episodes_per_sample = { + aid: len(l) for aid, l in agent_to_sampled_episode_idxs.items() + } + module_to_num_episodes_per_sample = { + mid: len(l) for mid, l in module_to_sampled_episode_idxs.items() + } + agent_to_num_steps_per_sample = { + aid: len(l) for aid, l in agent_to_sampled_env_step_idxs.items() + } + module_to_num_steps_per_sample = { + mid: len(l) for mid, l in module_to_sampled_env_step_idxs.items() + } + agent_to_sampled_n_step = { + aid: sum(l) / len(l) for aid, l in agent_to_sampled_n_steps.items() + } + module_to_sampled_n_step = { + mid: sum(l) / len(l) for mid, l in module_to_sampled_n_steps.items() + } + self._update_sample_metrics( + num_env_steps_sampled=num_env_steps_sampled, + num_episodes_per_sample=num_episodes_per_sample, + num_env_steps_per_sample=num_env_steps_per_sample, + sampled_n_step=sampled_n_step, + num_resamples=num_resamples, + agent_to_num_steps_sampled=agent_to_num_steps_sampled, + agent_to_num_episodes_per_sample=agent_to_num_episodes_per_sample, + agent_to_num_steps_per_sample=agent_to_num_steps_per_sample, + agent_to_sampled_n_step=agent_to_sampled_n_step, + agent_to_num_resamples=agent_to_num_resamples, + module_to_num_steps_sampled=module_to_num_steps_sampled, + module_to_num_episodes_per_sample=module_to_num_episodes_per_sample, + module_to_num_steps_per_sample=module_to_num_steps_per_sample, + module_to_sampled_n_step=module_to_sampled_n_step, + module_to_num_resamples=module_to_num_resamples, + ) + + # Return multi-agent dictionary. + return sampled_episodes diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_replay_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..368b95d737ed6b85f64bd7091599c7bab4bc14b8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_prioritized_replay_buffer.py @@ -0,0 +1,279 @@ +from typing import Dict +import logging +import numpy as np + +from ray.util.timer import _Timer +from ray.rllib.utils.annotations import override +from ray.rllib.utils.replay_buffers.multi_agent_replay_buffer import ( + MultiAgentReplayBuffer, + ReplayMode, + merge_dicts_with_warning, +) +from ray.rllib.utils.replay_buffers.prioritized_replay_buffer import ( + PrioritizedReplayBuffer, +) +from ray.rllib.utils.replay_buffers.replay_buffer import ( + StorageUnit, +) +from ray.rllib.utils.typing import PolicyID, SampleBatchType +from ray.rllib.policy.sample_batch import SampleBatch +from ray.util.debug import log_once +from ray.util.annotations import DeveloperAPI +from ray.rllib.policy.rnn_sequencing import timeslice_along_seq_lens_with_overlap + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class MultiAgentPrioritizedReplayBuffer( + MultiAgentReplayBuffer, PrioritizedReplayBuffer +): + """A prioritized replay buffer shard for multiagent setups. + + This buffer is meant to be run in parallel to distribute experiences + across `num_shards` shards. Unlike simpler buffers, it holds a set of + buffers - one for each policy ID. + """ + + def __init__( + self, + capacity: int = 10000, + storage_unit: str = "timesteps", + num_shards: int = 1, + replay_mode: str = "independent", + replay_sequence_override: bool = True, + replay_sequence_length: int = 1, + replay_burn_in: int = 0, + replay_zero_init_states: bool = True, + underlying_buffer_config: dict = None, + prioritized_replay_alpha: float = 0.6, + prioritized_replay_beta: float = 0.4, + prioritized_replay_eps: float = 1e-6, + **kwargs, + ): + """Initializes a MultiAgentReplayBuffer instance. + + Args: + capacity: The capacity of the buffer, measured in `storage_unit`. + storage_unit: Either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. If they + are stored in episodes, replay_sequence_length is ignored. + If they are stored in episodes, replay_sequence_length is + ignored. + num_shards: The number of buffer shards that exist in total + (including this one). + replay_mode: One of "independent" or "lockstep". Determines, + whether batches are sampled independently or to an equal + amount. + replay_sequence_override: If True, ignore sequences found in incoming + batches, slicing them into sequences as specified by + `replay_sequence_length` and `replay_sequence_burn_in`. This only has + an effect if storage_unit is `sequences`. + replay_sequence_length: The sequence length (T) of a single + sample. If > 1, we will sample B x T from this buffer. + replay_burn_in: The burn-in length in case + `replay_sequence_length` > 0. This is the number of timesteps + each sequence overlaps with the previous one to generate a + better internal state (=state after the burn-in), instead of + starting from 0.0 each RNN rollout. + replay_zero_init_states: Whether the initial states in the + buffer (if replay_sequence_length > 0) are alwayas 0.0 or + should be updated with the previous train_batch state outputs. + underlying_buffer_config: A config that contains all necessary + constructor arguments and arguments for methods to call on + the underlying buffers. This replaces the standard behaviour + of the underlying PrioritizedReplayBuffer. The config + follows the conventions of the general + replay_buffer_config. kwargs for subsequent calls of methods + may also be included. Example: + "replay_buffer_config": {"type": PrioritizedReplayBuffer, + "capacity": 10, "storage_unit": "timesteps", + prioritized_replay_alpha: 0.5, prioritized_replay_beta: 0.5, + prioritized_replay_eps: 0.5} + prioritized_replay_alpha: Alpha parameter for a prioritized + replay buffer. Use 0.0 for no prioritization. + prioritized_replay_beta: Beta parameter for a prioritized + replay buffer. + prioritized_replay_eps: Epsilon parameter for a prioritized + replay buffer. + ``**kwargs``: Forward compatibility kwargs. + """ + if "replay_mode" in kwargs and ( + kwargs["replay_mode"] == "lockstep" + or kwargs["replay_mode"] == ReplayMode.LOCKSTEP + ): + if log_once("lockstep_mode_not_supported"): + logger.error( + "Replay mode `lockstep` is not supported for " + "MultiAgentPrioritizedReplayBuffer. " + "This buffer will run in `independent` mode." + ) + kwargs["replay_mode"] = "independent" + + if underlying_buffer_config is not None: + if log_once("underlying_buffer_config_not_supported"): + logger.info( + "PrioritizedMultiAgentReplayBuffer instantiated " + "with underlying_buffer_config. This will " + "overwrite the standard behaviour of the " + "underlying PrioritizedReplayBuffer." + ) + prioritized_replay_buffer_config = underlying_buffer_config + else: + prioritized_replay_buffer_config = { + "type": PrioritizedReplayBuffer, + "alpha": prioritized_replay_alpha, + "beta": prioritized_replay_beta, + } + + shard_capacity = capacity // num_shards + MultiAgentReplayBuffer.__init__( + self, + capacity=shard_capacity, + storage_unit=storage_unit, + replay_sequence_override=replay_sequence_override, + replay_mode=replay_mode, + replay_sequence_length=replay_sequence_length, + replay_burn_in=replay_burn_in, + replay_zero_init_states=replay_zero_init_states, + underlying_buffer_config=prioritized_replay_buffer_config, + **kwargs, + ) + + self.prioritized_replay_eps = prioritized_replay_eps + self.update_priorities_timer = _Timer() + + @DeveloperAPI + @override(MultiAgentReplayBuffer) + def _add_to_underlying_buffer( + self, policy_id: PolicyID, batch: SampleBatchType, **kwargs + ) -> None: + """Add a batch of experiences to the underlying buffer of a policy. + + If the storage unit is `timesteps`, cut the batch into timeslices + before adding them to the appropriate buffer. Otherwise, let the + underlying buffer decide how slice batches. + + Args: + policy_id: ID of the policy that corresponds to the underlying + buffer + batch: SampleBatch to add to the underlying buffer + ``**kwargs``: Forward compatibility kwargs. + """ + # Merge kwargs, overwriting standard call arguments + kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs) + + # For the storage unit `timesteps`, the underlying buffer will + # simply store the samples how they arrive. For sequences and + # episodes, the underlying buffer may split them itself. + if self.storage_unit is StorageUnit.TIMESTEPS: + timeslices = batch.timeslices(1) + elif self.storage_unit is StorageUnit.SEQUENCES: + timeslices = timeslice_along_seq_lens_with_overlap( + sample_batch=batch, + seq_lens=batch.get(SampleBatch.SEQ_LENS) + if self.replay_sequence_override + else None, + zero_pad_max_seq_len=self.replay_sequence_length, + pre_overlap=self.replay_burn_in, + zero_init_states=self.replay_zero_init_states, + ) + elif self.storage_unit == StorageUnit.EPISODES: + timeslices = [] + for eps in batch.split_by_episode(): + if eps.get(SampleBatch.T)[0] == 0 and ( + eps.get(SampleBatch.TERMINATEDS, [True])[-1] + or eps.get(SampleBatch.TRUNCATEDS, [False])[-1] + ): + # Only add full episodes to the buffer + timeslices.append(eps) + else: + if log_once("only_full_episodes"): + logger.info( + "This buffer uses episodes as a storage " + "unit and thus allows only full episodes " + "to be added to it. Some samples may be " + "dropped." + ) + elif self.storage_unit == StorageUnit.FRAGMENTS: + timeslices = [batch] + else: + raise ValueError("Unknown `storage_unit={}`".format(self.storage_unit)) + + for slice in timeslices: + # If SampleBatch has prio-replay weights, average + # over these to use as a weight for the entire + # sequence. + if self.replay_mode is ReplayMode.INDEPENDENT: + if "weights" in slice and len(slice["weights"]): + weight = np.mean(slice["weights"]) + else: + weight = None + + if "weight" in kwargs and weight is not None: + if log_once("overwrite_weight"): + logger.warning( + "Adding batches with column " + "`weights` to this buffer while " + "providing weights as a call argument " + "to the add method results in the " + "column being overwritten." + ) + + kwargs = {"weight": weight, **kwargs} + else: + if "weight" in kwargs: + if log_once("lockstep_no_weight_allowed"): + logger.warning( + "Settings weights for batches in " + "lockstep mode is not allowed." + "Weights are being ignored." + ) + + kwargs = {**kwargs, "weight": None} + self.replay_buffers[policy_id].add(slice, **kwargs) + + @DeveloperAPI + @override(PrioritizedReplayBuffer) + def update_priorities(self, prio_dict: Dict) -> None: + """Updates the priorities of underlying replay buffers. + + Computes new priorities from td_errors and prioritized_replay_eps. + These priorities are used to update underlying replay buffers per + policy_id. + + Args: + prio_dict: A dictionary containing td_errors for + batches saved in underlying replay buffers. + """ + with self.update_priorities_timer: + for policy_id, (batch_indexes, td_errors) in prio_dict.items(): + new_priorities = np.abs(td_errors) + self.prioritized_replay_eps + self.replay_buffers[policy_id].update_priorities( + batch_indexes, new_priorities + ) + + @DeveloperAPI + @override(MultiAgentReplayBuffer) + def stats(self, debug: bool = False) -> Dict: + """Returns the stats of this buffer and all underlying buffers. + + Args: + debug: If True, stats of underlying replay buffers are + fetched with debug=True. + + Returns: + stat: Dictionary of buffer stats. + """ + stat = { + "add_batch_time_ms": round(1000 * self.add_batch_timer.mean, 3), + "replay_time_ms": round(1000 * self.replay_timer.mean, 3), + "update_priorities_time_ms": round( + 1000 * self.update_priorities_timer.mean, 3 + ), + } + for policy_id, replay_buffer in self.replay_buffers.items(): + stat.update( + {"policy_{}".format(policy_id): replay_buffer.stats(debug=debug)} + ) + return stat diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_replay_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..ac3af0125b27dcaf2487491ef6a1a653531f525a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/multi_agent_replay_buffer.py @@ -0,0 +1,392 @@ +import collections +import logging +from enum import Enum +from typing import Any, Dict, Optional + +from ray.util.timer import _Timer +from ray.rllib.policy.rnn_sequencing import timeslice_along_seq_lens_with_overlap +from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.replay_buffers.replay_buffer import ( + _ALL_POLICIES, + ReplayBuffer, + StorageUnit, +) +from ray.rllib.utils.typing import PolicyID, SampleBatchType +from ray.util.annotations import DeveloperAPI +from ray.util.debug import log_once + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class ReplayMode(Enum): + LOCKSTEP = "lockstep" + INDEPENDENT = "independent" + + +@DeveloperAPI +def merge_dicts_with_warning(args_on_init, args_on_call): + """Merge argument dicts, overwriting args_on_call with warning. + + The MultiAgentReplayBuffer supports setting standard arguments for calls + of methods of the underlying buffers. These arguments can be + overwritten. Such overwrites trigger a warning to the user. + """ + for arg_name, arg_value in args_on_call.items(): + if arg_name in args_on_init: + if log_once("overwrite_argument_{}".format((str(arg_name)))): + logger.warning( + "Replay Buffer was initialized to have " + "underlying buffers methods called with " + "argument `{}={}`, but was subsequently called " + "with `{}={}`.".format( + arg_name, + args_on_init[arg_name], + arg_name, + arg_value, + ) + ) + return {**args_on_init, **args_on_call} + + +@DeveloperAPI +class MultiAgentReplayBuffer(ReplayBuffer): + """A replay buffer shard for multiagent setups. + + This buffer is meant to be run in parallel to distribute experiences + across `num_shards` shards. Unlike simpler buffers, it holds a set of + buffers - one for each policy ID. + """ + + def __init__( + self, + capacity: int = 10000, + storage_unit: str = "timesteps", + num_shards: int = 1, + replay_mode: str = "independent", + replay_sequence_override: bool = True, + replay_sequence_length: int = 1, + replay_burn_in: int = 0, + replay_zero_init_states: bool = True, + underlying_buffer_config: dict = None, + **kwargs, + ): + """Initializes a MultiAgentReplayBuffer instance. + + Args: + capacity: The capacity of the buffer, measured in `storage_unit`. + storage_unit: Either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. If they + are stored in episodes, replay_sequence_length is ignored. + num_shards: The number of buffer shards that exist in total + (including this one). + replay_mode: One of "independent" or "lockstep". Determines, + whether batches are sampled independently or to an equal + amount. + replay_sequence_override: If True, ignore sequences found in incoming + batches, slicing them into sequences as specified by + `replay_sequence_length` and `replay_sequence_burn_in`. This only has + an effect if storage_unit is `sequences`. + replay_sequence_length: The sequence length (T) of a single + sample. If > 1, we will sample B x T from this buffer. This + only has an effect if storage_unit is 'timesteps'. + replay_burn_in: This is the number of timesteps + each sequence overlaps with the previous one to generate a + better internal state (=state after the burn-in), instead of + starting from 0.0 each RNN rollout. This only has an effect + if storage_unit is `sequences`. + replay_zero_init_states: Whether the initial states in the + buffer (if replay_sequence_length > 0) are alwayas 0.0 or + should be updated with the previous train_batch state outputs. + underlying_buffer_config: A config that contains all necessary + constructor arguments and arguments for methods to call on + the underlying buffers. + ``**kwargs``: Forward compatibility kwargs. + """ + shard_capacity = capacity // num_shards + ReplayBuffer.__init__(self, capacity, storage_unit) + + # If the user provides an underlying buffer config, we use to + # instantiate and interact with underlying buffers + self.underlying_buffer_config = underlying_buffer_config + if self.underlying_buffer_config is not None: + self.underlying_buffer_call_args = self.underlying_buffer_config + else: + self.underlying_buffer_call_args = {} + self.replay_sequence_override = replay_sequence_override + self.replay_mode = replay_mode + self.replay_sequence_length = replay_sequence_length + self.replay_burn_in = replay_burn_in + self.replay_zero_init_states = replay_zero_init_states + self.replay_sequence_override = replay_sequence_override + + if ( + replay_sequence_length > 1 + and self.storage_unit is not StorageUnit.SEQUENCES + ): + logger.warning( + "MultiAgentReplayBuffer configured with " + "`replay_sequence_length={}`, but `storage_unit={}`. " + "replay_sequence_length will be ignored and set to 1.".format( + replay_sequence_length, storage_unit + ) + ) + self.replay_sequence_length = 1 + + if replay_sequence_length == 1 and self.storage_unit is StorageUnit.SEQUENCES: + logger.warning( + "MultiAgentReplayBuffer configured with " + "`replay_sequence_length={}`, but `storage_unit={}`. " + "This will result in sequences equal to timesteps.".format( + replay_sequence_length, storage_unit + ) + ) + + if replay_mode in ["lockstep", ReplayMode.LOCKSTEP]: + self.replay_mode = ReplayMode.LOCKSTEP + if self.storage_unit in [StorageUnit.EPISODES, StorageUnit.SEQUENCES]: + raise ValueError( + "MultiAgentReplayBuffer does not support " + "lockstep mode with storage unit `episodes`" + "or `sequences`." + ) + elif replay_mode in ["independent", ReplayMode.INDEPENDENT]: + self.replay_mode = ReplayMode.INDEPENDENT + else: + raise ValueError("Unsupported replay mode: {}".format(replay_mode)) + + if self.underlying_buffer_config: + ctor_args = { + **{"capacity": shard_capacity, "storage_unit": StorageUnit.FRAGMENTS}, + **self.underlying_buffer_config, + } + + def new_buffer(): + return from_config(self.underlying_buffer_config["type"], ctor_args) + + else: + # Default case + def new_buffer(): + self.underlying_buffer_call_args = {} + return ReplayBuffer( + self.capacity, + storage_unit=StorageUnit.FRAGMENTS, + ) + + self.replay_buffers = collections.defaultdict(new_buffer) + + # Metrics. + self.add_batch_timer = _Timer() + self.replay_timer = _Timer() + self._num_added = 0 + + def __len__(self) -> int: + """Returns the number of items currently stored in this buffer.""" + return sum(len(buffer._storage) for buffer in self.replay_buffers.values()) + + @DeveloperAPI + @Deprecated( + old="ReplayBuffer.replay()", + new="ReplayBuffer.sample(num_items)", + error=True, + ) + def replay(self, num_items: int = None, **kwargs) -> Optional[SampleBatchType]: + """Deprecated in favor of new ReplayBuffer API.""" + pass + + @DeveloperAPI + @override(ReplayBuffer) + def add(self, batch: SampleBatchType, **kwargs) -> None: + """Adds a batch to the appropriate policy's replay buffer. + + Turns the batch into a MultiAgentBatch of the DEFAULT_POLICY_ID if + it is not a MultiAgentBatch. Subsequently, adds the individual policy + batches to the storage. + + Args: + batch : The batch to be added. + ``**kwargs``: Forward compatibility kwargs. + """ + if batch is None: + if log_once("empty_batch_added_to_buffer"): + logger.info( + "A batch that is `None` was added to {}. This can be " + "normal at the beginning of execution but might " + "indicate an issue.".format(type(self).__name__) + ) + return + # Make a copy so the replay buffer doesn't pin plasma memory. + batch = batch.copy() + # Handle everything as if multi-agent. + batch = batch.as_multi_agent() + + with self.add_batch_timer: + pids_and_batches = self._maybe_split_into_policy_batches(batch) + for policy_id, sample_batch in pids_and_batches.items(): + self._add_to_underlying_buffer(policy_id, sample_batch, **kwargs) + + self._num_added += batch.count + + @DeveloperAPI + def _add_to_underlying_buffer( + self, policy_id: PolicyID, batch: SampleBatchType, **kwargs + ) -> None: + """Add a batch of experiences to the underlying buffer of a policy. + + If the storage unit is `timesteps`, cut the batch into timeslices + before adding them to the appropriate buffer. Otherwise, let the + underlying buffer decide how slice batches. + + Args: + policy_id: ID of the policy that corresponds to the underlying + buffer + batch: SampleBatch to add to the underlying buffer + ``**kwargs``: Forward compatibility kwargs. + """ + # Merge kwargs, overwriting standard call arguments + kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs) + + # For the storage unit `timesteps`, the underlying buffer will + # simply store the samples how they arrive. For sequences and + # episodes, the underlying buffer may split them itself. + if self.storage_unit is StorageUnit.TIMESTEPS: + timeslices = batch.timeslices(1) + elif self.storage_unit is StorageUnit.SEQUENCES: + timeslices = timeslice_along_seq_lens_with_overlap( + sample_batch=batch, + seq_lens=batch.get(SampleBatch.SEQ_LENS) + if self.replay_sequence_override + else None, + zero_pad_max_seq_len=self.replay_sequence_length, + pre_overlap=self.replay_burn_in, + zero_init_states=self.replay_zero_init_states, + ) + elif self.storage_unit == StorageUnit.EPISODES: + timeslices = [] + for eps in batch.split_by_episode(): + if eps.get(SampleBatch.T)[0] == 0 and ( + eps.get(SampleBatch.TERMINATEDS, [True])[-1] + or eps.get(SampleBatch.TRUNCATEDS, [False])[-1] + ): + # Only add full episodes to the buffer + timeslices.append(eps) + else: + if log_once("only_full_episodes"): + logger.info( + "This buffer uses episodes as a storage " + "unit and thus allows only full episodes " + "to be added to it. Some samples may be " + "dropped." + ) + elif self.storage_unit == StorageUnit.FRAGMENTS: + timeslices = [batch] + else: + raise ValueError("Unknown `storage_unit={}`".format(self.storage_unit)) + + for slice in timeslices: + self.replay_buffers[policy_id].add(slice, **kwargs) + + @DeveloperAPI + @override(ReplayBuffer) + def sample( + self, num_items: int, policy_id: Optional[PolicyID] = None, **kwargs + ) -> Optional[SampleBatchType]: + """Samples a MultiAgentBatch of `num_items` per one policy's buffer. + + If less than `num_items` records are in the policy's buffer, + some samples in the results may be repeated to fulfil the batch size + `num_items` request. Returns an empty batch if there are no items in + the buffer. + + Args: + num_items: Number of items to sample from a policy's buffer. + policy_id: ID of the policy that created the experiences we sample. If + none is given, sample from all policies. + + Returns: + Concatenated MultiAgentBatch of items. + ``**kwargs``: Forward compatibility kwargs. + """ + # Merge kwargs, overwriting standard call arguments + kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs) + + with self.replay_timer: + # Lockstep mode: Sample from all policies at the same time an + # equal amount of steps. + if self.replay_mode == ReplayMode.LOCKSTEP: + assert ( + policy_id is None + ), "`policy_id` specifier not allowed in `lockstep` mode!" + # In lockstep mode we sample MultiAgentBatches + return self.replay_buffers[_ALL_POLICIES].sample(num_items, **kwargs) + elif policy_id is not None: + sample = self.replay_buffers[policy_id].sample(num_items, **kwargs) + return MultiAgentBatch({policy_id: sample}, sample.count) + else: + samples = {} + for policy_id, replay_buffer in self.replay_buffers.items(): + samples[policy_id] = replay_buffer.sample(num_items, **kwargs) + return MultiAgentBatch(samples, sum(s.count for s in samples.values())) + + @DeveloperAPI + @override(ReplayBuffer) + def stats(self, debug: bool = False) -> Dict: + """Returns the stats of this buffer and all underlying buffers. + + Args: + debug: If True, stats of underlying replay buffers + are fetched with debug=True. + + Returns: + stat: Dictionary of buffer stats. + """ + stat = { + "add_batch_time_ms": round(1000 * self.add_batch_timer.mean, 3), + "replay_time_ms": round(1000 * self.replay_timer.mean, 3), + } + for policy_id, replay_buffer in self.replay_buffers.items(): + stat.update( + {"policy_{}".format(policy_id): replay_buffer.stats(debug=debug)} + ) + return stat + + @DeveloperAPI + @override(ReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Returns all local state. + + Returns: + The serializable local state. + """ + state = {"num_added": self._num_added, "replay_buffers": {}} + for policy_id, replay_buffer in self.replay_buffers.items(): + state["replay_buffers"][policy_id] = replay_buffer.get_state() + return state + + @DeveloperAPI + @override(ReplayBuffer) + def set_state(self, state: Dict[str, Any]) -> None: + """Restores all local state to the provided `state`. + + Args: + state: The new state to set this buffer. Can be obtained by + calling `self.get_state()`. + """ + self._num_added = state["num_added"] + buffer_states = state["replay_buffers"] + for policy_id in buffer_states.keys(): + self.replay_buffers[policy_id].set_state(buffer_states[policy_id]) + + def _maybe_split_into_policy_batches(self, batch: SampleBatchType): + """Returns a dict of policy IDs and batches, depending on our replay mode. + + This method helps with splitting up MultiAgentBatches only if the + self.replay_mode requires it. + """ + if self.replay_mode == ReplayMode.LOCKSTEP: + return {_ALL_POLICIES: batch} + else: + return batch.policy_batches diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/prioritized_episode_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/prioritized_episode_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..dc00b94cb0d05d6c36a22601ffe01214276776e1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/prioritized_episode_buffer.py @@ -0,0 +1,732 @@ +import copy +import hashlib +import numpy as np +import scipy + +from collections import deque +from numpy.typing import NDArray +from typing import Any, Dict, List, Optional, Tuple, Union + +from ray.rllib.core import DEFAULT_AGENT_ID, DEFAULT_MODULE_ID +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.execution.segment_tree import MinSegmentTree, SumSegmentTree +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import ( + override, +) +from ray.rllib.utils.replay_buffers.episode_replay_buffer import EpisodeReplayBuffer +from ray.rllib.utils.typing import ModuleID, SampleBatchType + + +class PrioritizedEpisodeReplayBuffer(EpisodeReplayBuffer): + """Prioritized Replay Buffer that stores episodes by their ID. + + This replay buffer stores episode data (more specifically `SingleAgentEpisode` + objects) and implements prioritized experience replay first proposed + in the paper by Schaul et al. (2016, https://arxiv.org/abs/1511.05952). + + Implementation is based on segment trees as suggested by the authors of + the cited paper, i.e. we use proportional prioritization with an order + of O(log N) in updating and sampling. + + Each "row" (a slot in a deque) in the buffer is occupied by one episode. If an + incomplete episode is added to the buffer and then another chunk of that episode is + added at a later time, the buffer will automatically concatenate the new fragment to + the original episode. This way, episodes can be completed via subsequent `add` + calls. + + Sampling returns a size `B` episode list (number of 'rows'), where each episode + holds a tuple tuple of the form + + `(o_t, a_t, sum(r_t+1:t+n), o_t+n)` + + where `o_t` is the observation in `t`, `a_t` the action chosen at observation `o_t`, + `o_t+n` is the observation `n` timesteps later and `sum(r_t+1:t+n)` is the sum of + all rewards collected over the time steps between `t+1` and `t+n`. The `n`-step can + be chosen freely when sampling and defaults to `1`. If `n_step` is a tuple it is + sampled uniformly across the interval defined by the tuple (for each row in the + batch). + + Each episode contains - in addition to the data tuples presented above - two further + elements in its ` extra_model_outputs`, namely `n_steps` and `weights`. The former + holds the `n_step` used for the sampled timesteps in the episode and the latter the + corresponding (importance sampling) weight for the transition. + + After sampling priorities can be updated (for the last sampled episode list) with + `self.update_priorities`. This method assigns the new priorities automatically to + the last sampled timesteps. Note, this implies that sampling timesteps and updating + their corresponding priorities needs to alternate (e.g. sampling several times and + then updating the priorities would not work because the buffer caches the last + sampled timestep indices). + + .. testcode:: + + import gymnasium as gym + + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.replay_buffers import ( + PrioritizedEpisodeReplayBuffer + ) + + # Create the environment. + env = gym.make("CartPole-v1") + + # Set up the loop variables + terminated = False + truncated = False + num_timesteps = 10000 + episodes = [] + + # Initialize the first episode entries. + eps = SingleAgentEpisode() + obs, info = env.reset() + eps.add_env_reset(obs, info) + + # Sample 10,000 timesteps. + for i in range(num_timesteps): + # If terminated we create a new episode. + if terminated: + episodes.append(eps.to_numpy()) + eps = SingleAgentEpisode() + obs, info = env.reset() + eps.add_env_reset(obs, info) + + action = env.action_space.sample() + obs, reward, terminated, truncated, info = env.step(action) + eps.add_env_step( + obs, + action, + reward, + info, + terminated=terminated, + truncated=truncated + ) + + # Add the last (truncated) episode to the list of episodes. + if not terminated or truncated: + episodes.append(eps) + + # Create the buffer. + buffer = PrioritizedEpisodeReplayBuffer() + # Add the list of episodes sampled. + buffer.add(episodes) + + # Pull a sample from the buffer using an `n-step` of 3. + sample = buffer.sample(num_items=256, gamma=0.95, n_step=3) + """ + + def __init__( + self, + capacity: int = 10000, + *, + batch_size_B: int = 16, + batch_length_T: int = 1, + alpha: float = 1.0, + metrics_num_episodes_for_smoothing: int = 100, + **kwargs, + ): + """Initializes a `PrioritizedEpisodeReplayBuffer` object + + Args: + capacity: The total number of timesteps to be storable in this buffer. + Will start ejecting old episodes once this limit is reached. + batch_size_B: The number of episodes returned from `sample()`. + batch_length_T: The length of each episode in the episode list returned from + `sample()`. + alpha: The amount of prioritization to be used: `alpha=1.0` means full + prioritization, `alpha=0.0` means no prioritization. + """ + super().__init__( + capacity=capacity, + batch_size_B=batch_size_B, + batch_length_T=batch_length_T, + metrics_num_episodes_for_smoothing=metrics_num_episodes_for_smoothing, + ) + + # `alpha` should be non-negative. + assert alpha >= 0 + self._alpha = alpha + + # Initialize segment trees for the priority weights. Note, b/c the trees + # are binary we need for them a capacity that is an exponential of 2. + # Double it to enable temporary buffer overflow (we need then free nodes + # in the trees). + tree_capacity = int(2 ** np.ceil(np.log2(self.capacity))) + + self._max_priority = 1.0 + self._sum_segment = SumSegmentTree(2 * tree_capacity) + self._min_segment = MinSegmentTree(2 * tree_capacity) + # At initialization all nodes are free. + self._free_nodes = deque( + list(range(2 * tree_capacity)), maxlen=2 * tree_capacity + ) + # Keep track of the maximum index used from the trees. This helps + # to not traverse the complete trees. + self._max_idx = 0 + # Map from tree indices to sample indices (i.e. `self._indices`). + self._tree_idx_to_sample_idx = {} + # Keep track of the indices that were sampled last for updating the + # weights later. + self._last_sampled_indices = [] + + @override(EpisodeReplayBuffer) + def add( + self, + episodes: Union[List["SingleAgentEpisode"], "SingleAgentEpisode"], + weight: Optional[float] = None, + ) -> None: + """Adds incoming episodes to the replay buffer. + + Note, if the incoming episodes' time steps cause the buffer to overflow, + older episodes are evicted. Because episodes usually come in chunks and + not complete, this could lead to edge cases (e.g. with very small capacity + or very long episode length) where the first part of an episode is evicted + while the next part just comes in. + To defend against such case, the complete episode is evicted, including + the new chunk, unless the episode is the only one in the buffer. In the + latter case the buffer will be allowed to overflow in a temporary fashion, + i.e. during the next addition of samples to the buffer an attempt is made + to fall below capacity again. + + The user is advised to select a large enough buffer with regard to the maximum + expected episode length. + + Args: + episodes: A list of `SingleAgentEpisode`s that contain the episode data. + weight: A starting priority for the time steps in `episodes`. If `None` + the maximum priority is used, i.e. 1.0 (as suggested in the original + paper we scale weights to the interval [0.0, 1.0]).. + """ + + # TODO (sven, simon): Eventually allow here an array? + if weight is None: + weight = self._max_priority + + episodes = force_list(episodes) + + # Set up some counters for metrics. + num_env_steps_added = 0 + agent_to_num_steps_added = {DEFAULT_AGENT_ID: 0} + module_to_num_steps_added = {DEFAULT_MODULE_ID: 0} + num_episodes_added = 0 + agent_to_num_episodes_added = {DEFAULT_AGENT_ID: 0} + module_to_num_episodes_added = {DEFAULT_MODULE_ID: 0} + num_episodes_evicted = 0 + agent_to_num_episodes_evicted = {DEFAULT_AGENT_ID: 0} + module_to_num_episodes_evicted = {DEFAULT_MODULE_ID: 0} + num_env_steps_evicted = 0 + agent_to_num_steps_evicted = {DEFAULT_AGENT_ID: 0} + module_to_num_steps_evicted = {DEFAULT_MODULE_ID: 0} + + # Add first the timesteps of new episodes to have info about how many + # episodes should be evicted to stay below capacity. + new_episode_ids = [] + for eps in episodes: + new_episode_ids.append(eps.id_) + self._num_timesteps += len(eps) + self._num_timesteps_added += len(eps) + + eps_evicted = [] + eps_evicted_ids = [] + eps_evicted_idxs = [] + while ( + self._num_timesteps > self.capacity + and self._num_remaining_episodes(new_episode_ids, eps_evicted_ids) != 1 + ): + # Evict episode + eps_evicted.append(self.episodes.popleft()) + eps_evicted_ids.append(eps_evicted[-1].id_) + eps_evicted_idxs.append(self.episode_id_to_index.pop(eps_evicted_ids[-1])) + num_episodes_evicted += 1 + num_env_steps_evicted += len(eps_evicted[-1]) + agent_to_num_episodes_evicted[DEFAULT_AGENT_ID] += 1 + agent_to_num_steps_evicted[DEFAULT_AGENT_ID] += eps_evicted[ + -1 + ].agent_steps() + module_to_num_episodes_evicted[DEFAULT_MODULE_ID] += 1 + module_to_num_steps_evicted[DEFAULT_MODULE_ID] += eps_evicted[ + -1 + ].agent_steps() + # If this episode has a new chunk in the new episodes added, + # we subtract it again. + # TODO (sven, simon): Should we just treat such an episode chunk + # as a new episode? + if eps_evicted_ids[-1] in new_episode_ids: + # TODO (simon): Apply the same logic as in the MA-case. + len_to_subtract = len( + episodes[new_episode_ids.index(eps_evicted_idxs[-1])] + ) + self._num_timesteps -= len_to_subtract + self._num_timesteps_added -= len_to_subtract + # Remove the timesteps of the evicted episode from the counter. + self._num_timesteps -= len(eps_evicted[-1]) + self._num_episodes_evicted += 1 + + # Remove corresponding indices, if episodes were evicted. + # TODO (simon): Refactor into method such that MultiAgent + # version can inherit. + if eps_evicted_idxs: + new_indices = [] + i = 0 + for idx_triple in self._indices: + # If the index comes from an evicted episode free the nodes. + if idx_triple[0] in eps_evicted_idxs: + # Here we need the index of a sample in the segment tree. + self._free_nodes.appendleft(idx_triple[2]) + # Also remove the potentially maximum index. + self._max_idx -= 1 if self._max_idx == idx_triple[2] else 0 + self._sum_segment[idx_triple[2]] = 0.0 + self._min_segment[idx_triple[2]] = float("inf") + self._tree_idx_to_sample_idx.pop(idx_triple[2]) + # Otherwise update the index in the index mapping. + else: + new_indices.append(idx_triple) + self._tree_idx_to_sample_idx[idx_triple[2]] = i + i += 1 + # Assign the new list of indices. + self._indices = new_indices + + # Now append the indices for the new episodes. + j = len(self._indices) + for eps in episodes: + # If the episode chunk is part of an evicted episode continue. + if eps.id_ in eps_evicted_ids: + continue + # Otherwise, add the episode data to the buffer. + else: + eps = copy.deepcopy(eps) + # If the episode is part of an already existing episode, concatenate. + if eps.id_ in self.episode_id_to_index: + eps_idx = self.episode_id_to_index[eps.id_] + existing_eps = self.episodes[eps_idx - self._num_episodes_evicted] + old_len = len(existing_eps) + self._indices.extend( + [ + ( + eps_idx, + old_len + i, + # Get the index in the segment trees. + self._get_free_node_and_assign(j + i, weight), + ) + for i in range(len(eps)) + ] + ) + existing_eps.concat_episode(eps) + # Otherwise, create a new entry. + else: + num_episodes_added += 1 + agent_to_num_episodes_added[DEFAULT_AGENT_ID] += 1 + module_to_num_episodes_added[DEFAULT_MODULE_ID] += 1 + self.episodes.append(eps) + eps_idx = len(self.episodes) - 1 + self._num_episodes_evicted + self.episode_id_to_index[eps.id_] = eps_idx + self._indices.extend( + [ + ( + eps_idx, + i, + self._get_free_node_and_assign(j + i, weight), + ) + for i in range(len(eps)) + ] + ) + num_env_steps_added += len(eps) + agent_to_num_steps_added[DEFAULT_AGENT_ID] += eps.agent_steps() + module_to_num_steps_added[DEFAULT_MODULE_ID] += eps.agent_steps() + # Increase index to the new length of `self._indices`. + j = len(self._indices) + + # Increase metrics. + self._update_add_metrics( + num_episodes_added=num_episodes_added, + num_env_steps_added=num_env_steps_added, + num_episodes_evicted=num_episodes_evicted, + num_env_steps_evicted=num_env_steps_evicted, + agent_to_num_episodes_added=agent_to_num_episodes_added, + agent_to_num_steps_added=agent_to_num_steps_added, + agent_to_num_episodes_evicted=agent_to_num_episodes_evicted, + agent_to_num_steps_evicted=agent_to_num_steps_evicted, + module_to_num_episodes_added=module_to_num_steps_added, + module_to_num_steps_added=module_to_num_episodes_added, + module_to_num_episodes_evicted=module_to_num_episodes_evicted, + module_to_num_steps_evicted=module_to_num_steps_evicted, + ) + + @override(EpisodeReplayBuffer) + def sample( + self, + num_items: Optional[int] = None, + *, + batch_size_B: Optional[int] = None, + batch_length_T: Optional[int] = None, + n_step: Optional[Union[int, Tuple]] = None, + beta: float = 0.0, + gamma: float = 0.99, + include_infos: bool = False, + include_extra_model_outputs: bool = False, + to_numpy: bool = False, + **kwargs, + ) -> SampleBatchType: + """Samples from a buffer in a prioritized way. + + This sampling method also adds (importance sampling) weights to + the returned batch. See for prioritized sampling Schaul et al. + (2016). + + Each sampled item defines a transition of the form: + + `(o_t, a_t, sum(r_(t+1:t+n+1)), o_(t+n), terminated_(t+n), truncated_(t+n))` + + where `o_(t+n)` is drawn by prioritized sampling, i.e. the priority + of `o_(t+n)` led to the sample and defines the importance weight that + is returned in the sample batch. `n` is defined by the `n_step` applied. + + If requested, `info`s of a transitions last timestep `t+n` are added to + the batch. + + Args: + num_items: Number of items (transitions) to sample from this + buffer. + batch_size_B: The number of rows (transitions) to return in the + batch + batch_length_T: THe sequence length to sample. At this point in time + only sequences of length 1 are possible. + n_step: The n-step to apply. For the default the batch contains in + `"new_obs"` the observation and in `"obs"` the observation `n` + time steps before. The reward will be the sum of rewards + collected in between these two observations and the action will + be the one executed n steps before such that we always have the + state-action pair that triggered the rewards. + If `n_step` is a tuple, it is considered as a range to sample + from. If `None`, we use `n_step=1`. + beta: The exponent of the importance sampling weight (see Schaul et + al. (2016)). A `beta=0.0` does not correct for the bias introduced + by prioritized replay and `beta=1.0` fully corrects for it. + gamma: The discount factor to be used when applying n-step calculations. + The default of `0.99` should be replaced by the `Algorithm`s + discount factor. + include_infos: A boolean indicating, if `info`s should be included in + the batch. This could be of advantage, if the `info` contains + values from the environment important for loss computation. If + `True`, the info at the `"new_obs"` in the batch is included. + include_extra_model_outputs: A boolean indicating, if + `extra_model_outputs` should be included in the batch. This could be + of advantage, if the `extra_mdoel_outputs` contain outputs from the + model important for loss computation and only able to compute with the + actual state of model e.g. action log-probabilities, etc.). If `True`, + the extra model outputs at the `"obs"` in the batch is included (the + timestep at which the action is computed). + + Returns: + A list of 1-step long episodes containing all basic episode data and if + requested infos and extra model outputs. + """ + assert beta >= 0.0 + + if num_items is not None: + assert batch_size_B is None, ( + "Cannot call `sample()` with both `num_items` and `batch_size_B` " + "provided! Use either one." + ) + batch_size_B = num_items + + # Use our default values if no sizes/lengths provided. + batch_size_B = batch_size_B or self.batch_size_B + # TODO (simon): Implement trajectory sampling for RNNs. + batch_length_T = batch_length_T or self.batch_length_T + + # Sample the n-step if necessary. + actual_n_step = n_step or 1 + random_n_step = isinstance(n_step, tuple) + + # Keep track of the indices that were sampled last for updating the + # weights later (see `ray.rllib.utils.replay_buffer.utils. + # update_priorities_in_episode_replay_buffer`). + self._last_sampled_indices = [] + + sampled_episodes = [] + # Record all the env step buffer indices that are contained in the sample. + sampled_env_step_idxs = set() + # Record all the episode buffer indices that are contained in the sample. + sampled_episode_idxs = set() + # Record all n-steps that have been used. + sampled_n_steps = [] + # Record the number of times it needs to be resampled. + num_resamples = 0 + + # Sample proportionally from replay buffer's segments using the weights. + total_segment_sum = self._sum_segment.sum() + p_min = self._min_segment.min() / total_segment_sum + max_weight = (p_min * self.get_num_timesteps()) ** (-beta) + B = 0 + while B < batch_size_B: + # First, draw a random sample from Uniform(0, sum over all weights). + # Note, transitions with higher weight get sampled more often (as + # more random draws fall into larger intervals). + random_sum = self.rng.random() * self._sum_segment.sum() + # Get the highest index in the sum-tree for which the sum is + # smaller or equal the random sum sample. + # Note, in contrast to Schaul et al. (2018) (who sample `o_(t + n_step)`, + # Algorithm 1) we sample `o_t`. + idx = self._sum_segment.find_prefixsum_idx(random_sum) + # Get the theoretical probability mass for drawing this sample. + p_sample = self._sum_segment[idx] / total_segment_sum + # Compute the importance sampling weight. + weight = (p_sample * self.get_num_timesteps()) ** (-beta) + # Now, get the transition stored at this index. + index_triple = self._indices[self._tree_idx_to_sample_idx[idx]] + + # Compute the actual episode index (offset by the number of + # already evicted episodes) + episode_idx, episode_ts = ( + index_triple[0] - self._num_episodes_evicted, + index_triple[1], + ) + episode = self.episodes[episode_idx] + + # If we use random n-step sampling, draw the n-step for this item. + if random_n_step: + actual_n_step = int(self.rng.integers(n_step[0], n_step[1])) + + # Skip, if we are too far to the end and `episode_ts` + n_step would go + # beyond the episode's end. + if episode_ts + actual_n_step > len(episode): + num_resamples += 1 + continue + + # Note, this will be the reward after executing action + # `a_(episode_ts-n_step+1)`. For `n_step>1` this will be the discounted + # sum of all discounted rewards that were collected over the last n steps. + raw_rewards = episode.get_rewards( + slice(episode_ts, episode_ts + actual_n_step) + ) + rewards = scipy.signal.lfilter([1], [1, -gamma], raw_rewards[::-1], axis=0)[ + -1 + ] + + # Generate the episode to be returned. + sampled_episode = SingleAgentEpisode( + # Ensure that each episode contains a tuple of the form: + # (o_t, a_t, sum(r_(t:t+n_step)), o_(t+n_step)) + # Two observations (t and t+n). + observations=[ + episode.get_observations(episode_ts), + episode.get_observations(episode_ts + actual_n_step), + ], + observation_space=episode.observation_space, + infos=( + [ + episode.get_infos(episode_ts), + episode.get_infos(episode_ts + actual_n_step), + ] + if include_infos + else None + ), + actions=[episode.get_actions(episode_ts)], + action_space=episode.action_space, + rewards=[rewards], + # If the sampled time step is the episode's last time step check, if + # the episode is terminated or truncated. + terminated=( + False + if episode_ts + actual_n_step < len(episode) + else episode.is_terminated + ), + truncated=( + False + if episode_ts + actual_n_step < len(episode) + else episode.is_truncated + ), + extra_model_outputs={ + # TODO (simon): Check, if we have to correct here for sequences + # later. + "weights": [weight / max_weight * 1], # actual_size=1 + "n_step": [actual_n_step], + **( + { + k: [episode.get_extra_model_outputs(k, episode_ts)] + for k in episode.extra_model_outputs.keys() + } + if include_extra_model_outputs + else {} + ), + }, + # TODO (sven): Support lookback buffers. + len_lookback_buffer=0, + t_started=episode_ts, + ) + # Record here the episode time step via a hash code. + sampled_env_step_idxs.add( + hashlib.sha256(f"{episode.id_}-{episode_ts}".encode()).hexdigest() + ) + # Convert to numpy arrays, if required. + if to_numpy: + sampled_episode.to_numpy() + sampled_episodes.append(sampled_episode) + + # Add the episode buffer index to the sampled indices. + sampled_episode_idxs.add(episode_idx) + # Record the actual n-step for this sample. + sampled_n_steps.append(actual_n_step) + + # Increment counter. + B += 1 + + # Keep track of sampled indices for updating priorities later. + self._last_sampled_indices.append(idx) + + # Add to the sampled timesteps counter of the buffer. + self.sampled_timesteps += batch_size_B + + # Update the sample metrics. + num_env_steps_sampled = batch_size_B + num_episodes_per_sample = len(sampled_episode_idxs) + num_env_steps_per_sample = len(sampled_env_step_idxs) + sampled_n_step = sum(sampled_n_steps) / batch_size_B + agent_to_num_steps_sampled = {DEFAULT_AGENT_ID: num_env_steps_sampled} + agent_to_num_episodes_per_sample = {DEFAULT_AGENT_ID: num_episodes_per_sample} + agent_to_num_steps_per_sample = {DEFAULT_AGENT_ID: num_env_steps_per_sample} + agent_to_sampled_n_step = {DEFAULT_AGENT_ID: sampled_n_step} + agent_to_num_resamples = {DEFAULT_AGENT_ID: num_resamples} + module_to_num_steps_sampled = {DEFAULT_MODULE_ID: num_env_steps_sampled} + module_to_num_episodes_per_sample = {DEFAULT_MODULE_ID: num_episodes_per_sample} + module_to_num_steps_per_sample = {DEFAULT_MODULE_ID: num_env_steps_per_sample} + module_to_sampled_n_step = {DEFAULT_MODULE_ID: sampled_n_step} + module_to_num_resamples = {DEFAULT_MODULE_ID: num_resamples} + self._update_sample_metrics( + num_env_steps_sampled=num_env_steps_sampled, + num_episodes_per_sample=num_episodes_per_sample, + num_env_steps_per_sample=num_env_steps_per_sample, + sampled_n_step=sampled_n_step, + num_resamples=num_resamples, + agent_to_num_steps_sampled=agent_to_num_steps_sampled, + agent_to_num_episodes_per_sample=agent_to_num_episodes_per_sample, + agent_to_num_steps_per_sample=agent_to_num_steps_per_sample, + agent_to_sampled_n_step=agent_to_sampled_n_step, + agent_to_num_resamples=agent_to_num_resamples, + module_to_num_steps_sampled=module_to_num_steps_sampled, + module_to_num_episodes_per_sample=module_to_num_episodes_per_sample, + module_to_num_steps_per_sample=module_to_num_steps_per_sample, + module_to_sampled_n_step=module_to_sampled_n_step, + module_to_num_resamples=module_to_num_resamples, + ) + + return sampled_episodes + + @override(EpisodeReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Gets the state of a `PrioritizedEpisodeReplayBuffer`. + + Returns: + A state dict that can be stored in a checkpoint. + """ + # Get super's state. + state = super().get_state() + # Add additional attributes. + state.update( + { + "_sum_segment": self._sum_segment.get_state(), + "_min_segment": self._min_segment.get_state(), + "_free_nodes": list(self._free_nodes), + "_max_priority": self._max_priority, + "_max_idx": self._max_idx, + "_tree_idx_to_sample_idx": list(self._tree_idx_to_sample_idx.items()), + # TODO (sven, simon): Do we need these? + "_last_sampled_indices": self._last_sampled_indices, + } + ) + return state + + @override(EpisodeReplayBuffer) + def set_state(self, state) -> None: + """Sets the state of a `PrioritizedEpisodeReplayBuffer`. + + Args: + state: A buffer state stored (usually stored in a checkpoint). + """ + # Set super's state. + super().set_state(state) + # Set additional attributes. + self._sum_segment.set_state(state["_sum_segment"]) + self._min_segment.set_state(state["_min_segment"]) + self._free_nodes = deque(state["_free_nodes"]) + self._max_priority = state["_max_priority"] + self._max_idx = state["_max_idx"] + self._tree_idx_to_sample_idx = dict(state["_tree_idx_to_sample_idx"]) + # TODO (sven, simon): Do we need these? + self._last_sampled_indices = state["_last_sampled_indices"] + + def update_priorities( + self, priorities: NDArray, module_id: Optional[ModuleID] = None + ) -> None: + """Update the priorities of items at corresponding indices. + + Usually, incoming priorities are TD-errors. + + Args: + priorities: Numpy array containing the new priorities to be used + in sampling for the items in the last sampled batch. + """ + assert len(priorities) == len(self._last_sampled_indices) + + for idx, priority in zip(self._last_sampled_indices, priorities): + # Note, TD-errors come in as absolute values or results from + # cross-entropy loss calculations. + # assert priority > 0, f"priority was {priority}" + priority = max(priority, 1e-12) + assert 0 <= idx < self._sum_segment.capacity + # TODO (simon): Create metrics. + # delta = priority**self._alpha - self._sum_segment[idx] + # Update the priorities in the segment trees. + self._sum_segment[idx] = priority**self._alpha + self._min_segment[idx] = priority**self._alpha + # Update the maximal priority. + self._max_priority = max(self._max_priority, priority) + self._last_sampled_indices.clear() + + def _get_free_node_and_assign(self, sample_index, weight: float = 1.0) -> int: + """Gets the next free node in the segment trees. + + In addition the initial priorities for a new transition are added + to the segment trees and the index of the nodes is added to the + index mapping. + + Args: + sample_index: The index of the sample in the `self._indices` list. + weight: The initial priority weight to be used in sampling for + the item at index `sample_index`. + + Returns: + The index in the segment trees `self._sum_segment` and + `self._min_segment` for the item at index `sample_index` in + ``self._indices`. + """ + # Get an index from the free nodes in the segment trees. + idx = self._free_nodes.popleft() + self._max_idx = idx if idx > self._max_idx else self._max_idx + # Add the weight to the segments. + self._sum_segment[idx] = weight**self._alpha + self._min_segment[idx] = weight**self._alpha + # Map the index in the trees to the index in `self._indices`. + self._tree_idx_to_sample_idx[idx] = sample_index + # Return the index. + return idx + + def _num_remaining_episodes(self, new_eps, evicted_eps): + """Calculates the number of remaining episodes. + + When adding episodes and evicting them in the `add()` method + this function calculates iteratively the number of remaining + episodes. + + Args: + new_eps: List of new episode IDs. + evicted_eps: List of evicted episode IDs. + + Returns: + Number of episodes remaining after evicting the episodes in + `evicted_eps` and adding the episode in `new_eps`. + """ + return len( + set(self.episode_id_to_index.keys()).union(set(new_eps)) - set(evicted_eps) + ) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/prioritized_replay_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/prioritized_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..00db60b7adfaad1867a445ee376b7a6f0f815f2a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/prioritized_replay_buffer.py @@ -0,0 +1,240 @@ +import random +from typing import Any, Dict, List, Optional +import numpy as np + +# Import ray before psutil will make sure we use psutil's bundled version +import ray # noqa F401 +import psutil # noqa E402 + +from ray.rllib.execution.segment_tree import SumSegmentTree, MinSegmentTree +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.metrics.window_stat import WindowStat +from ray.rllib.utils.replay_buffers.replay_buffer import ReplayBuffer +from ray.rllib.utils.typing import SampleBatchType +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class PrioritizedReplayBuffer(ReplayBuffer): + """This buffer implements Prioritized Experience Replay. + + The algorithm has been described by Tom Schaul et. al. in "Prioritized + Experience Replay". See https://arxiv.org/pdf/1511.05952.pdf for + the full paper. + """ + + def __init__( + self, + capacity: int = 10000, + storage_unit: str = "timesteps", + alpha: float = 1.0, + **kwargs, + ): + """Initializes a PrioritizedReplayBuffer instance. + + Args: + capacity: Max number of timesteps to store in the FIFO + buffer. After reaching this number, older samples will be + dropped to make space for new ones. + storage_unit: Either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. + alpha: How much prioritization is used + (0.0=no prioritization, 1.0=full prioritization). + ``**kwargs``: Forward compatibility kwargs. + """ + ReplayBuffer.__init__(self, capacity, storage_unit, **kwargs) + + assert alpha > 0 + self._alpha = alpha + + # Segment tree must have capacity that is a power of 2 + it_capacity = 1 + while it_capacity < self.capacity: + it_capacity *= 2 + + self._it_sum = SumSegmentTree(it_capacity) + self._it_min = MinSegmentTree(it_capacity) + self._max_priority = 1.0 + self._prio_change_stats = WindowStat("reprio", 1000) + + @DeveloperAPI + @override(ReplayBuffer) + def _add_single_batch(self, item: SampleBatchType, **kwargs) -> None: + """Add a batch of experiences to self._storage with weight. + + An item consists of either one or more timesteps, a sequence or an + episode. Differs from add() in that it does not consider the storage + unit or type of batch and simply stores it. + + Args: + item: The item to be added. + ``**kwargs``: Forward compatibility kwargs. + """ + weight = kwargs.get("weight", None) + + if weight is None: + weight = self._max_priority + + self._it_sum[self._next_idx] = weight**self._alpha + self._it_min[self._next_idx] = weight**self._alpha + + ReplayBuffer._add_single_batch(self, item) + + def _sample_proportional(self, num_items: int) -> List[int]: + res = [] + for _ in range(num_items): + # TODO(szymon): should we ensure no repeats? + mass = random.random() * self._it_sum.sum(0, len(self._storage)) + idx = self._it_sum.find_prefixsum_idx(mass) + res.append(idx) + return res + + @DeveloperAPI + @override(ReplayBuffer) + def sample( + self, num_items: int, beta: float, **kwargs + ) -> Optional[SampleBatchType]: + """Sample `num_items` items from this buffer, including prio. weights. + + Samples in the results may be repeated. + + Examples for storage of SamplesBatches: + - If storage unit `timesteps` has been chosen and batches of + size 5 have been added, sample(5) will yield a concatenated batch of + 15 timesteps. + - If storage unit 'sequences' has been chosen and sequences of + different lengths have been added, sample(5) will yield a concatenated + batch with a number of timesteps equal to the sum of timesteps in + the 5 sampled sequences. + - If storage unit 'episodes' has been chosen and episodes of + different lengths have been added, sample(5) will yield a concatenated + batch with a number of timesteps equal to the sum of timesteps in + the 5 sampled episodes. + + Args: + num_items: Number of items to sample from this buffer. + beta: To what degree to use importance weights (0 - no corrections, + 1 - full correction). + ``**kwargs``: Forward compatibility kwargs. + + Returns: + Concatenated SampleBatch of items including "weights" and + "batch_indexes" fields denoting IS of each sampled + transition and original idxes in buffer of sampled experiences. + """ + assert beta >= 0.0 + + if len(self) == 0: + raise ValueError("Trying to sample from an empty buffer.") + + idxes = self._sample_proportional(num_items) + + weights = [] + batch_indexes = [] + p_min = self._it_min.min() / self._it_sum.sum() + max_weight = (p_min * len(self)) ** (-beta) + + for idx in idxes: + p_sample = self._it_sum[idx] / self._it_sum.sum() + weight = (p_sample * len(self)) ** (-beta) + count = self._storage[idx].count + # If zero-padded, count will not be the actual batch size of the + # data. + if ( + isinstance(self._storage[idx], SampleBatch) + and self._storage[idx].zero_padded + ): + actual_size = self._storage[idx].max_seq_len + else: + actual_size = count + weights.extend([weight / max_weight] * actual_size) + batch_indexes.extend([idx] * actual_size) + self._num_timesteps_sampled += count + batch = self._encode_sample(idxes) + + # Note: prioritization is not supported in multi agent lockstep + if isinstance(batch, SampleBatch): + batch["weights"] = np.array(weights) + batch["batch_indexes"] = np.array(batch_indexes) + + return batch + + @DeveloperAPI + def update_priorities(self, idxes: List[int], priorities: List[float]) -> None: + """Update priorities of items at given indices. + + Sets priority of item at index idxes[i] in buffer + to priorities[i]. + + Args: + idxes: List of indices of items + priorities: List of updated priorities corresponding to items at the + idxes denoted by variable `idxes`. + """ + # Making sure we don't pass in e.g. a torch tensor. + assert isinstance( + idxes, (list, np.ndarray) + ), "ERROR: `idxes` is not a list or np.ndarray, but {}!".format( + type(idxes).__name__ + ) + assert len(idxes) == len(priorities) + for idx, priority in zip(idxes, priorities): + assert priority > 0 + assert 0 <= idx < len(self._storage) + delta = priority**self._alpha - self._it_sum[idx] + self._prio_change_stats.push(delta) + self._it_sum[idx] = priority**self._alpha + self._it_min[idx] = priority**self._alpha + + self._max_priority = max(self._max_priority, priority) + + @DeveloperAPI + @override(ReplayBuffer) + def stats(self, debug: bool = False) -> Dict: + """Returns the stats of this buffer. + + Args: + debug: If true, adds sample eviction statistics to the returned stats dict. + + Returns: + A dictionary of stats about this buffer. + """ + parent = ReplayBuffer.stats(self, debug) + if debug: + parent.update(self._prio_change_stats.stats()) + return parent + + @DeveloperAPI + @override(ReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Returns all local state. + + Returns: + The serializable local state. + """ + # Get parent state. + state = super().get_state() + # Add prio weights. + state.update( + { + "sum_segment_tree": self._it_sum.get_state(), + "min_segment_tree": self._it_min.get_state(), + "max_priority": self._max_priority, + } + ) + return state + + @DeveloperAPI + @override(ReplayBuffer) + def set_state(self, state: Dict[str, Any]) -> None: + """Restores all local state to the provided `state`. + + Args: + state: The new state to set this buffer. Can be obtained by calling + `self.get_state()`. + """ + super().set_state(state) + self._it_sum.set_state(state["sum_segment_tree"]) + self._it_min.set_state(state["min_segment_tree"]) + self._max_priority = state["max_priority"] diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/replay_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd2c2c378ab6d93ed66d45c62c72a8317e3cbb8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/replay_buffer.py @@ -0,0 +1,374 @@ +from enum import Enum +import logging +import numpy as np +import random +from typing import Any, Dict, List, Optional, Union + +# Import ray before psutil will make sure we use psutil's bundled version +import ray # noqa F401 +import psutil + +from ray.rllib.policy.sample_batch import SampleBatch, concat_samples +from ray.rllib.utils.actor_manager import FaultAwareApply +from ray.rllib.utils.annotations import override +from ray.rllib.utils.metrics.window_stat import WindowStat +from ray.rllib.utils.replay_buffers.base import ReplayBufferInterface +from ray.rllib.utils.typing import SampleBatchType +from ray.util.annotations import DeveloperAPI +from ray.util.debug import log_once + +# Constant that represents all policies in lockstep replay mode. +_ALL_POLICIES = "__all__" + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class StorageUnit(Enum): + """Specifies how batches are structured in a ReplayBuffer. + + timesteps: One buffer slot per timestep. + sequences: One buffer slot per sequence. + episodes: One buffer slot per episode. + fragemts: One buffer slot per incoming batch. + """ + + TIMESTEPS = "timesteps" + SEQUENCES = "sequences" + EPISODES = "episodes" + FRAGMENTS = "fragments" + + +@DeveloperAPI +def warn_replay_capacity(*, item: SampleBatchType, num_items: int) -> None: + """Warn if the configured replay buffer capacity is too large.""" + if log_once("replay_capacity"): + item_size = item.size_bytes() + psutil_mem = psutil.virtual_memory() + total_gb = psutil_mem.total / 1e9 + mem_size = num_items * item_size / 1e9 + msg = ( + "Estimated max memory usage for replay buffer is {} GB " + "({} batches of size {}, {} bytes each), " + "available system memory is {} GB".format( + mem_size, num_items, item.count, item_size, total_gb + ) + ) + if mem_size > total_gb: + raise ValueError(msg) + elif mem_size > 0.2 * total_gb: + logger.warning(msg) + else: + logger.info(msg) + + +@DeveloperAPI +class ReplayBuffer(ReplayBufferInterface, FaultAwareApply): + """The lowest-level replay buffer interface used by RLlib. + + This class implements a basic ring-type of buffer with random sampling. + ReplayBuffer is the base class for advanced types that add functionality while + retaining compatibility through inheritance. + + The following examples show how buffers behave with different storage_units + and capacities. This behaviour is generally similar for other buffers, although + they might not implement all storage_units. + + Examples: + + .. testcode:: + + from ray.rllib.utils.replay_buffers.replay_buffer import ReplayBuffer + from ray.rllib.utils.replay_buffers.replay_buffer import StorageUnit + from ray.rllib.policy.sample_batch import SampleBatch + + # Store any batch as a whole + buffer = ReplayBuffer(capacity=10, storage_unit=StorageUnit.FRAGMENTS) + buffer.add(SampleBatch({"a": [1], "b": [2, 3, 4]})) + buffer.sample(1) + + # Store only complete episodes + buffer = ReplayBuffer(capacity=10, + storage_unit=StorageUnit.EPISODES) + buffer.add(SampleBatch({"c": [1, 2, 3, 4], + SampleBatch.T: [0, 1, 0, 1], + SampleBatch.TERMINATEDS: [False, True, False, True], + SampleBatch.EPS_ID: [0, 0, 1, 1]})) + buffer.sample(1) + + # Store single timesteps + buffer = ReplayBuffer(capacity=2, storage_unit=StorageUnit.TIMESTEPS) + buffer.add(SampleBatch({"a": [1, 2], SampleBatch.T: [0, 1]})) + buffer.sample(1) + + buffer.add(SampleBatch({"a": [3], SampleBatch.T: [2]})) + print(buffer._eviction_started) + buffer.sample(1) + + buffer = ReplayBuffer(capacity=10, storage_unit=StorageUnit.SEQUENCES) + buffer.add(SampleBatch({"c": [1, 2, 3], SampleBatch.SEQ_LENS: [1, 2]})) + buffer.sample(1) + + .. testoutput:: + + True + + `True` is not the output of the above testcode, but an artifact of unexpected + behaviour of sphinx doctests. + (see https://github.com/ray-project/ray/pull/32477#discussion_r1106776101) + """ + + def __init__( + self, + capacity: int = 10000, + storage_unit: Union[str, StorageUnit] = "timesteps", + **kwargs, + ): + """Initializes a (FIFO) ReplayBuffer instance. + + Args: + capacity: Max number of timesteps to store in this FIFO + buffer. After reaching this number, older samples will be + dropped to make space for new ones. + storage_unit: If not a StorageUnit, either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. + ``**kwargs``: Forward compatibility kwargs. + """ + + if storage_unit in ["timesteps", StorageUnit.TIMESTEPS]: + self.storage_unit = StorageUnit.TIMESTEPS + elif storage_unit in ["sequences", StorageUnit.SEQUENCES]: + self.storage_unit = StorageUnit.SEQUENCES + elif storage_unit in ["episodes", StorageUnit.EPISODES]: + self.storage_unit = StorageUnit.EPISODES + elif storage_unit in ["fragments", StorageUnit.FRAGMENTS]: + self.storage_unit = StorageUnit.FRAGMENTS + else: + raise ValueError( + f"storage_unit must be either '{StorageUnit.TIMESTEPS}', " + f"'{StorageUnit.SEQUENCES}', '{StorageUnit.EPISODES}' " + f"or '{StorageUnit.FRAGMENTS}', but is {storage_unit}" + ) + + # The actual storage (list of SampleBatches or MultiAgentBatches). + self._storage = [] + + # Caps the number of timesteps stored in this buffer + if capacity <= 0: + raise ValueError( + "Capacity of replay buffer has to be greater than zero " + "but was set to {}.".format(capacity) + ) + self.capacity = capacity + # The next index to override in the buffer. + self._next_idx = 0 + # len(self._hit_count) must always be less than len(capacity) + self._hit_count = np.zeros(self.capacity) + + # Whether we have already hit our capacity (and have therefore + # started to evict older samples). + self._eviction_started = False + + # Number of (single) timesteps that have been added to the buffer + # over its lifetime. Note that each added item (batch) may contain + # more than one timestep. + self._num_timesteps_added = 0 + self._num_timesteps_added_wrap = 0 + + # Number of (single) timesteps that have been sampled from the buffer + # over its lifetime. + self._num_timesteps_sampled = 0 + + self._evicted_hit_stats = WindowStat("evicted_hit", 1000) + self._est_size_bytes = 0 + + self.batch_size = None + + @override(ReplayBufferInterface) + def __len__(self) -> int: + return len(self._storage) + + @override(ReplayBufferInterface) + def add(self, batch: SampleBatchType, **kwargs) -> None: + """Adds a batch of experiences or other data to this buffer. + + Splits batch into chunks of timesteps, sequences or episodes, depending on + `self._storage_unit`. Calls `self._add_single_batch` to add resulting slices + to the buffer storage. + + Args: + batch: The batch to add. + ``**kwargs``: Forward compatibility kwargs. + """ + if not batch.count > 0: + return + + warn_replay_capacity(item=batch, num_items=self.capacity / batch.count) + + if self.storage_unit == StorageUnit.TIMESTEPS: + timeslices = batch.timeslices(1) + for t in timeslices: + self._add_single_batch(t, **kwargs) + + elif self.storage_unit == StorageUnit.SEQUENCES: + timestep_count = 0 + for seq_len in batch.get(SampleBatch.SEQ_LENS): + start_seq = timestep_count + end_seq = timestep_count + seq_len + self._add_single_batch(batch[start_seq:end_seq], **kwargs) + timestep_count = end_seq + + elif self.storage_unit == StorageUnit.EPISODES: + for eps in batch.split_by_episode(): + if eps.get(SampleBatch.T, [0])[0] == 0 and ( + eps.get(SampleBatch.TERMINATEDS, [True])[-1] + or eps.get(SampleBatch.TRUNCATEDS, [False])[-1] + ): + # Only add full episodes to the buffer + # Check only if info is available + self._add_single_batch(eps, **kwargs) + else: + if log_once("only_full_episodes"): + logger.info( + "This buffer uses episodes as a storage " + "unit and thus allows only full episodes " + "to be added to it (starting from T=0 and ending in " + "`terminateds=True` or `truncateds=True`. " + "Some samples may be dropped." + ) + + elif self.storage_unit == StorageUnit.FRAGMENTS: + self._add_single_batch(batch, **kwargs) + + @DeveloperAPI + def _add_single_batch(self, item: SampleBatchType, **kwargs) -> None: + """Add a SampleBatch of experiences to self._storage. + + An item consists of either one or more timesteps, a sequence or an + episode. Differs from add() in that it does not consider the storage + unit or type of batch and simply stores it. + + Args: + item: The batch to be added. + ``**kwargs``: Forward compatibility kwargs. + """ + self._num_timesteps_added += item.count + self._num_timesteps_added_wrap += item.count + + if self._next_idx >= len(self._storage): + self._storage.append(item) + self._est_size_bytes += item.size_bytes() + else: + item_to_be_removed = self._storage[self._next_idx] + self._est_size_bytes -= item_to_be_removed.size_bytes() + self._storage[self._next_idx] = item + self._est_size_bytes += item.size_bytes() + + # Eviction of older samples has already started (buffer is "full"). + if self._eviction_started: + self._evicted_hit_stats.push(self._hit_count[self._next_idx]) + self._hit_count[self._next_idx] = 0 + + # Wrap around storage as a circular buffer once we hit capacity. + if self._num_timesteps_added_wrap >= self.capacity: + self._eviction_started = True + self._num_timesteps_added_wrap = 0 + self._next_idx = 0 + else: + self._next_idx += 1 + + @override(ReplayBufferInterface) + def sample( + self, num_items: Optional[int] = None, **kwargs + ) -> Optional[SampleBatchType]: + """Samples `num_items` items from this buffer. + + The items depend on the buffer's storage_unit. + Samples in the results may be repeated. + + Examples for sampling results: + + 1) If storage unit 'timesteps' has been chosen and batches of + size 5 have been added, sample(5) will yield a concatenated batch of + 15 timesteps. + + 2) If storage unit 'sequences' has been chosen and sequences of + different lengths have been added, sample(5) will yield a concatenated + batch with a number of timesteps equal to the sum of timesteps in + the 5 sampled sequences. + + 3) If storage unit 'episodes' has been chosen and episodes of + different lengths have been added, sample(5) will yield a concatenated + batch with a number of timesteps equal to the sum of timesteps in + the 5 sampled episodes. + + Args: + num_items: Number of items to sample from this buffer. + ``**kwargs``: Forward compatibility kwargs. + + Returns: + Concatenated batch of items. + """ + if len(self) == 0: + raise ValueError("Trying to sample from an empty buffer.") + idxes = [random.randint(0, len(self) - 1) for _ in range(num_items)] + sample = self._encode_sample(idxes) + self._num_timesteps_sampled += sample.count + return sample + + @DeveloperAPI + def stats(self, debug: bool = False) -> dict: + """Returns the stats of this buffer. + + Args: + debug: If True, adds sample eviction statistics to the returned + stats dict. + + Returns: + A dictionary of stats about this buffer. + """ + data = { + "added_count": self._num_timesteps_added, + "added_count_wrapped": self._num_timesteps_added_wrap, + "eviction_started": self._eviction_started, + "sampled_count": self._num_timesteps_sampled, + "est_size_bytes": self._est_size_bytes, + "num_entries": len(self._storage), + } + if debug: + data.update(self._evicted_hit_stats.stats()) + return data + + @override(ReplayBufferInterface) + def get_state(self) -> Dict[str, Any]: + state = {"_storage": self._storage, "_next_idx": self._next_idx} + state.update(self.stats(debug=False)) + return state + + @override(ReplayBufferInterface) + def set_state(self, state: Dict[str, Any]) -> None: + # The actual storage. + self._storage = state["_storage"] + self._next_idx = state["_next_idx"] + # Stats and counts. + self._num_timesteps_added = state["added_count"] + self._num_timesteps_added_wrap = state["added_count_wrapped"] + self._eviction_started = state["eviction_started"] + self._num_timesteps_sampled = state["sampled_count"] + self._est_size_bytes = state["est_size_bytes"] + + @DeveloperAPI + def _encode_sample(self, idxes: List[int]) -> SampleBatchType: + """Fetches concatenated samples at given indices from the storage.""" + samples = [] + for i in idxes: + self._hit_count[i] += 1 + samples.append(self._storage[i]) + + if samples: + # We assume all samples are of same type + out = concat_samples(samples) + else: + out = SampleBatch() + out.decompress_if_needed() + return out diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/reservoir_replay_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/reservoir_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..6cf098b1567ac23ea71b371a59867206159605a8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/reservoir_replay_buffer.py @@ -0,0 +1,132 @@ +from typing import Any, Dict +import random + +# Import ray before psutil will make sure we use psutil's bundled version +import ray # noqa F401 +import psutil # noqa E402 + +from ray.rllib.utils.annotations import ExperimentalAPI, override +from ray.rllib.utils.replay_buffers.replay_buffer import ( + ReplayBuffer, + warn_replay_capacity, +) +from ray.rllib.utils.typing import SampleBatchType + + +# __sphinx_doc_reservoir_buffer__begin__ +@ExperimentalAPI +class ReservoirReplayBuffer(ReplayBuffer): + """This buffer implements reservoir sampling. + + The algorithm has been described by Jeffrey S. Vitter in "Random sampling + with a reservoir". + """ + + def __init__( + self, capacity: int = 10000, storage_unit: str = "timesteps", **kwargs + ): + """Initializes a ReservoirBuffer instance. + + Args: + capacity: Max number of timesteps to store in the FIFO + buffer. After reaching this number, older samples will be + dropped to make space for new ones. + storage_unit: Either 'timesteps', 'sequences' or + 'episodes'. Specifies how experiences are stored. + """ + ReplayBuffer.__init__(self, capacity, storage_unit) + self._num_add_calls = 0 + self._num_evicted = 0 + + @ExperimentalAPI + @override(ReplayBuffer) + def _add_single_batch(self, item: SampleBatchType, **kwargs) -> None: + """Add a SampleBatch of experiences to self._storage. + + An item consists of either one or more timesteps, a sequence or an + episode. Differs from add() in that it does not consider the storage + unit or type of batch and simply stores it. + + Args: + item: The batch to be added. + ``**kwargs``: Forward compatibility kwargs. + """ + self._num_timesteps_added += item.count + self._num_timesteps_added_wrap += item.count + + # Update add counts. + self._num_add_calls += 1 + # Update our timesteps counts. + + if self._num_timesteps_added < self.capacity: + self._storage.append(item) + self._est_size_bytes += item.size_bytes() + else: + # Eviction of older samples has already started (buffer is "full") + self._eviction_started = True + idx = random.randint(0, self._num_add_calls - 1) + if idx < len(self._storage): + self._num_evicted += 1 + self._evicted_hit_stats.push(self._hit_count[idx]) + self._hit_count[idx] = 0 + # This is a bit of a hack: ReplayBuffer always inserts at + # self._next_idx + self._next_idx = idx + self._evicted_hit_stats.push(self._hit_count[idx]) + self._hit_count[idx] = 0 + + item_to_be_removed = self._storage[idx] + self._est_size_bytes -= item_to_be_removed.size_bytes() + self._storage[idx] = item + self._est_size_bytes += item.size_bytes() + + assert item.count > 0, item + warn_replay_capacity(item=item, num_items=self.capacity / item.count) + + @ExperimentalAPI + @override(ReplayBuffer) + def stats(self, debug: bool = False) -> dict: + """Returns the stats of this buffer. + + Args: + debug: If True, adds sample eviction statistics to the returned + stats dict. + + Returns: + A dictionary of stats about this buffer. + """ + data = { + "num_evicted": self._num_evicted, + "num_add_calls": self._num_add_calls, + } + parent = ReplayBuffer.stats(self, debug) + parent.update(data) + return parent + + @ExperimentalAPI + @override(ReplayBuffer) + def get_state(self) -> Dict[str, Any]: + """Returns all local state. + + Returns: + The serializable local state. + """ + parent = ReplayBuffer.get_state(self) + parent.update(self.stats()) + return parent + + @ExperimentalAPI + @override(ReplayBuffer) + def set_state(self, state: Dict[str, Any]) -> None: + """Restores all local state to the provided `state`. + + Args: + state: The new state to set this buffer. Can be + obtained by calling `self.get_state()`. + """ + self._num_evicted = state["num_evicted"] + self._num_add_calls = state["num_add_calls"] + ReplayBuffer.set_state(self, state) + + +# __sphinx_doc_reservoir_buffer__end__ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/simple_replay_buffer.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/simple_replay_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/utils.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..16fa37d0626ff1cad5b617e8f17e5d4f0c5a5079 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/replay_buffers/utils.py @@ -0,0 +1,440 @@ +import logging +import psutil +from typing import Any, Dict, Optional + +import numpy as np + +from ray.rllib.utils import deprecation_warning +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.deprecation import DEPRECATED_VALUE +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.metrics import ALL_MODULES, TD_ERROR_KEY +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.replay_buffers import ( + EpisodeReplayBuffer, + MultiAgentPrioritizedReplayBuffer, + PrioritizedEpisodeReplayBuffer, + ReplayBuffer, + MultiAgentReplayBuffer, +) +from ray.rllib.policy.sample_batch import concat_samples, MultiAgentBatch, SampleBatch +from ray.rllib.utils.typing import ( + AlgorithmConfigDict, + ModuleID, + ResultDict, + SampleBatchType, + TensorType, +) +from ray.util import log_once +from ray.util.annotations import DeveloperAPI + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +def update_priorities_in_episode_replay_buffer( + *, + replay_buffer: EpisodeReplayBuffer, + td_errors: Dict[ModuleID, TensorType], +) -> None: + # Only update priorities, if the buffer supports them. + if isinstance(replay_buffer, PrioritizedEpisodeReplayBuffer): + + # The `ResultDict` will be multi-agent. + for module_id, td_error in td_errors.items(): + # Skip the `"__all__"` keys. + if module_id in ["__all__", ALL_MODULES]: + continue + + # Warn once, if we have no TD-errors to update priorities. + if TD_ERROR_KEY not in td_error or td_error[TD_ERROR_KEY] is None: + if log_once( + "no_td_error_in_train_results_from_module_{}".format(module_id) + ): + logger.warning( + "Trying to update priorities for module with ID " + f"`{module_id}` in prioritized episode replay buffer without " + "providing `td_errors` in train_results. Priority update for " + "this policy is being skipped." + ) + continue + # TODO (simon): Implement multi-agent version. Remove, happens in buffer. + # assert len(td_error[TD_ERROR_KEY]) == len( + # replay_buffer._last_sampled_indices + # ) + # TODO (simon): Implement for stateful modules. + + replay_buffer.update_priorities(td_error[TD_ERROR_KEY], module_id) + + +@OldAPIStack +def update_priorities_in_replay_buffer( + replay_buffer: ReplayBuffer, + config: AlgorithmConfigDict, + train_batch: SampleBatchType, + train_results: ResultDict, +) -> None: + """Updates the priorities in a prioritized replay buffer, given training results. + + The `abs(TD-error)` from the loss (inside `train_results`) is used as new + priorities for the row-indices that were sampled for the train batch. + + Don't do anything if the given buffer does not support prioritized replay. + + Args: + replay_buffer: The replay buffer, whose priority values to update. This may also + be a buffer that does not support priorities. + config: The Algorithm's config dict. + train_batch: The batch used for the training update. + train_results: A train results dict, generated by e.g. the `train_one_step()` + utility. + """ + # Only update priorities if buffer supports them. + if isinstance(replay_buffer, MultiAgentPrioritizedReplayBuffer): + # Go through training results for the different policies (maybe multi-agent). + prio_dict = {} + for policy_id, info in train_results.items(): + # TODO(sven): This is currently structured differently for + # torch/tf. Clean up these results/info dicts across + # policies (note: fixing this in torch_policy.py will + # break e.g. DDPPO!). + td_error = info.get("td_error", info[LEARNER_STATS_KEY].get("td_error")) + + policy_batch = train_batch.policy_batches[policy_id] + # Set the get_interceptor to None in order to be able to access the numpy + # arrays directly (instead of e.g. a torch array). + policy_batch.set_get_interceptor(None) + # Get the replay buffer row indices that make up the `train_batch`. + batch_indices = policy_batch.get("batch_indexes") + + if SampleBatch.SEQ_LENS in policy_batch: + # Batch_indices are represented per column, in order to update + # priorities, we need one index per td_error + _batch_indices = [] + + # Sequenced batches have been zero padded to max_seq_len. + # Depending on how batches are split during learning, not all + # sequences have an associated td_error (trailing ones missing). + if policy_batch.zero_padded: + seq_lens = len(td_error) * [policy_batch.max_seq_len] + else: + seq_lens = policy_batch[SampleBatch.SEQ_LENS][: len(td_error)] + + # Go through all indices by sequence that they represent and shrink + # them to one index per sequences + sequence_sum = 0 + for seq_len in seq_lens: + _batch_indices.append(batch_indices[sequence_sum]) + sequence_sum += seq_len + batch_indices = np.array(_batch_indices) + + if td_error is None: + if log_once( + "no_td_error_in_train_results_from_policy_{}".format(policy_id) + ): + logger.warning( + "Trying to update priorities for policy with id `{}` in " + "prioritized replay buffer without providing td_errors in " + "train_results. Priority update for this policy is being " + "skipped.".format(policy_id) + ) + continue + + if batch_indices is None: + if log_once( + "no_batch_indices_in_train_result_for_policy_{}".format(policy_id) + ): + logger.warning( + "Trying to update priorities for policy with id `{}` in " + "prioritized replay buffer without providing batch_indices in " + "train_batch. Priority update for this policy is being " + "skipped.".format(policy_id) + ) + continue + + # Try to transform batch_indices to td_error dimensions + if len(batch_indices) != len(td_error): + T = replay_buffer.replay_sequence_length + assert ( + len(batch_indices) > len(td_error) and len(batch_indices) % T == 0 + ) + batch_indices = batch_indices.reshape([-1, T])[:, 0] + assert len(batch_indices) == len(td_error) + prio_dict[policy_id] = (batch_indices, td_error) + + # Make the actual buffer API call to update the priority weights on all + # policies. + replay_buffer.update_priorities(prio_dict) + + +@DeveloperAPI +def sample_min_n_steps_from_buffer( + replay_buffer: ReplayBuffer, min_steps: int, count_by_agent_steps: bool +) -> Optional[SampleBatchType]: + """Samples a minimum of n timesteps from a given replay buffer. + + This utility method is primarily used by the QMIX algorithm and helps with + sampling a given number of time steps which has stored samples in units + of sequences or complete episodes. Samples n batches from replay buffer + until the total number of timesteps reaches `train_batch_size`. + + Args: + replay_buffer: The replay buffer to sample from + num_timesteps: The number of timesteps to sample + count_by_agent_steps: Whether to count agent steps or env steps + + Returns: + A concatenated SampleBatch or MultiAgentBatch with samples from the + buffer. + """ + train_batch_size = 0 + train_batches = [] + while train_batch_size < min_steps: + batch = replay_buffer.sample(num_items=1) + batch_len = batch.agent_steps() if count_by_agent_steps else batch.env_steps() + if batch_len == 0: + # Replay has not started, so we can't accumulate timesteps here + return batch + train_batches.append(batch) + train_batch_size += batch_len + # All batch types are the same type, hence we can use any concat_samples() + train_batch = concat_samples(train_batches) + return train_batch + + +@DeveloperAPI +def validate_buffer_config(config: dict) -> None: + """Checks and fixes values in the replay buffer config. + + Checks the replay buffer config for common misconfigurations, warns or raises + error in case validation fails. The type "key" is changed into the inferred + replay buffer class. + + Args: + config: The replay buffer config to be validated. + + Raises: + ValueError: When detecting severe misconfiguration. + """ + if config.get("replay_buffer_config", None) is None: + config["replay_buffer_config"] = {} + + if config.get("worker_side_prioritization", DEPRECATED_VALUE) != DEPRECATED_VALUE: + deprecation_warning( + old="config['worker_side_prioritization']", + new="config['replay_buffer_config']['worker_side_prioritization']", + error=True, + ) + + prioritized_replay = config.get("prioritized_replay", DEPRECATED_VALUE) + if prioritized_replay != DEPRECATED_VALUE: + deprecation_warning( + old="config['prioritized_replay'] or config['replay_buffer_config'][" + "'prioritized_replay']", + help="Replay prioritization specified by config key. RLlib's new replay " + "buffer API requires setting `config[" + "'replay_buffer_config']['type']`, e.g. `config[" + "'replay_buffer_config']['type'] = " + "'MultiAgentPrioritizedReplayBuffer'` to change the default " + "behaviour.", + error=True, + ) + + capacity = config.get("buffer_size", DEPRECATED_VALUE) + if capacity == DEPRECATED_VALUE: + capacity = config["replay_buffer_config"].get("buffer_size", DEPRECATED_VALUE) + if capacity != DEPRECATED_VALUE: + deprecation_warning( + old="config['buffer_size'] or config['replay_buffer_config'][" + "'buffer_size']", + new="config['replay_buffer_config']['capacity']", + error=True, + ) + + replay_burn_in = config.get("burn_in", DEPRECATED_VALUE) + if replay_burn_in != DEPRECATED_VALUE: + config["replay_buffer_config"]["replay_burn_in"] = replay_burn_in + deprecation_warning( + old="config['burn_in']", + help="config['replay_buffer_config']['replay_burn_in']", + ) + + replay_batch_size = config.get("replay_batch_size", DEPRECATED_VALUE) + if replay_batch_size == DEPRECATED_VALUE: + replay_batch_size = config["replay_buffer_config"].get( + "replay_batch_size", DEPRECATED_VALUE + ) + if replay_batch_size != DEPRECATED_VALUE: + deprecation_warning( + old="config['replay_batch_size'] or config['replay_buffer_config'][" + "'replay_batch_size']", + help="Specification of replay_batch_size is not supported anymore but is " + "derived from `train_batch_size`. Specify the number of " + "items you want to replay upon calling the sample() method of replay " + "buffers if this does not work for you.", + error=True, + ) + + # Deprecation of old-style replay buffer args + # Warnings before checking of we need local buffer so that algorithms + # Without local buffer also get warned + keys_with_deprecated_positions = [ + "prioritized_replay_alpha", + "prioritized_replay_beta", + "prioritized_replay_eps", + "no_local_replay_buffer", + "replay_zero_init_states", + "replay_buffer_shards_colocated_with_driver", + ] + for k in keys_with_deprecated_positions: + if config.get(k, DEPRECATED_VALUE) != DEPRECATED_VALUE: + deprecation_warning( + old="config['{}']".format(k), + help="config['replay_buffer_config']['{}']" "".format(k), + error=False, + ) + # Copy values over to new location in config to support new + # and old configuration style. + if config.get("replay_buffer_config") is not None: + config["replay_buffer_config"][k] = config[k] + + learning_starts = config.get( + "learning_starts", + config.get("replay_buffer_config", {}).get("learning_starts", DEPRECATED_VALUE), + ) + if learning_starts != DEPRECATED_VALUE: + deprecation_warning( + old="config['learning_starts'] or" + "config['replay_buffer_config']['learning_starts']", + help="config['num_steps_sampled_before_learning_starts']", + error=True, + ) + config["num_steps_sampled_before_learning_starts"] = learning_starts + + # Can't use DEPRECATED_VALUE here because this is also a deliberate + # value set for some algorithms + # TODO: (Artur): Compare to DEPRECATED_VALUE on deprecation + replay_sequence_length = config.get("replay_sequence_length", None) + if replay_sequence_length is not None: + config["replay_buffer_config"][ + "replay_sequence_length" + ] = replay_sequence_length + deprecation_warning( + old="config['replay_sequence_length']", + help="Replay sequence length specified at new " + "location config['replay_buffer_config'][" + "'replay_sequence_length'] will be overwritten.", + error=True, + ) + + replay_buffer_config = config["replay_buffer_config"] + assert ( + "type" in replay_buffer_config + ), "Can not instantiate ReplayBuffer from config without 'type' key." + + # Check if old replay buffer should be instantiated + buffer_type = config["replay_buffer_config"]["type"] + + if isinstance(buffer_type, str) and buffer_type.find(".") == -1: + # Create valid full [module].[class] string for from_config + config["replay_buffer_config"]["type"] = ( + "ray.rllib.utils.replay_buffers." + buffer_type + ) + + # Instantiate a dummy buffer to fail early on misconfiguration and find out about + # inferred buffer class + dummy_buffer = from_config(buffer_type, config["replay_buffer_config"]) + + config["replay_buffer_config"]["type"] = type(dummy_buffer) + + if hasattr(dummy_buffer, "update_priorities"): + if ( + config["replay_buffer_config"].get("replay_mode", "independent") + == "lockstep" + ): + raise ValueError( + "Prioritized replay is not supported when replay_mode=lockstep." + ) + elif config["replay_buffer_config"].get("replay_sequence_length", 0) > 1: + raise ValueError( + "Prioritized replay is not supported when " + "replay_sequence_length > 1." + ) + else: + if config["replay_buffer_config"].get("worker_side_prioritization"): + raise ValueError( + "Worker side prioritization is not supported when " + "prioritized_replay=False." + ) + + +@DeveloperAPI +def warn_replay_buffer_capacity(*, item: SampleBatchType, capacity: int) -> None: + """Warn if the configured replay buffer capacity is too large for machine's memory. + + Args: + item: A (example) item that's supposed to be added to the buffer. + This is used to compute the overall memory footprint estimate for the + buffer. + capacity: The capacity value of the buffer. This is interpreted as the + number of items (such as given `item`) that will eventually be stored in + the buffer. + + Raises: + ValueError: If computed memory footprint for the buffer exceeds the machine's + RAM. + """ + if log_once("warn_replay_buffer_capacity"): + item_size = item.size_bytes() + psutil_mem = psutil.virtual_memory() + total_gb = psutil_mem.total / 1e9 + mem_size = capacity * item_size / 1e9 + msg = ( + "Estimated max memory usage for replay buffer is {} GB " + "({} batches of size {}, {} bytes each), " + "available system memory is {} GB".format( + mem_size, capacity, item.count, item_size, total_gb + ) + ) + if mem_size > total_gb: + raise ValueError(msg) + elif mem_size > 0.2 * total_gb: + logger.warning(msg) + else: + logger.info(msg) + + +def patch_buffer_with_fake_sampling_method( + buffer: ReplayBuffer, fake_sample_output: SampleBatchType +) -> None: + """Patch a ReplayBuffer such that we always sample fake_sample_output. + + Transforms fake_sample_output into a MultiAgentBatch if it is not a + MultiAgentBatch and the buffer is a MultiAgentBuffer. This is useful for testing + purposes if we need deterministic sampling. + + Args: + buffer: The buffer to be patched + fake_sample_output: The output to be sampled + + """ + if isinstance(buffer, MultiAgentReplayBuffer) and not isinstance( + fake_sample_output, MultiAgentBatch + ): + fake_sample_output = SampleBatch(fake_sample_output).as_multi_agent() + + def fake_sample(_: Any = None, **kwargs) -> Optional[SampleBatchType]: + """Always returns a predefined batch. + + Args: + _: dummy arg to match signature of sample() method + __: dummy arg to match signature of sample() method + ``**kwargs``: dummy args to match signature of sample() method + + Returns: + Predefined MultiAgentBatch fake_sample_output + """ + + return fake_sample_output + + buffer.sample = fake_sample diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/__init__.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba7f682b981ca5c96f7a7713ca595b9d0a228ba7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/__pycache__/runner.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/__pycache__/runner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbc52d69fe746ae7f6329daf587512e6c5fce287 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/__pycache__/runner.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/__pycache__/runner_group.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/__pycache__/runner_group.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6a48d06e17bc83a5e7a2276a410f2a35a986e54 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/__pycache__/runner_group.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/runner.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/runner.py new file mode 100644 index 0000000000000000000000000000000000000000..c7193a6719d509964bdd3cb3db5df5b2b430ebd2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/runner.py @@ -0,0 +1,105 @@ +import abc +import logging + +from typing import Any, TYPE_CHECKING + +from ray.rllib.utils.actor_manager import FaultAwareApply +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.typing import DeviceType, TensorType + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +logger = logging.getLogger(__name__) + + +class Runner(FaultAwareApply, metaclass=abc.ABCMeta): + def __init__(self, *, config: "AlgorithmConfig", **kwargs): + """Initializes a `Runner` instance. + + Args: + config: The `AlgorithmConfig` to use to setup this `Runner`. + **kwargs: Forward compatibility `kwargs`. + """ + self.worker_index: int = kwargs.get("worker_index") + self.config: AlgorithmConfig = config.copy(copy_frozen=False) + # Set the device. + self.set_device() + # Generate the `RLModule`. + self.make_module() + self._weights_seq_no = 0 + + # Create a MetricsLogger object for logging custom stats. + self.metrics: MetricsLogger = MetricsLogger() + + # Initialize the `FaultAwareApply`. + super().__init__() + + @abc.abstractmethod + def assert_healthy(self): + """Checks that self.__init__() has been completed properly. + + Useful in case an `Runner` is run as @ray.remote (Actor) and the owner + would like to make sure the Ray Actor has been properly initialized. + + Raises: + AssertionError: If the `Runner` Actor has NOT been properly initialized. + """ + + @abc.abstractmethod + def make_module(self): + """Creates the `RLModule` for this `Runner` and assigns it to `self.module`. + + Note that users should be able to change the `Runner`'s config (e.g. change + `self.config.rl_module_spec`) and then call this method to create a new `RLModule` + with the updated configuration. + """ + pass + + @abc.abstractmethod + def run(self, **kwargs) -> Any: + """Runs the `Runner`. + + The exact logic of this method could have very different forms. + + Args: + **kwargs: Forward compatibility kwargs. + + Returns: + Anything. + """ + + @abc.abstractmethod + def get_metrics(self) -> Any: + """Returns metrics (in any form) of the logic run in this `Runner`. + + Returns: + Metrics of any form. + """ + + @abc.abstractmethod + def stop(self) -> None: + """Releases all resources used by this `Runner`. + + For example, when using a `gym.Env` in this `Runner`, you should make sure + that its `close()` method is called. + """ + + @property + @abc.abstractmethod + def _device(self) -> DeviceType: + """Returns the device of this `Runner`.""" + pass + + @abc.abstractmethod + def set_device(self) -> None: + """Sets the device for this `Runner`.""" + pass + + @abc.abstractmethod + def __del__(self) -> None: + """If this Actor is deleted, clears all resources used by it.""" + + @abc.abstractmethod + def _convert_to_tensor(self, struct) -> TensorType: + """Converts structs to a framework-specific tensor.""" diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/runner_group.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/runner_group.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb01ab37823da374b49d3097153889022e3d42a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/runners/runner_group.py @@ -0,0 +1,752 @@ +import abc +import logging +import ray + +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Tuple, + TYPE_CHECKING, + TypeVar, + Union, +) + +from ray.actor import ActorHandle +from ray.exceptions import RayActorError +from ray.rllib.core import ( + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_LEARNER, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + COMPONENT_RL_MODULE, +) +from ray.rllib.core.learner.learner_group import LearnerGroup +from ray.rllib.utils.actor_manager import FaultTolerantActorManager +from ray.rllib.utils.metrics import NUM_ENV_STEPS_SAMPLED_LIFETIME, WEIGHTS_SEQ_NO +from ray.rllib.utils.runners.runner import Runner +from ray.rllib.utils.typing import PolicyID +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +logger = logging.getLogger(__name__) + +# Generic type var for `foreach_*` methods. +T = TypeVar("T") + + +@DeveloperAPI +class RunnerGroup(metaclass=abc.ABCMeta): + def __init__( + self, + config: "AlgorithmConfig", + # TODO (simon): Check, if this is needed. Derived classes could define + # this if needed. + # default_policy_class: Optional[Type[Policy]] + local_runner: Optional[bool] = False, + logdir: Optional[str] = None, + # TODO (simon): Check, if still needed. + tune_trial_id: Optional[str] = None, + pg_offset: int = 0, + _setup: bool = True, + **kwargs: Dict[str, Any], + ) -> None: + + # TODO (simon): Remove when old stack is deprecated. + self.config: AlgorithmConfig = ( + AlgorithmConfig.from_dict(config) + if isinstance(config, dict) + else (config or AlgorithmConfig()) + ) + + self._remote_config = config + self._remote_config_obj_ref = ray.put(self._remote_config) + + self._tune_trial_id = tune_trial_id + self._pg_offset = pg_offset + + self._logdir = logdir + + self._worker_manager = FaultTolerantActorManager( + max_remote_requests_in_flight_per_actor=self._max_requests_in_flight_per_runner, + init_id=1, + ) + + if _setup: + try: + self._setup( + config=config, + num_runners=self.num_runners, + local_runner=local_runner, + **kwargs, + ) + # `RunnerGroup` creation possibly fails, if some (remote) workers cannot + # be initialized properly (due to some errors in the `Runners`'s + # constructor). + except RayActorError as e: + # In case of an actor (remote worker) init failure, the remote worker + # may still exist and will be accessible, however, e.g. calling + # its `run.remote()` would result in strange "property not found" + # errors. + if e.actor_init_failed: + # Raise the original error here that the `Runners` raised + # during its construction process. This is to enforce transparency + # for the user (better to understand the real reason behind the + # failure). + # - e.args[0]: The `RayTaskError` (inside the caught `RayActorError`). + # - e.args[0].args[2]: The original `Exception` (e.g. a `ValueError` due + # to a config mismatch) thrown inside the actor. + raise e.args[0].args[2] + # In any other case, raise the `RayActorError` as-is. + else: + raise e + + def _setup( + self, + *, + config: Optional["AlgorithmConfig"] = None, + num_runners: int = 0, + local_runner: Optional[bool] = False, + validate: Optional[bool] = None, + **kwargs: Dict[str, Any], + ) -> None: + + # TODO (simon): Deprecate this as soon as we are deprecating the old stack. + self._local_runner = None + if num_runners == 0: + local_runner = True + + self.__local_config = config + + # Create a number of @ray.remote workers. + self.add_runners( + num_runners, + validate=validate + if validate is not None + else self._validate_runners_after_construction, + **kwargs, + ) + + if local_runner: + self._local_runner = self._make_runner( + runner_index=0, + num_runners=num_runners, + config=self._local_config, + **kwargs, + ) + + def add_runners(self, num_runners: int, validate: bool = False, **kwargs) -> None: + """Creates and adds a number of remote runners to this runner set.""" + + old_num_runners = self._worker_manager.num_actors() + new_runners = [ + self._make_runner( + runner_index=old_num_runners + i + 1, + num_runners=old_num_runners + num_runners, + # `self._remote_config` can be large and it's best practice to + # pass it by reference instead of value + # (https://docs.ray.io/en/latest/ray-core/patterns/pass-large-arg-by-value.html) # noqa + config=self._remote_config_obj_ref, + **kwargs, + ) + for i in range(num_runners) + ] + # Add the new workers to the worker manager. + self._worker_manager.add_actors(new_runners) + + # Validate here, whether all remote workers have been constructed properly + # and are "up and running". Establish initial states. + if validate: + self.validate() + + def validate(self) -> Exception: + for result in self._worker_manager.foreach_actor(lambda w: w.assert_healthy()): + # Simiply raise the error, which will get handled by the try-except + # clause around the _setup(). + if not result.ok: + e = result.get() + if self._ignore_ray_errors_on_runners: + logger.error( + f"Validation of {self.runner_cls.__name__} failed! Error={str(e)}" + ) + else: + raise e + + def _make_runner( + self, + *, + runner_index: int, + num_runners: int, + recreated_runner: bool = False, + config: "AlgorithmConfig", + **kwargs, + ) -> ActorHandle: + # TODO (simon): Change this in the `EnvRunner` API + # to `runner_*`. + kwargs = dict( + config=config, + worker_index=runner_index, + num_workers=num_runners, + recreated_worker=recreated_runner, + log_dir=self._logdir, + tune_trial_id=self._tune_trial_id, + **kwargs, + ) + + # If a local runner is requested just return a runner instance. + if runner_index == 0: + return self.runner_cls(**kwargs) + + # Otherwise define a bundle index and schedule the remote worker. + pg_bundle_idx = ( + -1 + if ray.util.get_current_placement_group() is None + else self._pg_offset + runner_index + ) + return ( + ray.remote(**self._remote_args)(self.runner_cls) + .options(placement_group_bundle_index=pg_bundle_idx) + .remote(**kwargs) + ) + + def sync_runner_states( + self, + *, + config: "AlgorithmConfig", + from_runner: Optional[Runner] = None, + env_steps_sampled: Optional[int] = None, + connector_states: Optional[List[Dict[str, Any]]] = None, + rl_module_state: Optional[Dict[str, Any]] = None, + runner_indices_to_update: Optional[List[int]] = None, + env_to_module=None, + module_to_env=None, + **kwargs, + ): + """Synchronizes the connectors of this `RunnerGroup`'s `Runner`s.""" + + # If no `Runner` is passed in synchronize through the local `Runner`. + from_runner = from_runner or self.local_runner + + merge = config.merge_runner_states or ( + config.merge_runner_states == "training_only" and config.in_evaluation + ) + + broadcast = config.broadcast_runner_states + + # Early out if the number of (healthy) remote workers is 0. In this case, the + # local worker is the only operating worker and thus of course always holds + # the reference connector state. + if self.num_healthy_remote_runners == 0 and self.local_runner: + self.local_runner.set_state( + { + **( + {NUM_ENV_STEPS_SAMPLED_LIFETIME: env_steps_sampled} + if env_steps_sampled is not None + else {} + ), + **(rl_module_state or {}), + } + ) + + # Also early out, if we don't merge AND don't broadcast. + if not merge and not broadcast: + return + + # Use states from all remote `Runner`s. + if merge: + if connector_states == []: + runner_states = {} + else: + if connector_states is None: + connector_states = self.foreach_runner( + lambda w: w.get_state( + components=[ + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + ] + ), + local_runner=False, + timeout_seconds=( + config.sync_filters_on_rollout_workers_timeout_s + ), + ) + env_to_module_states = [ + s[COMPONENT_ENV_TO_MODULE_CONNECTOR] + for s in connector_states + if COMPONENT_ENV_TO_MODULE_CONNECTOR in s + ] + module_to_env_states = [ + s[COMPONENT_MODULE_TO_ENV_CONNECTOR] + for s in connector_states + if COMPONENT_MODULE_TO_ENV_CONNECTOR in s + ] + + if ( + self.local_runner is not None + and hasattr(self.local_runner, "_env_to_module") + and hasattr(self.local_runner, "_module_to_env") + ): + assert env_to_module is None + env_to_module = self.local_runner._env_to_module + assert module_to_env is None + module_to_env = self.local_runner._module_to_env + + runner_states = {} + if env_to_module_states: + runner_states.update( + { + COMPONENT_ENV_TO_MODULE_CONNECTOR: ( + env_to_module.merge_states(env_to_module_states) + ), + } + ) + if module_to_env_states: + runner_states.update( + { + COMPONENT_MODULE_TO_ENV_CONNECTOR: ( + module_to_env.merge_states(module_to_env_states) + ), + } + ) + # Ignore states from remote `Runner`s (use the current `from_worker` states + # only). + else: + if from_runner is None: + runner_states = { + COMPONENT_ENV_TO_MODULE_CONNECTOR: env_to_module.get_state(), + COMPONENT_MODULE_TO_ENV_CONNECTOR: module_to_env.get_state(), + } + else: + runner_states = from_runner.get_state( + components=[ + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + ] + ) + + # Update the global number of environment steps, if necessary. + # Make sure to divide by the number of env runners (such that each `Runner` + # knows (roughly) its own(!) lifetime count and can infer the global lifetime + # count from it). + if env_steps_sampled is not None: + runner_states[NUM_ENV_STEPS_SAMPLED_LIFETIME] = env_steps_sampled // ( + config.num_runners or 1 + ) + + # If we do NOT want remote `Runner`s to get their Connector states updated, + # only update the local worker here (with all state components, except the model + # weights) and then remove the connector components. + if not broadcast: + if self.local_runner is not None: + self.local_runner.set_state(runner_states) + else: + env_to_module.set_state( + runner_states.get(COMPONENT_ENV_TO_MODULE_CONNECTOR), {} + ) + module_to_env.set_state( + runner_states.get(COMPONENT_MODULE_TO_ENV_CONNECTOR), {} + ) + runner_states.pop(COMPONENT_ENV_TO_MODULE_CONNECTOR, None) + runner_states.pop(COMPONENT_MODULE_TO_ENV_CONNECTOR, None) + + # If there are components in the state left -> Update remote workers with these + # state components (and maybe the local worker, if it hasn't been updated yet). + if runner_states: + # Update the local `Runner`, but NOT with the weights. If used at all for + # evaluation (through the user calling `self.evaluate`), RLlib would update + # the weights up front either way. + if self.local_runner is not None and broadcast: + self.local_runner.set_state(runner_states) + + # Send the model weights only to remote `Runner`s. + # In case the local `Runner` is ever needed for evaluation, + # RLlib updates its weight right before such an eval step. + if rl_module_state: + runner_states.update(rl_module_state) + + # Broadcast updated states back to all workers. + self.foreach_runner( + "set_state", # Call the `set_state()` remote method. + kwargs=dict(state=runner_states), + remote_worker_ids=runner_indices_to_update, + local_runner=False, + timeout_seconds=0.0, # This is a state update -> Fire-and-forget. + ) + + def sync_weights( + self, + policies: Optional[List[PolicyID]] = None, + from_worker_or_learner_group: Optional[Union[Runner, "LearnerGroup"]] = None, + to_worker_indices: Optional[List[int]] = None, + timeout_seconds: Optional[float] = 0.0, + inference_only: Optional[bool] = False, + **kwargs, + ) -> None: + """Syncs model weights from the given weight source to all remote workers. + + Weight source can be either a (local) rollout worker or a learner_group. It + should just implement a `get_weights` method. + + Args: + policies: Optional list of PolicyIDs to sync weights for. + If None (default), sync weights to/from all policies. + from_worker_or_learner_group: Optional (local) `Runner` instance or + LearnerGroup instance to sync from. If None (default), + sync from this `Runner`Group's local worker. + to_worker_indices: Optional list of worker indices to sync the + weights to. If None (default), sync to all remote workers. + global_vars: An optional global vars dict to set this + worker to. If None, do not update the global_vars. + timeout_seconds: Timeout in seconds to wait for the sync weights + calls to complete. Default is 0.0 (fire-and-forget, do not wait + for any sync calls to finish). Setting this to 0.0 might significantly + improve algorithm performance, depending on the algo's `training_step` + logic. + inference_only: Sync weights with workers that keep inference-only + modules. This is needed for algorithms in the new stack that + use inference-only modules. In this case only a part of the + parameters are synced to the workers. Default is False. + """ + if self.local_runner is None and from_worker_or_learner_group is None: + raise TypeError( + "No `local_runner` in `RunnerGroup`! Must provide " + "`from_worker_or_learner_group` arg in `sync_weights()`!" + ) + + # Only sync if we have remote workers or `from_worker_or_trainer` is provided. + rl_module_state = None + if self.num_remote_runners or from_worker_or_learner_group is not None: + weights_src = ( + from_worker_or_learner_group + if from_worker_or_learner_group is not None + else self.local_runner + ) + + if weights_src is None: + raise ValueError( + "`from_worker_or_trainer` is None. In this case, `RunnerGroup`^ " + "should have `local_runner`. But `local_runner` is also `None`." + ) + + modules = ( + [COMPONENT_RL_MODULE + "/" + p for p in policies] + if policies is not None + else [COMPONENT_RL_MODULE] + ) + # LearnerGroup has-a Learner, which has-a RLModule. + if isinstance(weights_src, LearnerGroup): + rl_module_state = weights_src.get_state( + components=[COMPONENT_LEARNER + "/" + m for m in modules], + inference_only=inference_only, + )[COMPONENT_LEARNER] + # `Runner` (new API stack). + else: + # Runner (remote) has a RLModule. + # TODO (sven): Replace this with a new ActorManager API: + # try_remote_request_till_success("get_state") -> tuple(int, + # remoteresult) + # `weights_src` could be the ActorManager, then. Then RLlib would know + # that it has to ping the manager to try all healthy actors until the + # first returns something. + if isinstance(weights_src, ActorHandle): + rl_module_state = ray.get( + weights_src.get_state.remote( + components=modules, + inference_only=inference_only, + ) + ) + # `Runner` (local) has an RLModule. + else: + rl_module_state = weights_src.get_state( + components=modules, + inference_only=inference_only, + ) + + # Make sure `rl_module_state` only contains the weights and the + # weight seq no, nothing else. + rl_module_state = { + k: v + for k, v in rl_module_state.items() + if k in [COMPONENT_RL_MODULE, WEIGHTS_SEQ_NO] + } + + # Move weights to the object store to avoid having to make n pickled + # copies of the weights dict for each worker. + rl_module_state_ref = ray.put(rl_module_state) + + # Sync to specified remote workers in this `Runner`Group. + self.foreach_runner( + func="set_state", + kwargs=dict(state=rl_module_state_ref), + local_runner=False, # Do not sync back to local worker. + remote_worker_ids=to_worker_indices, + timeout_seconds=timeout_seconds, + ) + + # If `from_worker_or_learner_group` is provided, also sync to this + # `RunnerGroup`'s local worker. + if self.local_runner is not None: + if from_worker_or_learner_group is not None: + self.local_runner.set_state(rl_module_state) + + def reset(self, new_remote_runners: List[ActorHandle]) -> None: + """Hard overrides the remote `Runner`s in this set with the provided ones. + + Args: + new_remote_workers: A list of new `Runner`s (as `ActorHandles`) to use as + new remote workers. + """ + self._worker_manager.clear() + self._worker_manager.add_actors(new_remote_runners) + + def stop(self) -> None: + """Calls `stop` on all `Runner`s (including the local one).""" + try: + # Make sure we stop all `Runner`s, include the ones that were just + # restarted / recovered or that are tagged unhealthy (at least, we should + # try). + self.foreach_runner( + lambda w: w.stop(), healthy_only=False, local_runner=True + ) + except Exception: + logger.exception("Failed to stop workers!") + finally: + self._worker_manager.clear() + + def foreach_runner( + self, + func: Union[Callable[[Runner], T], List[Callable[[Runner], T]], str, List[str]], + *, + kwargs=None, + local_runner: bool = True, + healthy_only: bool = True, + remote_worker_ids: List[int] = None, + timeout_seconds: Optional[float] = None, + return_obj_refs: bool = False, + mark_healthy: bool = False, + ) -> List[T]: + """Calls the given function with each `Runner` as its argument. + + Args: + func: The function to call for each `Runner`s. The only call argument is + the respective `Runner` instance. + local_env_runner: Whether to apply `func` to local `Runner`, too. + Default is True. + healthy_only: Apply `func` on known-to-be healthy `Runner`s only. + remote_worker_ids: Apply `func` on a selected set of remote `Runner`s. + Use None (default) for all remote `Runner`s. + timeout_seconds: Time to wait (in seconds) for results. Set this to 0.0 for + fire-and-forget. Set this to None (default) to wait infinitely (i.e. for + synchronous execution). + return_obj_refs: Whether to return `ObjectRef` instead of actual results. + Note, for fault tolerance reasons, these returned ObjectRefs should + never be resolved with ray.get() outside of this `RunnerGroup`. + mark_healthy: Whether to mark all those `Runner`s healthy again that are + currently marked unhealthy AND that returned results from the remote + call (within the given `timeout_seconds`). + Note that `Runner`s are NOT set unhealthy, if they simply time out + (only if they return a `RayActorError`). + Also note that this setting is ignored if `healthy_only=True` (b/c + `mark_healthy` only affects `Runner`s that are currently tagged as + unhealthy). + + Returns: + The list of return values of all calls to `func([worker])`. + """ + assert ( + not return_obj_refs or not local_runner + ), "Can not return `ObjectRef` from local worker." + + local_result = [] + if local_runner and self.local_runner is not None: + if kwargs: + local_kwargs = kwargs[0] + kwargs = kwargs[1:] + else: + local_kwargs = {} + kwargs = kwargs + if isinstance(func, str): + local_result = [getattr(self.local_runner, func)(**local_kwargs)] + else: + local_result = [func(self.local_runner, **local_kwargs)] + + if not self._worker_manager.actor_ids(): + return local_result + + remote_results = self._worker_manager.foreach_actor( + func, + kwargs=kwargs, + healthy_only=healthy_only, + remote_actor_ids=remote_worker_ids, + timeout_seconds=timeout_seconds, + return_obj_refs=return_obj_refs, + mark_healthy=mark_healthy, + ) + + FaultTolerantActorManager.handle_remote_call_result_errors( + remote_results, ignore_ray_errors=self._ignore_ray_errors_on_runners + ) + + # With application errors handled, return good results. + remote_results = [r.get() for r in remote_results.ignore_errors()] + + return local_result + remote_results + + def foreach_runner_async( + self, + func: Union[Callable[[Runner], T], List[Callable[[Runner], T]], str, List[str]], + *, + healthy_only: bool = True, + remote_worker_ids: List[int] = None, + ) -> int: + """Calls the given function asynchronously with each `Runner` as the argument. + + Does not return results directly. Instead, `fetch_ready_async_reqs()` can be + used to pull results in an async manner whenever they are available. + + Args: + func: The function to call for each `Runner`s. The only call argument is + the respective `Runner` instance. + healthy_only: Apply `func` on known-to-be healthy `Runner`s only. + remote_worker_ids: Apply `func` on a selected set of remote `Runner`s. + + Returns: + The number of async requests that have actually been made. This is the + length of `remote_worker_ids` (or self.num_remote_workers()` if + `remote_worker_ids` is None) minus the number of requests that were NOT + made b/c a remote `Runner` already had its + `max_remote_requests_in_flight_per_actor` counter reached. + """ + return self._worker_manager.foreach_actor_async( + func, + healthy_only=healthy_only, + remote_actor_ids=remote_worker_ids, + ) + + def fetch_ready_async_reqs( + self, + *, + timeout_seconds: Optional[float] = 0.0, + return_obj_refs: bool = False, + mark_healthy: bool = False, + ) -> List[Tuple[int, T]]: + """Get esults from outstanding asynchronous requests that are ready. + + Args: + timeout_seconds: Time to wait for results. Default is 0, meaning + those requests that are already ready. + return_obj_refs: Whether to return ObjectRef instead of actual results. + mark_healthy: Whether to mark all those workers healthy again that are + currently marked unhealthy AND that returned results from the remote + call (within the given `timeout_seconds`). + Note that workers are NOT set unhealthy, if they simply time out + (only if they return a RayActorError). + Also note that this setting is ignored if `healthy_only=True` (b/c + `mark_healthy` only affects workers that are currently tagged as + unhealthy). + + Returns: + A list of results successfully returned from outstanding remote calls, + paired with the indices of the callee workers. + """ + remote_results = self._worker_manager.fetch_ready_async_reqs( + timeout_seconds=timeout_seconds, + return_obj_refs=return_obj_refs, + mark_healthy=mark_healthy, + ) + + FaultTolerantActorManager.handle_remote_call_result_errors( + remote_results, + ignore_ray_errors=self._ignore_ray_errors_on_runners, + ) + + return [(r.actor_id, r.get()) for r in remote_results.ignore_errors()] + + def probe_unhealthy_runners(self) -> List[int]: + """Checks for unhealthy workers and tries restoring their states. + + Returns: + List of IDs of the workers that were restored. + """ + return self._worker_manager.probe_unhealthy_actors( + timeout_seconds=self.runner_health_probe_timeout_s, + mark_healthy=True, + ) + + @property + @abc.abstractmethod + def runner_health_probe_timeout_s(self): + """Number of seconds to wait for health probe calls to `Runner`s.""" + + @property + @abc.abstractmethod + def runner_cls(self) -> Callable: + """Class for each runner.""" + + @property + def _local_config(self) -> "AlgorithmConfig": + """Returns the config for a local `Runner`.""" + return self.__local_config + + @property + def local_runner(self) -> Runner: + """Returns the local `Runner`.""" + return self._local_runner + + @property + def healthy_runner_ids(self) -> List[int]: + """Returns the list of remote `Runner` IDs.""" + return self._worker_manager.healthy_actor_ids() + + @property + @abc.abstractmethod + def num_runners(self) -> int: + """Number of runners to schedule and manage.""" + + @property + def num_remote_runners(self) -> int: + """Number of remote `Runner`s.""" + return self._worker_manager.num_actors() + + @property + def num_healthy_remote_runners(self) -> int: + """Returns the number of healthy remote `Runner`s.""" + return self._worker_manager.num_healthy_actors() + + @property + def num_healthy_runners(self) -> int: + """Returns the number of healthy `Runner`s.""" + return int(bool(self._local_runner)) + self.num_healthy_remote_runners() + + @property + def num_in_flight_async_reqs(self) -> int: + """Returns the number of in-flight async requests.""" + return self._worker_manager.num_outstanding_async_reqs() + + @property + def num_remote_runner_restarts(self) -> int: + """Returns the number of times managed remote `Runner`s have been restarted.""" + return self._worker_manager.total_num_restarts() + + @property + @abc.abstractmethod + def _remote_args(self): + """Remote arguments for each runner.""" + + @property + @abc.abstractmethod + def _ignore_ray_errors_on_runners(self): + """If errors in runners should be ignored.""" + + @property + @abc.abstractmethod + def _max_requests_in_flight_per_runner(self): + """Maximum requests in flight per runner.""" + + @property + @abc.abstractmethod + def _validate_runners_after_construction(self): + """If runners should validated after constructed.""" diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__init__.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..58503926968563c0dfcf6f1cf95ed04ca1a92cf1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__init__.py @@ -0,0 +1,15 @@ +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.schedules.constant_schedule import ConstantSchedule +from ray.rllib.utils.schedules.linear_schedule import LinearSchedule +from ray.rllib.utils.schedules.piecewise_schedule import PiecewiseSchedule +from ray.rllib.utils.schedules.polynomial_schedule import PolynomialSchedule +from ray.rllib.utils.schedules.exponential_schedule import ExponentialSchedule + +__all__ = [ + "ConstantSchedule", + "ExponentialSchedule", + "LinearSchedule", + "Schedule", + "PiecewiseSchedule", + "PolynomialSchedule", +] diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97d2d33463bd1e1ace360069303c430bc69decff Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/constant_schedule.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/constant_schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a35f9310c7084524c5e01ce86fa2ca4443dc77b7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/constant_schedule.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/exponential_schedule.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/exponential_schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af4d28458171430cb2775d58e26900ff6d78ea9f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/exponential_schedule.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/linear_schedule.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/linear_schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c39e42a5b7df1b22efcf87250e177e4930a51e61 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/linear_schedule.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/piecewise_schedule.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/piecewise_schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08f52264bd0eef05c54cdd946259de4720bc45a7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/piecewise_schedule.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/polynomial_schedule.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/polynomial_schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7575d76ef0d0b04f5ca7863d1393bb4210a679e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/polynomial_schedule.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/schedule.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/schedule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8ba0f039733eba80d336b4dd75fd0edc79eb3f8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/schedule.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/scheduler.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b83688940b8d76a999c748bb4d7be3ebb7e30a2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/__pycache__/scheduler.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/constant_schedule.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/constant_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad58e266f8d3e21144daae1c251cd2333b85907 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/constant_schedule.py @@ -0,0 +1,32 @@ +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class ConstantSchedule(Schedule): + """A Schedule where the value remains constant over time.""" + + def __init__(self, value: float, framework: Optional[str] = None): + """Initializes a ConstantSchedule instance. + + Args: + value: The constant value to return, independently of time. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + """ + super().__init__(framework=framework) + self._v = value + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + return self._v + + @override(Schedule) + def _tf_value_op(self, t: TensorType) -> TensorType: + return tf.constant(self._v) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/exponential_schedule.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/exponential_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..4aafac19470baa3081d06a5a3bc4cbd18d76e384 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/exponential_schedule.py @@ -0,0 +1,50 @@ +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType + +torch, _ = try_import_torch() + + +@OldAPIStack +class ExponentialSchedule(Schedule): + """Exponential decay schedule from `initial_p` to `final_p`. + + Reduces output over `schedule_timesteps`. After this many time steps + always returns `final_p`. + """ + + def __init__( + self, + schedule_timesteps: int, + framework: Optional[str] = None, + initial_p: float = 1.0, + decay_rate: float = 0.1, + ): + """Initializes a ExponentialSchedule instance. + + Args: + schedule_timesteps: Number of time steps for which to + linearly anneal initial_p to final_p. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + initial_p: Initial output value. + decay_rate: The percentage of the original value after + 100% of the time has been reached (see formula above). + >0.0: The smaller the decay-rate, the stronger the decay. + 1.0: No decay at all. + """ + super().__init__(framework=framework) + assert schedule_timesteps > 0 + self.schedule_timesteps = schedule_timesteps + self.initial_p = initial_p + self.decay_rate = decay_rate + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + """Returns the result of: initial_p * decay_rate ** (`t`/t_max).""" + if self.framework == "torch" and torch and isinstance(t, torch.Tensor): + t = t.float() + return self.initial_p * self.decay_rate ** (t / self.schedule_timesteps) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/linear_schedule.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/linear_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..d23647b9bbebf757f002444bb231a9b78d863a47 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/linear_schedule.py @@ -0,0 +1,18 @@ +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.schedules.polynomial_schedule import PolynomialSchedule + + +@OldAPIStack +class LinearSchedule(PolynomialSchedule): + """Linear interpolation between `initial_p` and `final_p`. + + Uses `PolynomialSchedule` with power=1.0. + + + The formula is: + value = `final_p` + (`initial_p` - `final_p`) * (1 - `t`/t_max) + """ + + def __init__(self, **kwargs): + """Initializes a LinearSchedule instance.""" + super().__init__(power=1.0, **kwargs) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/piecewise_schedule.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/piecewise_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4b15478b3f21bfa8612bdd5e39f952d0801086 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/piecewise_schedule.py @@ -0,0 +1,105 @@ +from typing import Callable, List, Optional, Tuple + +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType +from ray.util.annotations import DeveloperAPI + +tf1, tf, tfv = try_import_tf() + + +def _linear_interpolation(left, right, alpha): + return left + alpha * (right - left) + + +@DeveloperAPI +class PiecewiseSchedule(Schedule): + """Implements a Piecewise Scheduler.""" + + def __init__( + self, + endpoints: List[Tuple[int, float]], + framework: Optional[str] = None, + interpolation: Callable[ + [TensorType, TensorType, TensorType], TensorType + ] = _linear_interpolation, + outside_value: Optional[float] = None, + ): + """Initializes a PiecewiseSchedule instance. + + Args: + endpoints: A list of tuples + `(t, value)` such that the output + is an interpolation (given by the `interpolation` callable) + between two values. + E.g. + t=400 and endpoints=[(0, 20.0),(500, 30.0)] + output=20.0 + 0.8 * (30.0 - 20.0) = 28.0 + NOTE: All the values for time must be sorted in an increasing + order. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + interpolation: A function that takes the left-value, + the right-value and an alpha interpolation parameter + (0.0=only left value, 1.0=only right value), which is the + fraction of distance from left endpoint to right endpoint. + outside_value: If t in call to `value` is + outside of all the intervals in `endpoints` this value is + returned. If None then an AssertionError is raised when outside + value is requested. + """ + super().__init__(framework=framework) + + idxes = [e[0] for e in endpoints] + assert idxes == sorted(idxes) + self.interpolation = interpolation + self.outside_value = outside_value + self.endpoints = [(int(e[0]), float(e[1])) for e in endpoints] + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + # Find t in our list of endpoints. + for (l_t, l), (r_t, r) in zip(self.endpoints[:-1], self.endpoints[1:]): + # When found, return an interpolation (default: linear). + if l_t <= t < r_t: + alpha = float(t - l_t) / (r_t - l_t) + return self.interpolation(l, r, alpha) + + # t does not belong to any of the pieces, return `self.outside_value`. + assert self.outside_value is not None + return self.outside_value + + @override(Schedule) + def _tf_value_op(self, t: TensorType) -> TensorType: + assert self.outside_value is not None, ( + "tf-version of PiecewiseSchedule requires `outside_value` to be " + "provided!" + ) + + endpoints = tf.cast(tf.stack([e[0] for e in self.endpoints] + [-1]), tf.int64) + + # Create all possible interpolation results. + results_list = [] + for (l_t, l), (r_t, r) in zip(self.endpoints[:-1], self.endpoints[1:]): + alpha = tf.cast(t - l_t, tf.float32) / tf.cast(r_t - l_t, tf.float32) + results_list.append(self.interpolation(l, r, alpha)) + # If t does not belong to any of the pieces, return `outside_value`. + results_list.append(self.outside_value) + results_list = tf.stack(results_list) + + # Return correct results tensor depending on where we find t. + def _cond(i, x): + x = tf.cast(x, tf.int64) + return tf.logical_not( + tf.logical_or( + tf.equal(endpoints[i + 1], -1), + tf.logical_and(endpoints[i] <= x, x < endpoints[i + 1]), + ) + ) + + def _body(i, x): + return (i + 1, t) + + idx_and_t = tf.while_loop(_cond, _body, [tf.constant(0, dtype=tf.int64), t]) + return results_list[idx_and_t[0]] diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..17a2820d9af811d8c647f467501cd906f2bbdd9d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/polynomial_schedule.py @@ -0,0 +1,67 @@ +from typing import Optional + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.schedules.schedule import Schedule +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class PolynomialSchedule(Schedule): + """Polynomial interpolation between `initial_p` and `final_p`. + + Over `schedule_timesteps`. After this many time steps, always returns + `final_p`. + """ + + def __init__( + self, + schedule_timesteps: int, + final_p: float, + framework: Optional[str], + initial_p: float = 1.0, + power: float = 2.0, + ): + """Initializes a PolynomialSchedule instance. + + Args: + schedule_timesteps: Number of time steps for which to + linearly anneal initial_p to final_p + final_p: Final output value. + framework: The framework descriptor string, e.g. "tf", + "torch", or None. + initial_p: Initial output value. + power: The exponent to use (default: quadratic). + """ + super().__init__(framework=framework) + assert schedule_timesteps > 0 + self.schedule_timesteps = schedule_timesteps + self.final_p = final_p + self.initial_p = initial_p + self.power = power + + @override(Schedule) + def _value(self, t: TensorType) -> TensorType: + """Returns the result of: + final_p + (initial_p - final_p) * (1 - `t`/t_max) ** power + """ + if self.framework == "torch" and torch and isinstance(t, torch.Tensor): + t = t.float() + t = min(t, self.schedule_timesteps) + return ( + self.final_p + + (self.initial_p - self.final_p) + * (1.0 - (t / self.schedule_timesteps)) ** self.power + ) + + @override(Schedule) + def _tf_value_op(self, t: TensorType) -> TensorType: + t = tf.math.minimum(t, self.schedule_timesteps) + return ( + self.final_p + + (self.initial_p - self.final_p) + * (1.0 - (t / self.schedule_timesteps)) ** self.power + ) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/schedule.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..fa5b113ff5a9c1d328cdc0db0ec8197d4efa8b0f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/schedule.py @@ -0,0 +1,73 @@ +from abc import ABCMeta, abstractmethod +from typing import Any, Union + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class Schedule(metaclass=ABCMeta): + """Schedule classes implement various time-dependent scheduling schemas. + + - Constant behavior. + - Linear decay. + - Piecewise decay. + - Exponential decay. + + Useful for backend-agnostic rate/weight changes for learning rates, + exploration epsilons, beta parameters for prioritized replay, loss weights + decay, etc.. + + Each schedule can be called directly with the `t` (absolute time step) + value and returns the value dependent on the Schedule and the passed time. + """ + + def __init__(self, framework): + self.framework = framework + + def value(self, t: Union[int, TensorType]) -> Any: + """Generates the value given a timestep (based on schedule's logic). + + Args: + t: The time step. This could be a tf.Tensor. + + Returns: + The calculated value depending on the schedule and `t`. + """ + if self.framework in ["tf2", "tf"]: + return self._tf_value_op(t) + return self._value(t) + + def __call__(self, t: Union[int, TensorType]) -> Any: + """Simply calls self.value(t). Implemented to make Schedules callable.""" + return self.value(t) + + @abstractmethod + def _value(self, t: Union[int, TensorType]) -> Any: + """ + Returns the value based on a time step input. + + Args: + t: The time step. This could be a tf.Tensor. + + Returns: + The calculated value depending on the schedule and `t`. + """ + raise NotImplementedError + + def _tf_value_op(self, t: TensorType) -> TensorType: + """ + Returns the tf-op that calculates the value based on a time step input. + + Args: + t: The time step op (int tf.Tensor). + + Returns: + The calculated value depending on the schedule and `t`. + """ + # By default (most of the time), tf should work with python code. + # Override only if necessary. + return self._value(t) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/scheduler.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..901b5c785acd42a6fd2e2f0a3c9061145e3f0d54 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/schedules/scheduler.py @@ -0,0 +1,175 @@ +from typing import Optional + +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.schedules.piecewise_schedule import PiecewiseSchedule +from ray.rllib.utils.typing import LearningRateOrSchedule, TensorType +from ray.util.annotations import DeveloperAPI + + +_, tf, _ = try_import_tf() +torch, _ = try_import_torch() + + +@DeveloperAPI +class Scheduler: + """Class to manage a scheduled (framework-dependent) tensor variable. + + Uses the PiecewiseSchedule (for maximum configuration flexibility) + """ + + def __init__( + self, + fixed_value_or_schedule: LearningRateOrSchedule, + *, + framework: str = "torch", + device: Optional[str] = None, + ): + """Initializes a Scheduler instance. + + Args: + fixed_value_or_schedule: A fixed, constant value (in case no schedule should + be used) or a schedule configuration in the format of + [[timestep, value], [timestep, value], ...] + Intermediary timesteps will be assigned to linerarly interpolated + values. A schedule config's first entry must + start with timestep 0, i.e.: [[0, initial_value], [...]]. + framework: The framework string, for which to create the tensor variable + that hold the current value. This is the variable that can be used in + the graph, e.g. in a loss function. + device: Optional device (for torch) to place the tensor variable on. + """ + self.framework = framework + self.device = device + self.use_schedule = isinstance(fixed_value_or_schedule, (list, tuple)) + + if self.use_schedule: + # Custom schedule, based on list of + # ([ts], [value to be reached by ts])-tuples. + self._schedule = PiecewiseSchedule( + fixed_value_or_schedule, + outside_value=fixed_value_or_schedule[-1][-1], + framework=None, + ) + # As initial tensor valie, use the first timestep's (must be 0) value. + self._curr_value = self._create_tensor_variable( + initial_value=fixed_value_or_schedule[0][1] + ) + + # If no schedule, pin (fix) given value. + else: + self._curr_value = fixed_value_or_schedule + + @staticmethod + def validate( + *, + fixed_value_or_schedule: LearningRateOrSchedule, + setting_name: str, + description: str, + ) -> None: + """Performs checking of a certain schedule configuration. + + The first entry in `value_or_schedule` (if it's not a fixed value) must have a + timestep of 0. + + Args: + fixed_value_or_schedule: A fixed, constant value (in case no schedule should + be used) or a schedule configuration in the format of + [[timestep, value], [timestep, value], ...] + Intermediary timesteps will be assigned to linerarly interpolated + values. A schedule config's first entry must + start with timestep 0, i.e.: [[0, initial_value], [...]]. + setting_name: The property name of the schedule setting (within a config), + e.g. `lr` or `entropy_coeff`. + description: A full text description of the property that's being scheduled, + e.g. `learning rate`. + + Raises: + ValueError: In case, errors are found in the schedule's format. + """ + # Fixed (single) value. + if ( + isinstance(fixed_value_or_schedule, (int, float)) + or fixed_value_or_schedule is None + ): + return + + if not isinstance(fixed_value_or_schedule, (list, tuple)) or ( + len(fixed_value_or_schedule) < 2 + ): + raise ValueError( + f"Invalid `{setting_name}` ({fixed_value_or_schedule}) specified! " + f"Must be a list of 2 or more tuples, each of the form " + f"(`timestep`, `{description} to reach`), for example " + "`[(0, 0.001), (1e6, 0.0001), (2e6, 0.00005)]`." + ) + elif fixed_value_or_schedule[0][0] != 0: + raise ValueError( + f"When providing a `{setting_name}` schedule, the first timestep must " + f"be 0 and the corresponding lr value is the initial {description}! " + f"You provided ts={fixed_value_or_schedule[0][0]} {description}=" + f"{fixed_value_or_schedule[0][1]}." + ) + elif any(len(pair) != 2 for pair in fixed_value_or_schedule): + raise ValueError( + f"When providing a `{setting_name}` schedule, each tuple in the " + f"schedule list must have exctly 2 items of the form " + f"(`timestep`, `{description} to reach`), for example " + "`[(0, 0.001), (1e6, 0.0001), (2e6, 0.00005)]`." + ) + + def get_current_value(self) -> TensorType: + """Returns the current value (as a tensor variable). + + This method should be used in loss functions of other (in-graph) places + where the current value is needed. + + Returns: + The tensor variable (holding the current value to be used). + """ + return self._curr_value + + def update(self, timestep: int) -> float: + """Updates the underlying (framework specific) tensor variable. + + In case of a fixed value, this method does nothing and only returns the fixed + value as-is. + + Args: + timestep: The current timestep that the update might depend on. + + Returns: + The current value of the tensor variable as a python float. + """ + if self.use_schedule: + python_value = self._schedule.value(t=timestep) + if self.framework == "torch": + self._curr_value.data = torch.tensor(python_value) + else: + self._curr_value.assign(python_value) + else: + python_value = self._curr_value + + return python_value + + def _create_tensor_variable(self, initial_value: float) -> TensorType: + """Creates a framework-specific tensor variable to be scheduled. + + Args: + initial_value: The initial (float) value for the variable to hold. + + Returns: + The created framework-specific tensor variable. + """ + if self.framework == "torch": + return torch.tensor( + initial_value, + requires_grad=False, + dtype=torch.float32, + device=self.device, + ) + else: + return tf.Variable( + initial_value, + trainable=False, + dtype=tf.float32, + ) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__init__.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ab3d8c197707a961913e0fcd316e217bcb5d7c8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/flexdict.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/flexdict.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..907b75dc1ccdde0f3f8088920ae8433dc78ef352 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/flexdict.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/repeated.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/repeated.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef74d1b6f7951ed688d83c9189cc44f7baa8e0f9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/repeated.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/simplex.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/simplex.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2c2460eef5cae5ae7b19c5a83a7df88818c2bf3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/simplex.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/space_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/space_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2635d1f7a565aca31b7a05cb3d61e8bcec818143 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/__pycache__/space_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/flexdict.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/flexdict.py new file mode 100644 index 0000000000000000000000000000000000000000..905a05e2857b72856cee0bd142dd3af204029c07 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/flexdict.py @@ -0,0 +1,47 @@ +import gymnasium as gym + +from ray.rllib.utils.annotations import PublicAPI + + +@PublicAPI +class FlexDict(gym.spaces.Dict): + """Gym Dictionary with arbitrary keys updatable after instantiation + + Example: + space = FlexDict({}) + space['key'] = spaces.Box(4,) + See also: documentation for gym.spaces.Dict + """ + + def __init__(self, spaces=None, **spaces_kwargs): + err = "Use either Dict(spaces=dict(...)) or Dict(foo=x, bar=z)" + assert (spaces is None) or (not spaces_kwargs), err + + if spaces is None: + spaces = spaces_kwargs + + for space in spaces.values(): + self.assertSpace(space) + + super().__init__(spaces=spaces) + + def assertSpace(self, space): + err = "Values of the dict should be instances of gym.Space" + assert issubclass(type(space), gym.spaces.Space), err + + def sample(self): + return {k: space.sample() for k, space in self.spaces.items()} + + def __getitem__(self, key): + return self.spaces[key] + + def __setitem__(self, key, space): + self.assertSpace(space) + self.spaces[key] = space + + def __repr__(self): + return ( + "FlexDict(" + + ", ".join([str(k) + ":" + str(s) for k, s in self.spaces.items()]) + + ")" + ) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/repeated.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/repeated.py new file mode 100644 index 0000000000000000000000000000000000000000..77beaff288e749b01780c9e9bf6b25e3f123b2d8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/repeated.py @@ -0,0 +1,38 @@ +import gymnasium as gym +import numpy as np + +from ray.rllib.utils.annotations import PublicAPI + + +@PublicAPI +class Repeated(gym.Space): + """Represents a variable-length list of child spaces. + + Example: + self.observation_space = spaces.Repeated(spaces.Box(4,), max_len=10) + --> from 0 to 10 boxes of shape (4,) + + See also: documentation for rllib.models.RepeatedValues, which shows how + the lists are represented as batched input for ModelV2 classes. + """ + + def __init__(self, child_space: gym.Space, max_len: int): + super().__init__() + self.child_space = child_space + self.max_len = max_len + + def sample(self): + return [ + self.child_space.sample() + for _ in range(self.np_random.integers(1, self.max_len + 1)) + ] + + def contains(self, x): + return ( + isinstance(x, (list, np.ndarray)) + and len(x) <= self.max_len + and all(self.child_space.contains(c) for c in x) + ) + + def __repr__(self): + return "Repeated({}, {})".format(self.child_space, self.max_len) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/simplex.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/simplex.py new file mode 100644 index 0000000000000000000000000000000000000000..7e3b4c843ad0e4d0303f106b5621f88428f8b931 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/simplex.py @@ -0,0 +1,61 @@ +import gymnasium as gym +import numpy as np + +from ray.rllib.utils.annotations import PublicAPI + + +@PublicAPI +class Simplex(gym.Space): + """Represents a d - 1 dimensional Simplex in R^d. + + That is, all coordinates are in [0, 1] and sum to 1. + The dimension d of the simplex is assumed to be shape[-1]. + + Additionally one can specify the underlying distribution of + the simplex as a Dirichlet distribution by providing concentration + parameters. By default, sampling is uniform, i.e. concentration is + all 1s. + + Example usage: + self.action_space = spaces.Simplex(shape=(3, 4)) + --> 3 independent 4d Dirichlet with uniform concentration + """ + + def __init__(self, shape, concentration=None, dtype=np.float32): + assert type(shape) in [tuple, list] + + super().__init__(shape, dtype) + self.dim = self.shape[-1] + + if concentration is not None: + assert ( + concentration.shape[0] == shape[-1] + ), f"{concentration.shape[0]} vs {shape[-1]}" + self.concentration = concentration + else: + self.concentration = np.array([1] * self.dim) + + def sample(self): + return np.random.dirichlet(self.concentration, size=self.shape[:-1]).astype( + self.dtype + ) + + def contains(self, x): + return x.shape == self.shape and np.allclose( + np.sum(x, axis=-1), np.ones_like(x[..., 0]) + ) + + def to_jsonable(self, sample_n): + return np.array(sample_n).tolist() + + def from_jsonable(self, sample_n): + return [np.asarray(sample) for sample in sample_n] + + def __repr__(self): + return "Simplex({}; {})".format(self.shape, self.concentration) + + def __eq__(self, other): + return ( + np.allclose(self.concentration, other.concentration) + and self.shape == other.shape + ) diff --git a/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/space_utils.py b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/space_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..921c174d5d82d66f2007a09e917f055c4cc4344b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/rllib/utils/spaces/space_utils.py @@ -0,0 +1,562 @@ +import gymnasium as gym +from gymnasium.spaces import Tuple, Dict +from gymnasium.core import ActType, ObsType +import numpy as np +from ray.rllib.utils.annotations import DeveloperAPI +import tree # pip install dm_tree +from typing import Any, List, Optional, Union + + +@DeveloperAPI +class BatchedNdArray(np.ndarray): + """A ndarray-wrapper the usage of which indicates that there a batch dim exists. + + This is such that our `batch()` utility can distinguish between having to + stack n individual batch items (each one w/o any batch dim) vs having to + concatenate n already batched items (each one possibly with a different batch + dim, but definitely with some batch dim). + + TODO (sven): Maybe replace this by a list-override instead. + """ + + def __new__(cls, input_array): + # Use __new__ to create a new instance of our subclass. + obj = np.asarray(input_array).view(cls) + return obj + + +@DeveloperAPI +def get_original_space(space: gym.Space) -> gym.Space: + """Returns the original space of a space, if any. + + This function recursively traverses the given space and returns the original space + at the very end of the chain. + + Args: + space: The space to get the original space for. + + Returns: + The original space or the given space itself if no original space is found. + """ + if hasattr(space, "original_space"): + return get_original_space(space.original_space) + else: + return space + + +@DeveloperAPI +def is_composite_space(space: gym.Space) -> bool: + """Returns true, if the space is composite. + + Note, we follow here the glossary of `gymnasium` by which any spoace + that holds other spaces is defined as being 'composite'. + + Args: + space: The space to be checked for being composed of other spaces. + + Returns: + True, if the space is composed of other spaces, otherwise False. + """ + if type(space) in [ + gym.spaces.Dict, + gym.spaces.Graph, + gym.spaces.Sequence, + gym.spaces.Tuple, + ]: + return True + else: + return False + + +@DeveloperAPI +def to_jsonable_if_needed( + sample: Union[ActType, ObsType], space: gym.Space +) -> Union[ActType, ObsType, List]: + """Returns a jsonabled space sample, if the space is composite. + + Checks, if the space is composite and converts the sample to a jsonable + struct in this case. Otherwise return the sample as is. + + Args: + sample: Any action or observation type possible in `gymnasium`. + space: Any space defined in `gymnasium.spaces`. + + Returns: + The `sample` as-is, if the `space` is composite, otherwise converts the + composite sample to a JSONable data type. + """ + + if is_composite_space(space): + return space.to_jsonable([sample]) + else: + return sample + + +@DeveloperAPI +def from_jsonable_if_needed( + sample: Union[ActType, ObsType], space: gym.Space +) -> Union[ActType, ObsType, List]: + """Returns a jsonabled space sample, if the space is composite. + + Checks, if the space is composite and converts the sample to a JSONable + struct in this case. Otherwise return the sample as is. + + Args: + sample: Any action or observation type possible in `gymnasium`, or a + JSONable data type. + space: Any space defined in `gymnasium.spaces`. + + Returns: + The `sample` as-is, if the `space` is not composite, otherwise converts the + composite sample jsonable to an actual `space` sample.. + """ + + if is_composite_space(space): + return space.from_jsonable(sample)[0] + else: + return sample + + +@DeveloperAPI +def flatten_space(space: gym.Space) -> List[gym.Space]: + """Flattens a gym.Space into its primitive components. + + Primitive components are any non Tuple/Dict spaces. + + Args: + space: The gym.Space to flatten. This may be any + supported type (including nested Tuples and Dicts). + + Returns: + List[gym.Space]: The flattened list of primitive Spaces. This list + does not contain Tuples or Dicts anymore. + """ + + def _helper_flatten(space_, return_list): + from ray.rllib.utils.spaces.flexdict import FlexDict + + if isinstance(space_, Tuple): + for s in space_: + _helper_flatten(s, return_list) + elif isinstance(space_, (Dict, FlexDict)): + for k in sorted(space_.spaces): + _helper_flatten(space_[k], return_list) + else: + return_list.append(space_) + + ret = [] + _helper_flatten(space, ret) + return ret + + +@DeveloperAPI +def get_base_struct_from_space(space): + """Returns a Tuple/Dict Space as native (equally structured) py tuple/dict. + + Args: + space: The Space to get the python struct for. + + Returns: + Union[dict,tuple,gym.Space]: The struct equivalent to the given Space. + Note that the returned struct still contains all original + "primitive" Spaces (e.g. Box, Discrete). + + .. testcode:: + :skipif: True + + get_base_struct_from_space(Dict({ + "a": Box(), + "b": Tuple([Discrete(2), Discrete(3)]) + })) + + .. testoutput:: + + dict(a=Box(), b=tuple(Discrete(2), Discrete(3))) + """ + + def _helper_struct(space_): + if isinstance(space_, Tuple): + return tuple(_helper_struct(s) for s in space_) + elif isinstance(space_, Dict): + return {k: _helper_struct(space_[k]) for k in space_.spaces} + else: + return space_ + + return _helper_struct(space) + + +@DeveloperAPI +def get_dummy_batch_for_space( + space: gym.Space, + batch_size: int = 32, + *, + fill_value: Union[float, int, str] = 0.0, + time_size: Optional[int] = None, + time_major: bool = False, + one_hot_discrete: bool = False, +) -> np.ndarray: + """Returns batched dummy data (using `batch_size`) for the given `space`. + + Note: The returned batch will not pass a `space.contains(batch)` test + as an additional batch dimension has to be added at axis 0, unless `batch_size` is + set to 0. + + Args: + space: The space to get a dummy batch for. + batch_size: The required batch size (B). Note that this can also + be 0 (only if `time_size` is None!), which will result in a + non-batched sample for the given space (no batch dim). + fill_value: The value to fill the batch with + or "random" for random values. + time_size: If not None, add an optional time axis + of `time_size` size to the returned batch. This time axis might either + be inserted at axis=1 (default) or axis=0, if `time_major` is True. + time_major: If True AND `time_size` is not None, return batch + as shape [T x B x ...], otherwise as [B x T x ...]. If `time_size` + if None, ignore this setting and return [B x ...]. + one_hot_discrete: If True, will return one-hot vectors (instead of + int-values) for those sub-components of a (possibly complex) `space` + that are Discrete or MultiDiscrete. Note that in case `fill_value` is 0.0, + this will result in zero-hot vectors (where all slots have a value of 0.0). + + Returns: + The dummy batch of size `bqtch_size` matching the given space. + """ + # Complex spaces. Perform recursive calls of this function. + if isinstance(space, (gym.spaces.Dict, gym.spaces.Tuple, dict, tuple)): + base_struct = space + if isinstance(space, (gym.spaces.Dict, gym.spaces.Tuple)): + base_struct = get_base_struct_from_space(space) + return tree.map_structure( + lambda s: get_dummy_batch_for_space( + space=s, + batch_size=batch_size, + fill_value=fill_value, + time_size=time_size, + time_major=time_major, + one_hot_discrete=one_hot_discrete, + ), + base_struct, + ) + + if one_hot_discrete: + if isinstance(space, gym.spaces.Discrete): + space = gym.spaces.Box(0.0, 1.0, (space.n,), np.float32) + elif isinstance(space, gym.spaces.MultiDiscrete): + space = gym.spaces.Box(0.0, 1.0, (np.sum(space.nvec),), np.float32) + + # Primivite spaces: Box, Discrete, MultiDiscrete. + # Random values: Use gym's sample() method. + if fill_value == "random": + if time_size is not None: + assert batch_size > 0 and time_size > 0 + if time_major: + return np.array( + [ + [space.sample() for _ in range(batch_size)] + for t in range(time_size) + ], + dtype=space.dtype, + ) + else: + return np.array( + [ + [space.sample() for t in range(time_size)] + for _ in range(batch_size) + ], + dtype=space.dtype, + ) + else: + return np.array( + [space.sample() for _ in range(batch_size)] + if batch_size > 0 + else space.sample(), + dtype=space.dtype, + ) + # Fill value given: Use np.full. + else: + if time_size is not None: + assert batch_size > 0 and time_size > 0 + if time_major: + shape = [time_size, batch_size] + else: + shape = [batch_size, time_size] + else: + shape = [batch_size] if batch_size > 0 else [] + return np.full( + shape + list(space.shape), fill_value=fill_value, dtype=space.dtype + ) + + +@DeveloperAPI +def flatten_to_single_ndarray(input_): + """Returns a single np.ndarray given a list/tuple of np.ndarrays. + + Args: + input_ (Union[List[np.ndarray], np.ndarray]): The list of ndarrays or + a single ndarray. + + Returns: + np.ndarray: The result after concatenating all single arrays in input_. + + .. testcode:: + :skipif: True + + flatten_to_single_ndarray([ + np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]), + np.array([7, 8, 9]), + ]) + + .. testoutput:: + + np.array([ + 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 + ]) + """ + # Concatenate complex inputs. + if isinstance(input_, (list, tuple, dict)): + expanded = [] + for in_ in tree.flatten(input_): + expanded.append(np.reshape(in_, [-1])) + input_ = np.concatenate(expanded, axis=0).flatten() + return input_ + + +@DeveloperAPI +def batch( + list_of_structs: List[Any], + *, + individual_items_already_have_batch_dim: Union[bool, str] = False, +): + """Converts input from a list of (nested) structs to a (nested) struct of batches. + + Input: List of structs (each of these structs representing a single batch item). + [ + {"a": 1, "b": (4, 7.0)}, <- batch item 1 + {"a": 2, "b": (5, 8.0)}, <- batch item 2 + {"a": 3, "b": (6, 9.0)}, <- batch item 3 + ] + + Output: Struct of different batches (each batch has size=3 b/c there were 3 items + in the original list): + { + "a": np.array([1, 2, 3]), + "b": (np.array([4, 5, 6]), np.array([7.0, 8.0, 9.0])) + } + + Args: + list_of_structs: The list of (possibly nested) structs. Each item + in this list represents a single batch item. + individual_items_already_have_batch_dim: True, if the individual items in + `list_of_structs` already have a batch dim. In this case, we will + concatenate (instead of stack) at the end. In the example above, this would + look like this: Input: [{"a": [1], "b": ([4], [7.0])}, ...] -> Output: same + as in above example. + If the special value "auto" is used, + + Returns: + The struct of component batches. Each leaf item in this struct represents the + batch for a single component (in case struct is tuple/dict). If the input is a + simple list of primitive items, e.g. a list of floats, a np.array of floats + will be returned. + """ + if not list_of_structs: + raise ValueError("Input `list_of_structs` does not contain any items.") + + # TODO (sven): Maybe replace this by a list-override (usage of which indicated + # this method that concatenate should be used (not stack)). + if individual_items_already_have_batch_dim == "auto": + flat = tree.flatten(list_of_structs[0]) + individual_items_already_have_batch_dim = isinstance(flat[0], BatchedNdArray) + + np_func = np.concatenate if individual_items_already_have_batch_dim else np.stack + ret = tree.map_structure( + lambda *s: np.ascontiguousarray(np_func(s, axis=0)), *list_of_structs + ) + return ret + + +@DeveloperAPI +def unbatch(batches_struct): + """Converts input from (nested) struct of batches to batch of structs. + + Input: Struct of different batches (each batch has size=3): + { + "a": np.array([1, 2, 3]), + "b": (np.array([4, 5, 6]), np.array([7.0, 8.0, 9.0])) + } + Output: Batch (list) of structs (each of these structs representing a + single action): + [ + {"a": 1, "b": (4, 7.0)}, <- action 1 + {"a": 2, "b": (5, 8.0)}, <- action 2 + {"a": 3, "b": (6, 9.0)}, <- action 3 + ] + + Args: + batches_struct: The struct of component batches. Each leaf item + in this struct represents the batch for a single component + (in case struct is tuple/dict). + Alternatively, `batches_struct` may also simply be a batch of + primitives (non tuple/dict). + + Returns: + The list of individual structs. Each item in the returned list represents a + single (maybe complex) batch item. + """ + flat_batches = tree.flatten(batches_struct) + + out = [] + for batch_pos in range(len(flat_batches[0])): + out.append( + tree.unflatten_as( + batches_struct, + [flat_batches[i][batch_pos] for i in range(len(flat_batches))], + ) + ) + return out + + +@DeveloperAPI +def clip_action(action, action_space): + """Clips all components in `action` according to the given Space. + + Only applies to Box components within the action space. + + Args: + action: The action to be clipped. This could be any complex + action, e.g. a dict or tuple. + action_space: The action space struct, + e.g. `{"a": Distrete(2)}` for a space: Dict({"a": Discrete(2)}). + + Returns: + Any: The input action, but clipped by value according to the space's + bounds. + """ + + def map_(a, s): + if isinstance(s, gym.spaces.Box): + a = np.clip(a, s.low, s.high) + return a + + return tree.map_structure(map_, action, action_space) + + +@DeveloperAPI +def unsquash_action(action, action_space_struct): + """Unsquashes all components in `action` according to the given Space. + + Inverse of `normalize_action()`. Useful for mapping policy action + outputs (normalized between -1.0 and 1.0) to an env's action space. + Unsquashing results in cont. action component values between the + given Space's bounds (`low` and `high`). This only applies to Box + components within the action space, whose dtype is float32 or float64. + + Args: + action: The action to be unsquashed. This could be any complex + action, e.g. a dict or tuple. + action_space_struct: The action space struct, + e.g. `{"a": Box()}` for a space: Dict({"a": Box()}). + + Returns: + Any: The input action, but unsquashed, according to the space's + bounds. An unsquashed action is ready to be sent to the + environment (`BaseEnv.send_actions([unsquashed actions])`). + """ + + def map_(a, s): + if ( + isinstance(s, gym.spaces.Box) + and np.all(s.bounded_below) + and np.all(s.bounded_above) + ): + if s.dtype == np.float32 or s.dtype == np.float64: + # Assuming values are roughly between -1.0 and 1.0 -> + # unsquash them to the given bounds. + a = s.low + (a + 1.0) * (s.high - s.low) / 2.0 + # Clip to given bounds, just in case the squashed values were + # outside [-1.0, 1.0]. + a = np.clip(a, s.low, s.high) + elif np.issubdtype(s.dtype, np.integer): + # For Categorical and MultiCategorical actions, shift the selection + # into the proper range. + a = s.low + a + return a + + return tree.map_structure(map_, action, action_space_struct) + + +@DeveloperAPI +def normalize_action(action, action_space_struct): + """Normalizes all (Box) components in `action` to be in [-1.0, 1.0]. + + Inverse of `unsquash_action()`. Useful for mapping an env's action + (arbitrary bounded values) to a [-1.0, 1.0] interval. + This only applies to Box components within the action space, whose + dtype is float32 or float64. + + Args: + action: The action to be normalized. This could be any complex + action, e.g. a dict or tuple. + action_space_struct: The action space struct, + e.g. `{"a": Box()}` for a space: Dict({"a": Box()}). + + Returns: + Any: The input action, but normalized, according to the space's + bounds. + """ + + def map_(a, s): + if isinstance(s, gym.spaces.Box) and ( + s.dtype == np.float32 or s.dtype == np.float64 + ): + # Normalize values to be exactly between -1.0 and 1.0. + a = ((a - s.low) * 2.0) / (s.high - s.low) - 1.0 + return a + + return tree.map_structure(map_, action, action_space_struct) + + +@DeveloperAPI +def convert_element_to_space_type(element: Any, sampled_element: Any) -> Any: + """Convert all the components of the element to match the space dtypes. + + Args: + element: The element to be converted. + sampled_element: An element sampled from a space to be matched + to. + + Returns: + The input element, but with all its components converted to match + the space dtypes. + """ + + def map_(elem, s): + if isinstance(s, np.ndarray): + if not isinstance(elem, np.ndarray): + assert isinstance( + elem, (float, int) + ), f"ERROR: `elem` ({elem}) must be np.array, float or int!" + if s.shape == (): + elem = np.array(elem, dtype=s.dtype) + else: + raise ValueError( + "Element should be of type np.ndarray but is instead of \ + type {}".format( + type(elem) + ) + ) + elif s.dtype != elem.dtype: + elem = elem.astype(s.dtype) + + # Gymnasium now uses np.int_64 as the dtype of a Discrete action space + elif isinstance(s, int) or isinstance(s, np.int_): + if isinstance(elem, float) and elem.is_integer(): + elem = int(elem) + # Note: This does not check if the float element is actually an integer + if isinstance(elem, np.float_): + elem = np.int64(elem) + + return elem + + return tree.map_structure(map_, element, sampled_element, check_types=False) diff --git a/venv/lib/python3.10/site-packages/ray/runtime_env/__init__.py b/venv/lib/python3.10/site-packages/ray/runtime_env/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f401770d0ef075b7c733116b2e7f5ce14f5825e0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/runtime_env/__init__.py @@ -0,0 +1,8 @@ +from ray._private.runtime_env.mpi import mpi_init # noqa: E402,F401 +from ray.runtime_env.runtime_env import RuntimeEnv, RuntimeEnvConfig # noqa: E402,F401 + +__all__ = [ + "RuntimeEnvConfig", + "RuntimeEnv", + "mpi_init", +] diff --git a/venv/lib/python3.10/site-packages/ray/runtime_env/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/runtime_env/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c2606d1acb69961112d0011436a2b2af9cd7532 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/runtime_env/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/runtime_env/__pycache__/runtime_env.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/runtime_env/__pycache__/runtime_env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85bcf938d1b4a46613499017e0316630e8c27626 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/runtime_env/__pycache__/runtime_env.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/runtime_env/runtime_env.py b/venv/lib/python3.10/site-packages/ray/runtime_env/runtime_env.py new file mode 100644 index 0000000000000000000000000000000000000000..0682c48539fbb72237bcd9f42e0b39fd5325e9f7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/runtime_env/runtime_env.py @@ -0,0 +1,686 @@ +import json +import logging +import os +from copy import deepcopy +from dataclasses import asdict, is_dataclass +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union + +import ray +from ray._private.ray_constants import DEFAULT_RUNTIME_ENV_TIMEOUT_SECONDS +from ray._private.runtime_env.conda import get_uri as get_conda_uri +from ray._private.runtime_env.default_impl import get_image_uri_plugin_cls +from ray._private.runtime_env.pip import get_uri as get_pip_uri +from ray._private.runtime_env.plugin_schema_manager import RuntimeEnvPluginSchemaManager +from ray._private.runtime_env.uv import get_uri as get_uv_uri +from ray._private.runtime_env.validation import ( + OPTION_TO_VALIDATION_FN, + OPTION_TO_NO_PATH_VALIDATION_FN, +) +from ray._private.thirdparty.dacite import from_dict +from ray.core.generated.runtime_env_common_pb2 import ( + RuntimeEnvConfig as ProtoRuntimeEnvConfig, +) +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="stable") +class RuntimeEnvConfig(dict): + """Used to specify configuration options for a runtime environment. + + The config is not included when calculating the runtime_env hash, + which means that two runtime_envs with the same options but different + configs are considered the same for caching purposes. + + Args: + setup_timeout_seconds: The timeout of runtime environment + creation, timeout is in seconds. The value `-1` means disable + timeout logic, except `-1`, `setup_timeout_seconds` cannot be + less than or equal to 0. The default value of `setup_timeout_seconds` + is 600 seconds. + eager_install: Indicates whether to install the runtime environment + on the cluster at `ray.init()` time, before the workers are leased. + This flag is set to `True` by default. + """ + + known_fields: Set[str] = {"setup_timeout_seconds", "eager_install", "log_files"} + + _default_config: Dict = { + "setup_timeout_seconds": DEFAULT_RUNTIME_ENV_TIMEOUT_SECONDS, + "eager_install": True, + "log_files": [], + } + + def __init__( + self, + setup_timeout_seconds: int = DEFAULT_RUNTIME_ENV_TIMEOUT_SECONDS, + eager_install: bool = True, + log_files: Optional[List[str]] = None, + ): + super().__init__() + if not isinstance(setup_timeout_seconds, int): + raise TypeError( + "setup_timeout_seconds must be of type int, " + f"got: {type(setup_timeout_seconds)}" + ) + elif setup_timeout_seconds <= 0 and setup_timeout_seconds != -1: + raise ValueError( + "setup_timeout_seconds must be greater than zero " + f"or equals to -1, got: {setup_timeout_seconds}" + ) + self["setup_timeout_seconds"] = setup_timeout_seconds + + if not isinstance(eager_install, bool): + raise TypeError( + f"eager_install must be a boolean. got {type(eager_install)}" + ) + self["eager_install"] = eager_install + + if log_files is not None: + if not isinstance(log_files, list): + raise TypeError( + "log_files must be a list of strings or None, got " + f"{log_files} with type {type(log_files)}." + ) + for file_name in log_files: + if not isinstance(file_name, str): + raise TypeError("Each item in log_files must be a string.") + else: + log_files = self._default_config["log_files"] + + self["log_files"] = log_files + + @staticmethod + def parse_and_validate_runtime_env_config( + config: Union[Dict, "RuntimeEnvConfig"] + ) -> "RuntimeEnvConfig": + if isinstance(config, RuntimeEnvConfig): + return config + elif isinstance(config, Dict): + unknown_fields = set(config.keys()) - RuntimeEnvConfig.known_fields + if len(unknown_fields): + logger.warning( + "The following unknown entries in the runtime_env_config " + f"dictionary will be ignored: {unknown_fields}." + ) + config_dict = dict() + for field in RuntimeEnvConfig.known_fields: + if field in config: + config_dict[field] = config[field] + return RuntimeEnvConfig(**config_dict) + else: + raise TypeError( + "runtime_env['config'] must be of type dict or RuntimeEnvConfig, " + f"got: {type(config)}" + ) + + @classmethod + def default_config(cls): + return RuntimeEnvConfig(**cls._default_config) + + def build_proto_runtime_env_config(self) -> ProtoRuntimeEnvConfig: + runtime_env_config = ProtoRuntimeEnvConfig() + runtime_env_config.setup_timeout_seconds = self["setup_timeout_seconds"] + runtime_env_config.eager_install = self["eager_install"] + if self["log_files"] is not None: + runtime_env_config.log_files.extend(self["log_files"]) + return runtime_env_config + + @classmethod + def from_proto(cls, runtime_env_config: ProtoRuntimeEnvConfig): + setup_timeout_seconds = runtime_env_config.setup_timeout_seconds + # Cause python class RuntimeEnvConfig has validate to avoid + # setup_timeout_seconds equals zero, so setup_timeout_seconds + # on RuntimeEnvConfig is zero means other Language(except python) + # dosn't assign value to setup_timeout_seconds. So runtime_env_agent + # assign the default value to setup_timeout_seconds. + if setup_timeout_seconds == 0: + setup_timeout_seconds = cls._default_config["setup_timeout_seconds"] + return cls( + setup_timeout_seconds=setup_timeout_seconds, + eager_install=runtime_env_config.eager_install, + log_files=list(runtime_env_config.log_files), + ) + + def to_dict(self) -> Dict: + return dict(deepcopy(self)) + + +# Due to circular reference, field config can only be assigned a value here +OPTION_TO_VALIDATION_FN[ + "config" +] = RuntimeEnvConfig.parse_and_validate_runtime_env_config + + +@PublicAPI +class RuntimeEnv(dict): + """This class is used to define a runtime environment for a job, task, + or actor. + + See :ref:`runtime-environments` for detailed documentation. + + This class can be used interchangeably with an unstructured dictionary + in the relevant API calls. + + Can specify a runtime environment whole job, whether running a script + directly on the cluster, using Ray Job submission, or using Ray Client: + + .. code-block:: python + + from ray.runtime_env import RuntimeEnv + # Starting a single-node local Ray cluster + ray.init(runtime_env=RuntimeEnv(...)) + + .. code-block:: python + + from ray.runtime_env import RuntimeEnv + # Connecting to remote cluster using Ray Client + ray.init("ray://123.456.7.89:10001", runtime_env=RuntimeEnv(...)) + + Can specify different runtime environments per-actor or per-task using + ``.options()`` or the ``@ray.remote`` decorator: + + .. code-block:: python + + from ray.runtime_env import RuntimeEnv + # Invoke a remote task that runs in a specified runtime environment. + f.options(runtime_env=RuntimeEnv(...)).remote() + + # Instantiate an actor that runs in a specified runtime environment. + actor = SomeClass.options(runtime_env=RuntimeEnv(...)).remote() + + # Specify a runtime environment in the task definition. Future invocations via + # `g.remote()` use this runtime environment unless overridden by using + # `.options()` as above. + @ray.remote(runtime_env=RuntimeEnv(...)) + def g(): + pass + + # Specify a runtime environment in the actor definition. Future instantiations + # via `MyClass.remote()` use this runtime environment unless overridden by + # using `.options()` as above. + @ray.remote(runtime_env=RuntimeEnv(...)) + class MyClass: + pass + + Here are some examples of RuntimeEnv initialization: + + .. code-block:: python + + # Example for using conda + RuntimeEnv(conda={ + "channels": ["defaults"], "dependencies": ["codecov"]}) + RuntimeEnv(conda="pytorch_p36") # Found on DLAMIs + + # Example for using container + RuntimeEnv( + container={"image": "anyscale/ray-ml:nightly-py38-cpu", + "run_options": ["--cap-drop SYS_ADMIN","--log-level=debug"]}) + + # Example for set env_vars + RuntimeEnv(env_vars={"OMP_NUM_THREADS": "32", "TF_WARNINGS": "none"}) + + # Example for set pip + RuntimeEnv( + pip={"packages":["tensorflow", "requests"], "pip_check": False, + "pip_version": "==22.0.2;python_version=='3.8.11'"}) + + # Example for using image_uri + RuntimeEnv( + image_uri="rayproject/ray:2.39.0-py312-cu123") + + Args: + py_modules: List of local paths or remote URIs (either in the GCS or external + storage), each of which is a zip file that Ray unpacks and + inserts into the PYTHONPATH of the workers. + working_dir: Local path or remote URI (either in the GCS or external storage) of a zip + file that Ray unpacks in the directory of each task/actor. + pip: Either a list of pip packages, a string + containing the path to a pip requirements.txt file, or a Python + dictionary that has three fields: 1) ``packages`` (required, List[str]): a + list of pip packages, 2) ``pip_check`` (optional, bool): whether enable + pip check at the end of pip install, defaults to False. + 3) ``pip_version`` (optional, str): the version of pip, Ray prepends + the package name "pip" in front of the ``pip_version`` to form the final + requirement string, the syntax of a requirement specifier is defined in + full in PEP 508. + uv: Either a list of pip packages, or a Python dictionary that has one field: + 1) ``packages`` (required, List[str]). + conda: Either the conda YAML config, the name of a + local conda env (e.g., "pytorch_p36"), or the path to a conda + environment.yaml file. + Ray automatically injects the dependency into the conda + env to ensure compatibility with the cluster Ray. Ray may automatically + mangle the conda name to avoid conflicts between runtime envs. + This field can't be specified at the same time as the 'pip' field. + To use pip with conda, specify your pip dependencies within + the conda YAML config: + https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#create-env-file-manually + container: Require a given (Docker) container image, + The Ray worker process runs in a container with this image. + This parameter only works alone, or with the ``config`` or + ``env_vars`` parameters. + The `run_options` list spec is here: + https://docs.docker.com/engine/reference/run/ + env_vars: Environment variables to set. + worker_process_setup_hook: (Experimental) The setup hook that's + called after workers start and before Tasks and Actors are scheduled. + A module name (string type) or callable (function) can be passed. + When a module name is passed, Ray worker should be able to access the + module name. When a callable is passed, callable should be serializable. + When a runtime env is specified by job submission API, + only a module name (string) is allowed. + nsight: Dictionary mapping nsight profile option name to it's value. + rocprof_sys: Dictionary mapping rocprof-sys profile option name and environment + variables to it's value. + config: config for runtime environment. Either + a dict or a RuntimeEnvConfig. Field: (1) setup_timeout_seconds, the + timeout of runtime environment creation, timeout is in seconds. + image_uri: URI to a container image. The Ray worker process runs + in a container with this image. This parameter only works alone, + or with the ``config`` or ``env_vars`` parameters. + """ + + known_fields: Set[str] = { + "py_modules", + "py_executable", + "java_jars", + "working_dir", + "conda", + "pip", + "uv", + "container", + "excludes", + "env_vars", + "_ray_release", + "_ray_commit", + "_inject_current_ray", + "config", + "worker_process_setup_hook", + "_nsight", + "_rocprof_sys", + "mpi", + "image_uri", + } + + extensions_fields: Set[str] = { + "_ray_release", + "_ray_commit", + "_inject_current_ray", + } + + def __init__( + self, + *, + py_modules: Optional[List[str]] = None, + py_executable: Optional[str] = None, + working_dir: Optional[str] = None, + pip: Optional[List[str]] = None, + conda: Optional[Union[Dict[str, str], str]] = None, + container: Optional[Dict[str, str]] = None, + env_vars: Optional[Dict[str, str]] = None, + worker_process_setup_hook: Optional[Union[Callable, str]] = None, + nsight: Optional[Union[str, Dict[str, str]]] = None, + rocprof_sys: Optional[Union[str, Dict[str, Dict[str, str]]]] = None, + config: Optional[Union[Dict, RuntimeEnvConfig]] = None, + _validate: bool = True, + mpi: Optional[Dict] = None, + image_uri: Optional[str] = None, + uv: Optional[List[str]] = None, + **kwargs, + ): + super().__init__() + + runtime_env = kwargs + if py_modules is not None: + runtime_env["py_modules"] = py_modules + if py_executable is not None: + runtime_env["py_executable"] = py_executable + if working_dir is not None: + runtime_env["working_dir"] = working_dir + if pip is not None: + runtime_env["pip"] = pip + if uv is not None: + runtime_env["uv"] = uv + if conda is not None: + runtime_env["conda"] = conda + if nsight is not None: + runtime_env["_nsight"] = nsight + if rocprof_sys is not None: + runtime_env["_rocprof_sys"] = rocprof_sys + if container is not None: + runtime_env["container"] = container + if env_vars is not None: + runtime_env["env_vars"] = env_vars + if config is not None: + runtime_env["config"] = config + if worker_process_setup_hook is not None: + runtime_env["worker_process_setup_hook"] = worker_process_setup_hook + if mpi is not None: + runtime_env["mpi"] = mpi + if image_uri is not None: + runtime_env["image_uri"] = image_uri + + self.update(runtime_env) + + # Blindly trust that the runtime_env has already been validated. + # This is dangerous and should only be used internally (e.g., on the + # deserialization codepath. + if not _validate: + return + + if (self.get("conda") is not None) + (self.get("pip") is not None) + ( + self.get("uv") is not None + ) > 1: + raise ValueError( + "The 'pip' field, 'uv' field, and 'conda' field of " + "runtime_env cannot be specified at the same time.\n" + f"specified pip field: {self.get('pip')}\n" + f"specified conda field: {self.get('conda')}\n" + f"specified uv field: {self.get('uv')}\n" + "To use pip with conda, please only set the 'conda'" + "field, and specify your pip dependencies within the conda YAML " + "config dict: see https://conda.io/projects/conda/en/latest/" + "user-guide/tasks/manage-environments.html" + "#create-env-file-manually" + ) + + if self.get("container"): + invalid_keys = set(runtime_env.keys()) - {"container", "config", "env_vars"} + if len(invalid_keys): + raise ValueError( + "The 'container' field currently cannot be used " + "together with other fields of runtime_env. " + f"Specified fields: {invalid_keys}" + ) + + logger.warning( + "The `container` runtime environment field is DEPRECATED and will be " + "removed after July 31, 2025. Use `image_uri` instead. See " + "https://docs.ray.io/en/latest/serve/advanced-guides/multi-app-container.html." # noqa + ) + + if self.get("image_uri"): + image_uri_plugin_cls = get_image_uri_plugin_cls() + invalid_keys = ( + set(runtime_env.keys()) - image_uri_plugin_cls.get_compatible_keys() + ) + if len(invalid_keys): + raise ValueError( + "The 'image_uri' field currently cannot be used " + "together with other fields of runtime_env. " + f"Specified fields: {invalid_keys}" + ) + + for option, validate_fn in OPTION_TO_VALIDATION_FN.items(): + option_val = self.get(option) + if option_val is not None: + del self[option] + self[option] = option_val + + if "_ray_commit" not in self: + if self.get("pip") or self.get("conda"): + self["_ray_commit"] = ray.__commit__ + + # Used for testing wheels that have not yet been merged into master. + # If this is set to True, then we do not inject Ray into the conda + # or pip dependencies. + if "_inject_current_ray" not in self: + if "RAY_RUNTIME_ENV_LOCAL_DEV_MODE" in os.environ: + self["_inject_current_ray"] = True + + # NOTE(architkulkarni): This allows worker caching code in C++ to check + # if a runtime env is empty without deserializing it. This is a catch- + # all; for validated inputs we won't set the key if the value is None. + if all(val is None for val in self.values()): + self.clear() + + def __setitem__(self, key: str, value: Any) -> None: + if is_dataclass(value): + jsonable_type = asdict(value) + else: + jsonable_type = value + RuntimeEnvPluginSchemaManager.validate(key, jsonable_type) + res_value = jsonable_type + if key in RuntimeEnv.known_fields and key in OPTION_TO_VALIDATION_FN: + res_value = OPTION_TO_VALIDATION_FN[key](jsonable_type) + if res_value is None: + return + return super().__setitem__(key, res_value) + + def set(self, name: str, value: Any) -> None: + self.__setitem__(name, value) + + def get(self, name, default=None, data_class=None): + if name not in self: + return default + if not data_class: + return self.__getitem__(name) + else: + return from_dict(data_class=data_class, data=self.__getitem__(name)) + + @classmethod + def deserialize(cls, serialized_runtime_env: str) -> "RuntimeEnv": # noqa: F821 + return cls(_validate=False, **json.loads(serialized_runtime_env)) + + def serialize(self) -> str: + # To ensure the accuracy of Proto, `__setitem__` can only guarantee the + # accuracy of a certain field, not the overall accuracy + runtime_env = type(self)(_validate=True, **self) + return json.dumps( + runtime_env, + sort_keys=True, + ) + + def to_dict(self) -> Dict: + runtime_env_dict = dict(deepcopy(self)) + + # Replace strongly-typed RuntimeEnvConfig with a dict to allow the returned + # dict to work properly as a field in a dataclass. Details in issue #26986 + if runtime_env_dict.get("config"): + runtime_env_dict["config"] = runtime_env_dict["config"].to_dict() + + return runtime_env_dict + + def has_working_dir(self) -> bool: + return self.get("working_dir") is not None + + def working_dir_uri(self) -> Optional[str]: + return self.get("working_dir") + + def py_modules_uris(self) -> List[str]: + if "py_modules" in self: + return list(self["py_modules"]) + return [] + + def conda_uri(self) -> Optional[str]: + if "conda" in self: + return get_conda_uri(self) + return None + + def pip_uri(self) -> Optional[str]: + if "pip" in self: + return get_pip_uri(self) + return None + + def uv_uri(self) -> Optional[str]: + if "uv" in self: + return get_uv_uri(self) + return None + + def plugin_uris(self) -> List[str]: + """Not implemented yet, always return a empty list""" + return [] + + def working_dir(self) -> str: + return self.get("working_dir", "") + + def py_modules(self) -> List[str]: + if "py_modules" in self: + return list(self["py_modules"]) + return [] + + def py_executable(self) -> Optional[str]: + return self.get("py_executable", None) + + def java_jars(self) -> List[str]: + if "java_jars" in self: + return list(self["java_jars"]) + return [] + + def mpi(self) -> Optional[Union[str, Dict[str, str]]]: + return self.get("mpi", None) + + def nsight(self) -> Optional[Union[str, Dict[str, str]]]: + return self.get("_nsight", None) + + def rocprof_sys(self) -> Optional[Union[str, Dict[str, Dict[str, str]]]]: + return self.get("_rocprof_sys", None) + + def env_vars(self) -> Dict: + return self.get("env_vars", {}) + + def has_conda(self) -> str: + if self.get("conda"): + return True + return False + + def conda_env_name(self) -> str: + if not self.has_conda() or not isinstance(self["conda"], str): + return None + return self["conda"] + + def conda_config(self) -> str: + if not self.has_conda() or not isinstance(self["conda"], dict): + return None + return json.dumps(self["conda"], sort_keys=True) + + def has_pip(self) -> bool: + if self.get("pip"): + return True + return False + + def has_uv(self) -> bool: + if self.get("uv"): + return True + return False + + def virtualenv_name(self) -> Optional[str]: + if not self.has_pip() or not isinstance(self["pip"], str): + return None + return self["pip"] + + def pip_config(self) -> Dict: + if not self.has_pip() or isinstance(self["pip"], str): + return {} + # Parse and validate field pip on method `__setitem__` + self["pip"] = self["pip"] + return self["pip"] + + def uv_config(self) -> Dict: + if not self.has_uv() or isinstance(self["uv"], str): + return {} + # Parse and validate field pip on method `__setitem__` + self["uv"] = self["uv"] + return self["uv"] + + def get_extension(self, key) -> Optional[str]: + if key not in RuntimeEnv.extensions_fields: + raise ValueError( + f"Extension key must be one of {RuntimeEnv.extensions_fields}, " + f"got: {key}" + ) + return self.get(key) + + def has_py_container(self) -> bool: + if self.get("container"): + return True + return False + + def py_container_image(self) -> Optional[str]: + if not self.has_py_container(): + return None + return self["container"].get("image", "") + + def py_container_worker_path(self) -> Optional[str]: + if not self.has_py_container(): + return None + return self["container"].get("worker_path", "") + + def py_container_run_options(self) -> List: + if not self.has_py_container(): + return None + return self["container"].get("run_options", []) + + def image_uri(self) -> Optional[str]: + return self.get("image_uri") + + def plugins(self) -> List[Tuple[str, Any]]: + result = list() + for key, value in self.items(): + if key not in self.known_fields: + result.append((key, value)) + return result + + +def _validate_no_local_paths(runtime_env: RuntimeEnv): + """Checks that options such as working_dir and py_modules only contain URIs.""" + if not isinstance(runtime_env, RuntimeEnv): + raise TypeError( + f"Expected type to be RuntimeEnv but received {type(runtime_env)} instead." + ) + for option, validate_fn in OPTION_TO_NO_PATH_VALIDATION_FN.items(): + option_val = runtime_env.get(option) + if option_val: + validate_fn(option_val) + + +def _merge_runtime_env( + parent: Optional[RuntimeEnv], + child: Optional[RuntimeEnv], + override: bool = False, +) -> Optional[RuntimeEnv]: + """Merge the parent and child runtime environments. + + If override = True, the child's runtime env overrides the parent's + runtime env in the event of a conflict. + + Merging happens per key (i.e., "conda", "pip", ...), but + "env_vars" are merged per env var key. + + It returns None if Ray fails to merge runtime environments because + of a conflict and `override = False`. + + Args: + parent: Parent runtime env. + child: Child runtime env. + override: If True, the child's runtime env overrides + conflicting fields. + Returns: + The merged runtime env's if Ray successfully merges them. + None if the runtime env's conflict. Empty dict if + parent and child are both None. + """ + if parent is None: + parent = {} + if child is None: + child = {} + + parent = deepcopy(parent) + child = deepcopy(child) + parent_env_vars = parent.pop("env_vars", {}) + child_env_vars = child.pop("env_vars", {}) + + if not override: + if set(parent.keys()).intersection(set(child.keys())): + return None + if set(parent_env_vars.keys()).intersection(set(child_env_vars.keys())): # noqa + return None + + parent.update(child) + parent_env_vars.update(child_env_vars) + if parent_env_vars: + parent["env_vars"] = parent_env_vars + + return parent diff --git a/venv/lib/python3.10/site-packages/ray/scripts/__init__.py b/venv/lib/python3.10/site-packages/ray/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/scripts/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/scripts/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ab21bc5c65e0b72cd26f5a1837bad0b627bf9ae Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/scripts/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/scripts/__pycache__/scripts.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/scripts/__pycache__/scripts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5bcb39c5019c131ab97cac4042fc4cf1831cc30 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/scripts/__pycache__/scripts.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/scripts/scripts.py b/venv/lib/python3.10/site-packages/ray/scripts/scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..76bf5958d9b160db6b82b4deea1b1ea562c97c6f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/scripts/scripts.py @@ -0,0 +1,2746 @@ +import copy +import json +import logging +import os +import platform +import signal +import subprocess +import sys +import time +import urllib +import urllib.parse +import warnings +import shutil +from datetime import datetime +from typing import Optional, Set, List, Tuple +from ray._common.utils import load_class +from ray.dashboard.modules.metrics import install_and_start_prometheus +from ray.util.check_open_ports import check_open_ports +import requests + +import click +import colorama +import psutil +import yaml + +import ray +import ray._private.ray_constants as ray_constants +import ray._private.services as services +from ray._private.label_utils import ( + parse_node_labels_json, + parse_node_labels_from_yaml_file, + parse_node_labels_string, +) +from ray._private.utils import ( + check_ray_client_dependencies_installed, + parse_resources_json, +) +from ray._private.internal_api import memory_summary +from ray._private.usage import usage_lib +import ray._private.usage.usage_constants as usage_constant +from ray.autoscaler._private.cli_logger import add_click_logging_options, cf, cli_logger +from ray.autoscaler._private.commands import ( + RUN_ENV_TYPES, + attach_cluster, + create_or_update_cluster, + debug_status, + exec_cluster, + get_cluster_dump_archive, + get_head_node_ip, + get_local_dump_archive, + get_worker_node_ips, + kill_node, + monitor_cluster, + rsync, + teardown_cluster, +) +from ray.autoscaler._private.constants import RAY_PROCESSES +from ray.autoscaler._private.fake_multi_node.node_provider import FAKE_HEAD_NODE_ID +from ray.util.annotations import PublicAPI +from ray.core.generated import autoscaler_pb2 +from ray._private.resource_isolation_config import ResourceIsolationConfig + + +logger = logging.getLogger(__name__) + + +def _check_ray_version(gcs_client): + import ray._private.usage.usage_lib as ray_usage_lib + + cluster_metadata = ray_usage_lib.get_cluster_metadata(gcs_client) + if cluster_metadata and cluster_metadata["ray_version"] != ray.__version__: + raise RuntimeError( + "Ray version mismatch: cluster has Ray version " + f'{cluster_metadata["ray_version"]} ' + f"but local Ray version is {ray.__version__}" + ) + + +@click.group() +@click.option( + "--logging-level", + required=False, + default=ray_constants.LOGGER_LEVEL, + type=str, + help=ray_constants.LOGGER_LEVEL_HELP, +) +@click.option( + "--logging-format", + required=False, + default=ray_constants.LOGGER_FORMAT, + type=str, + help=ray_constants.LOGGER_FORMAT_HELP, +) +@click.version_option() +def cli(logging_level, logging_format): + level = logging.getLevelName(logging_level.upper()) + ray._private.ray_logging.setup_logger(level, logging_format) + cli_logger.set_format(format_tmpl=logging_format) + + +@click.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--port", + "-p", + required=False, + type=int, + default=ray_constants.DEFAULT_DASHBOARD_PORT, + help="The local port to forward to the dashboard", +) +@click.option( + "--remote-port", + required=False, + type=int, + default=ray_constants.DEFAULT_DASHBOARD_PORT, + help="The remote port your dashboard runs on", +) +@click.option( + "--no-config-cache", + is_flag=True, + default=False, + help="Disable the local cluster config cache.", +) +@PublicAPI +def dashboard(cluster_config_file, cluster_name, port, remote_port, no_config_cache): + """Port-forward a Ray cluster's dashboard to the local machine.""" + # Sleeping in a loop is preferable to `sleep infinity` because the latter + # only works on linux. + # Find the first open port sequentially from `remote_port`. + try: + port_forward = [ + (port, remote_port), + ] + click.echo( + "Attempting to establish dashboard locally at" + " http://localhost:{}/ connected to" + " remote port {}".format(port, remote_port) + ) + # We want to probe with a no-op that returns quickly to avoid + # exceptions caused by network errors. + exec_cluster( + cluster_config_file, + override_cluster_name=cluster_name, + port_forward=port_forward, + no_config_cache=no_config_cache, + ) + click.echo("Successfully established connection.") + except Exception as e: + raise click.ClickException( + "Failed to forward dashboard from remote port {1} to local port " + "{0}. There are a couple possibilities: \n 1. The remote port is " + "incorrectly specified \n 2. The local port {0} is already in " + "use.\n The exception is: {2}".format(port, remote_port, e) + ) from None + + +def continue_debug_session(live_jobs: Set[str]): + """Continue active debugging session. + + This function will connect 'ray debug' to the right debugger + when a user is stepping between Ray tasks. + """ + active_sessions = ray.experimental.internal_kv._internal_kv_list( + "RAY_PDB_", namespace=ray_constants.KV_NAMESPACE_PDB + ) + + for active_session in active_sessions: + if active_session.startswith(b"RAY_PDB_CONTINUE"): + # Check to see that the relevant job is still alive. + data = ray.experimental.internal_kv._internal_kv_get( + active_session, namespace=ray_constants.KV_NAMESPACE_PDB + ) + if json.loads(data)["job_id"] not in live_jobs: + ray.experimental.internal_kv._internal_kv_del( + active_session, namespace=ray_constants.KV_NAMESPACE_PDB + ) + continue + + print("Continuing pdb session in different process...") + key = b"RAY_PDB_" + active_session[len("RAY_PDB_CONTINUE_") :] + while True: + data = ray.experimental.internal_kv._internal_kv_get( + key, namespace=ray_constants.KV_NAMESPACE_PDB + ) + if data: + session = json.loads(data) + if "exit_debugger" in session or session["job_id"] not in live_jobs: + ray.experimental.internal_kv._internal_kv_del( + key, namespace=ray_constants.KV_NAMESPACE_PDB + ) + return + host, port = session["pdb_address"].split(":") + ray.util.rpdb._connect_pdb_client(host, int(port)) + ray.experimental.internal_kv._internal_kv_del( + key, namespace=ray_constants.KV_NAMESPACE_PDB + ) + continue_debug_session(live_jobs) + return + time.sleep(1.0) + + +def none_to_empty(s): + if s is None: + return "" + return s + + +def format_table(table): + """Format a table as a list of lines with aligned columns.""" + result = [] + col_width = [max(len(x) for x in col) for col in zip(*table)] + for line in table: + result.append( + " | ".join("{0:{1}}".format(x, col_width[i]) for i, x in enumerate(line)) + ) + return result + + +@cli.command() +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +@click.option( + "-v", + "--verbose", + required=False, + is_flag=True, + help="Shows additional fields in breakpoint selection page.", +) +def debug(address: str, verbose: bool): + """Show all active breakpoints and exceptions in the Ray debugger.""" + address = services.canonicalize_bootstrap_address_or_die(address) + logger.info(f"Connecting to Ray instance at {address}.") + ray.init(address=address, log_to_driver=False) + if os.environ.get("RAY_DEBUG", "1") != "legacy": + print( + f"{colorama.Fore.YELLOW}NOTE: The distributed debugger " + "https://docs.ray.io/en/latest/ray-observability" + "/ray-distributed-debugger.html is now the default " + "due to better interactive debugging support. If you want " + "to keep using 'ray debug' please set RAY_DEBUG=legacy " + f"in your cluster (e.g. via runtime environment).{colorama.Fore.RESET}" + ) + while True: + # Used to filter out and clean up entries from dead jobs. + live_jobs = { + job["JobID"] for job in ray._private.state.jobs() if not job["IsDead"] + } + continue_debug_session(live_jobs) + + active_sessions = ray.experimental.internal_kv._internal_kv_list( + "RAY_PDB_", namespace=ray_constants.KV_NAMESPACE_PDB + ) + print("Active breakpoints:") + sessions_data = [] + for active_session in active_sessions: + data = json.loads( + ray.experimental.internal_kv._internal_kv_get( + active_session, namespace=ray_constants.KV_NAMESPACE_PDB + ) + ) + # Check that the relevant job is alive, else clean up the entry. + if data["job_id"] in live_jobs: + sessions_data.append(data) + else: + ray.experimental.internal_kv._internal_kv_del( + active_session, namespace=ray_constants.KV_NAMESPACE_PDB + ) + sessions_data = sorted( + sessions_data, key=lambda data: data["timestamp"], reverse=True + ) + if verbose: + table = [ + [ + "index", + "timestamp", + "Ray task", + "filename:lineno", + "Task ID", + "Worker ID", + "Actor ID", + "Node ID", + ] + ] + for i, data in enumerate(sessions_data): + date = datetime.utcfromtimestamp(data["timestamp"]).strftime( + "%Y-%m-%d %H:%M:%S" + ) + table.append( + [ + str(i), + date, + data["proctitle"], + data["filename"] + ":" + str(data["lineno"]), + data["task_id"], + data["worker_id"], + none_to_empty(data["actor_id"]), + data["node_id"], + ] + ) + else: + # Non verbose mode: no IDs. + table = [["index", "timestamp", "Ray task", "filename:lineno"]] + for i, data in enumerate(sessions_data): + date = datetime.utcfromtimestamp(data["timestamp"]).strftime( + "%Y-%m-%d %H:%M:%S" + ) + table.append( + [ + str(i), + date, + data["proctitle"], + data["filename"] + ":" + str(data["lineno"]), + ] + ) + for i, line in enumerate(format_table(table)): + print(line) + if i >= 1 and not sessions_data[i - 1]["traceback"].startswith( + "NoneType: None" + ): + print(sessions_data[i - 1]["traceback"]) + inp = input("Enter breakpoint index or press enter to refresh: ") + if inp == "": + print() + continue + else: + index = int(inp) + session = json.loads( + ray.experimental.internal_kv._internal_kv_get( + active_sessions[index], namespace=ray_constants.KV_NAMESPACE_PDB + ) + ) + host, port = session["pdb_address"].split(":") + ray.util.rpdb._connect_pdb_client(host, int(port)) + + +@cli.command() +@click.option( + "--node-ip-address", required=False, type=str, help="the IP address of this node" +) +@click.option("--address", required=False, type=str, help="the address to use for Ray") +@click.option( + "--port", + type=int, + required=False, + help=f"the port of the head ray process. If not provided, defaults to " + f"{ray_constants.DEFAULT_PORT}; if port is set to 0, we will" + f" allocate an available port.", +) +@click.option( + "--node-name", + required=False, + hidden=True, + type=str, + help="the user-provided identifier or name for this node. " + "Defaults to the node's ip_address", +) +@click.option( + "--redis-username", + required=False, + hidden=True, + type=str, + default=ray_constants.REDIS_DEFAULT_USERNAME, + help="If provided, secure Redis ports with this username", +) +@click.option( + "--redis-password", + required=False, + hidden=True, + type=str, + default=ray_constants.REDIS_DEFAULT_PASSWORD, + help="If provided, secure Redis ports with this password", +) +@click.option( + "--redis-shard-ports", + required=False, + hidden=True, + type=str, + help="the port to use for the Redis shards other than the primary Redis shard", +) +@click.option( + "--object-manager-port", + required=False, + type=int, + help="the port to use for starting the object manager", +) +@click.option( + "--node-manager-port", + required=False, + type=int, + default=0, + help="the port to use for starting the node manager", +) +@click.option( + "--min-worker-port", + required=False, + type=int, + default=10002, + help="the lowest port number that workers will bind on. If not set, " + "random ports will be chosen.", +) +@click.option( + "--max-worker-port", + required=False, + type=int, + default=19999, + help="the highest port number that workers will bind on. If set, " + "'--min-worker-port' must also be set.", +) +@click.option( + "--worker-port-list", + required=False, + help="a comma-separated list of open ports for workers to bind on. " + "Overrides '--min-worker-port' and '--max-worker-port'.", +) +@click.option( + "--ray-client-server-port", + required=False, + type=int, + default=None, + help="the port number the ray client server binds on, default to 10001, " + "or None if ray[client] is not installed.", +) +@click.option( + "--memory", + required=False, + hidden=True, + type=int, + help="The amount of memory (in bytes) to make available to workers. " + "By default, this is set to the available memory on the node.", +) +@click.option( + "--object-store-memory", + required=False, + type=int, + help="The amount of memory (in bytes) to start the object store with. " + "By default, this is 30% of available system memory capped by " + "the shm size and 200G but can be set higher.", +) +@click.option( + "--num-cpus", required=False, type=int, help="the number of CPUs on this node" +) +@click.option( + "--num-gpus", required=False, type=int, help="the number of GPUs on this node" +) +@click.option( + "--resources", + required=False, + default="{}", + type=str, + help="A JSON serialized dictionary mapping resource name to resource quantity." + + ( + r""" + +Windows command prompt users must ensure to double quote command line arguments. Because +JSON requires the use of double quotes you must escape these arguments as well, for +example: + + ray start --head --resources="{\"special_hardware\":1, \"custom_label\":1}" + +Windows powershell users need additional escaping: + + ray start --head --resources="{\""special_hardware\"":1, \""custom_label\"":1}" +""" + if platform.system() == "Windows" + else "" + ), +) +@click.option( + "--head", + is_flag=True, + default=False, + help="provide this argument for the head node", +) +@click.option( + "--include-dashboard", + default=None, + type=bool, + help="provide this argument to start the Ray dashboard GUI", +) +@click.option( + "--dashboard-host", + required=False, + default=ray_constants.DEFAULT_DASHBOARD_IP, + help="the host to bind the dashboard server to, either localhost " + "(127.0.0.1) or 0.0.0.0 (available from all interfaces). By default, this " + "is 127.0.0.1", +) +@click.option( + "--dashboard-port", + required=False, + type=int, + default=ray_constants.DEFAULT_DASHBOARD_PORT, + help="the port to bind the dashboard server to--defaults to {}".format( + ray_constants.DEFAULT_DASHBOARD_PORT + ), +) +@click.option( + "--dashboard-agent-listen-port", + type=int, + default=ray_constants.DEFAULT_DASHBOARD_AGENT_LISTEN_PORT, + help="the port for dashboard agents to listen for http on.", +) +@click.option( + "--dashboard-agent-grpc-port", + type=int, + default=None, + help="the port for dashboard agents to listen for grpc on.", +) +@click.option( + "--runtime-env-agent-port", + type=int, + default=None, + help="The port for the runtime environment agents to listen for http on.", +) +@click.option( + "--block", + is_flag=True, + default=False, + help="provide this argument to block forever in this command", +) +@click.option( + "--plasma-directory", + required=False, + type=str, + help="object store directory for memory mapped files", +) +@click.option( + "--object-spilling-directory", + required=False, + type=str, + help="The path to spill objects to. This path will also be used as the fallback directory when the object store is full of in-use objects and cannot spill.", +) +@click.option( + "--autoscaling-config", + required=False, + type=str, + help="the file that contains the autoscaling config", +) +@click.option( + "--no-redirect-output", + is_flag=True, + default=False, + help="do not redirect non-worker stdout and stderr to files", +) +@click.option( + "--temp-dir", + default=None, + help="manually specify the root temporary dir of the Ray process, only " + "works when --head is specified", +) +@click.option( + "--system-config", + default=None, + hidden=True, + type=json.loads, + help="Override system configuration defaults.", +) +@click.option( + "--enable-object-reconstruction", + is_flag=True, + default=False, + hidden=True, + help="Specify whether object reconstruction will be used for this cluster.", +) +@click.option( + "--metrics-export-port", + type=int, + default=None, + help="the port to use to expose Ray metrics through a Prometheus endpoint.", +) +@click.option( + "--no-monitor", + is_flag=True, + hidden=True, + default=False, + help="If True, the ray autoscaler monitor for this cluster will not be started.", +) +@click.option( + "--tracing-startup-hook", + type=str, + hidden=True, + default=None, + help="The function that sets up tracing with a tracing provider, remote " + "span processor, and additional instruments. See docs.ray.io/tracing.html " + "for more info.", +) +@click.option( + "--ray-debugger-external", + is_flag=True, + default=False, + help="Make the Ray debugger available externally to the node. This is only " + "safe to activate if the node is behind a firewall.", +) +@click.option( + "--disable-usage-stats", + is_flag=True, + default=False, + help="If True, the usage stats collection will be disabled.", +) +@click.option( + "--labels", + required=False, + hidden=True, + default="", + type=str, + help="a string list of key-value pairs mapping label name to label value." + "These values take precedence over conflicting keys passed in from --labels-file." + 'Ex: --labels "key1=val1,key2=val2"', +) +@click.option( + "--labels-file", + required=False, + hidden=True, + default="", + type=str, + help="a path to a YAML file containing a dictionary mapping of label keys to values.", +) +@click.option( + "--include-log-monitor", + default=None, + type=bool, + help="If set to True or left unset, a log monitor will start monitoring " + "the log files of all processes on this node and push their contents to GCS. " + "Only one log monitor should be started per physical host to avoid log " + "duplication on the driver process.", +) +@click.option( + "--enable-resource-isolation", + required=False, + is_flag=True, + default=False, + help="Enable resource isolation through cgroupv2 by reserving memory and cpu " + "resources for ray system processes. To use, only cgroupv2 (not cgroupv1) must " + "be enabled with read and write permissions for the raylet. Cgroup memory and " + "cpu controllers must also be enabled.", +) +@click.option( + "--system-reserved-cpu", + required=False, + type=float, + help="The amount of cpu cores to reserve for ray system processes. Cores can be " + "fractional i.e. 0.5 means half a cpu core. " + "By default, the min of 20% and 1 core will be reserved." + "Must be >= 0.5 and < total number of available cores. " + "This option only works if --enable-resource-isolation is set.", +) +@click.option( + "--system-reserved-memory", + required=False, + type=int, + help="The amount of memory (in bytes) to reserve for ray system processes. " + "By default, the min of 10% and 25GB plus object_store_memory will be reserved. " + "Must be >= 100MB and system-reserved-memory + object-store-bytes < total available memory " + "This option only works if --enable-resource-isolation is set.", +) +@click.option( + "--cgroup-path", + required=False, + hidden=True, + type=str, + help="The path for the cgroup the raylet should use to enforce resource isolation. " + "By default, the cgroup used for resource isolation will be /sys/fs/cgroup. " + "The raylet must have read/write permissions to this path. " + "Cgroup memory and cpu controllers be enabled for this cgroup. " + "This option only works if --enable-resource-isolation is set.", +) +@add_click_logging_options +@PublicAPI +def start( + node_ip_address, + address, + port, + node_name, + redis_username, + redis_password, + redis_shard_ports, + object_manager_port, + node_manager_port, + min_worker_port, + max_worker_port, + worker_port_list, + ray_client_server_port, + memory, + object_store_memory, + num_cpus, + num_gpus, + resources, + head, + include_dashboard, + dashboard_host, + dashboard_port, + dashboard_agent_listen_port, + dashboard_agent_grpc_port, + runtime_env_agent_port, + block, + plasma_directory, + object_spilling_directory, + autoscaling_config, + no_redirect_output, + temp_dir, + system_config, + enable_object_reconstruction, + metrics_export_port, + no_monitor, + tracing_startup_hook, + ray_debugger_external, + disable_usage_stats, + labels, + labels_file, + include_log_monitor, + enable_resource_isolation, + system_reserved_cpu, + system_reserved_memory, + cgroup_path, +): + """Start Ray processes manually on the local machine.""" + + # Whether the original arguments include node_ip_address. + include_node_ip_address = False + if node_ip_address is not None: + include_node_ip_address = True + node_ip_address = services.resolve_ip_for_localhost(node_ip_address) + + resources = parse_resources_json(resources, cli_logger, cf) + + # Compose labels passed in with `--labels` and `--labels-file`. + # In the case of duplicate keys, the values from `--labels` take precedence. + try: + labels_from_file = parse_node_labels_from_yaml_file(labels_file) + except Exception as e: + cli_logger.abort( + "The file at `{}` is not a valid YAML file, detailed error: {} " + "Valid values look like this: `{}`", + cf.bold(f"--labels-file={labels_file}"), + str(e), + cf.bold("--labels-file='gpu_type: A100\nregion: us'"), + ) + try: + # Attempt to parse labels from new string format first. + labels_from_string = parse_node_labels_string(labels) + except Exception as e: + try: + # Fall back to JSON format if parsing from string fails. + labels_from_string = parse_node_labels_json(labels) + warnings.warn( + "passing node labels with `--labels` in JSON format is " + "deprecated and will be removed in a future version of Ray.", + DeprecationWarning, + stacklevel=2, + ) + except Exception: + # If parsing labels from both formats fails, return the original error message. + cli_logger.abort( + "`{}` is not a valid string of key-value pairs, detailed error: {} " + "Valid values look like this: `{}`", + cf.bold(f"--labels={labels}"), + str(e), + cf.bold('--labels="key1=val1,key2=val2"'), + ) + labels_dict = {**labels_from_file, **labels_from_string} + if temp_dir and not head: + cli_logger.warning( + f"`--temp-dir={temp_dir}` option will be ignored. " + "`--head` is a required flag to use `--temp-dir`. " + "temp_dir is only configurable from a head node. " + "All the worker nodes will use the same temp_dir as a head node. " + ) + temp_dir = None + + resource_isolation_config = ResourceIsolationConfig( + enable_resource_isolation=enable_resource_isolation, + cgroup_path=cgroup_path, + system_reserved_cpu=system_reserved_cpu, + system_reserved_memory=system_reserved_memory, + ) + + redirect_output = None if not no_redirect_output else True + + # no client, no port -> ok + # no port, has client -> default to 10001 + # has port, no client -> value error + # has port, has client -> ok, check port validity + has_ray_client = check_ray_client_dependencies_installed() + if has_ray_client and ray_client_server_port is None: + ray_client_server_port = 10001 + + ray_params = ray._private.parameter.RayParams( + node_ip_address=node_ip_address, + node_name=node_name if node_name else node_ip_address, + min_worker_port=min_worker_port, + max_worker_port=max_worker_port, + worker_port_list=worker_port_list, + ray_client_server_port=ray_client_server_port, + object_manager_port=object_manager_port, + node_manager_port=node_manager_port, + memory=memory, + object_store_memory=object_store_memory, + redis_username=redis_username, + redis_password=redis_password, + redirect_output=redirect_output, + num_cpus=num_cpus, + num_gpus=num_gpus, + resources=resources, + labels=labels_dict, + autoscaling_config=autoscaling_config, + plasma_directory=plasma_directory, + object_spilling_directory=object_spilling_directory, + huge_pages=False, + temp_dir=temp_dir, + include_dashboard=include_dashboard, + dashboard_host=dashboard_host, + dashboard_port=dashboard_port, + dashboard_agent_listen_port=dashboard_agent_listen_port, + metrics_agent_port=dashboard_agent_grpc_port, + runtime_env_agent_port=runtime_env_agent_port, + _system_config=system_config, + enable_object_reconstruction=enable_object_reconstruction, + metrics_export_port=metrics_export_port, + no_monitor=no_monitor, + tracing_startup_hook=tracing_startup_hook, + ray_debugger_external=ray_debugger_external, + include_log_monitor=include_log_monitor, + resource_isolation_config=resource_isolation_config, + ) + + if ray_constants.RAY_START_HOOK in os.environ: + load_class(os.environ[ray_constants.RAY_START_HOOK])(ray_params, head) + + if head: + # Start head node. + + if disable_usage_stats: + usage_lib.set_usage_stats_enabled_via_env_var(False) + usage_lib.show_usage_stats_prompt(cli=True) + cli_logger.newline() + + if port is None: + port = ray_constants.DEFAULT_PORT + + # Set bootstrap port. + assert ray_params.redis_port is None + assert ray_params.gcs_server_port is None + ray_params.gcs_server_port = port + + if os.environ.get("RAY_FAKE_CLUSTER"): + ray_params.env_vars = { + "RAY_OVERRIDE_NODE_ID_FOR_TESTING": FAKE_HEAD_NODE_ID + } + + if ( + no_monitor # KubeRay sets this flag when autoscaler is enabled. + and usage_constant.KUBERAY_ENV in os.environ # KubeRay exclusive. + and "RAY_CLOUD_INSTANCE_ID" in os.environ # required by autoscaler v2. + and "RAY_NODE_TYPE_NAME" in os.environ # required by autoscaler v2. + ): + # If this Ray cluster is managed by KubeRay and RAY_CLOUD_INSTANCE_ID and RAY_NODE_TYPE_NAME are set, + # we enable the v2 autoscaler by default if RAY_enable_autoscaler_v2 is not set. + os.environ.setdefault("RAY_enable_autoscaler_v2", "1") + + num_redis_shards = None + # Start Ray on the head node. + if redis_shard_ports is not None and address is None: + redis_shard_ports = redis_shard_ports.split(",") + # Infer the number of Redis shards from the ports if the number is + # not provided. + num_redis_shards = len(redis_shard_ports) + + # This logic is deprecated and will be removed later. + if address is not None: + cli_logger.warning( + "Specifying {} for external Redis address is deprecated. " + "Please specify environment variable {}={} instead.", + cf.bold("--address"), + cf.bold("RAY_REDIS_ADDRESS"), + address, + ) + external_addresses = address.split(",") + + # We reuse primary redis as sharding when there's only one + # instance provided. + if len(external_addresses) == 1: + external_addresses.append(external_addresses[0]) + + ray_params.update_if_absent(external_addresses=external_addresses) + num_redis_shards = len(external_addresses) - 1 + if redis_username == ray_constants.REDIS_DEFAULT_USERNAME: + cli_logger.warning( + "`{}` should not be specified as empty string if " + "external Redis server(s) `{}` points to requires " + "username.", + cf.bold("--redis-username"), + cf.bold("--address"), + ) + if redis_password == ray_constants.REDIS_DEFAULT_PASSWORD: + cli_logger.warning( + "`{}` should not be specified as empty string if " + "external redis server(s) `{}` points to requires " + "password.", + cf.bold("--redis-password"), + cf.bold("--address"), + ) + + # Get the node IP address if one is not provided. + ray_params.update_if_absent(node_ip_address=services.get_node_ip_address()) + cli_logger.labeled_value("Local node IP", ray_params.node_ip_address) + + # Initialize Redis settings. + ray_params.update_if_absent( + redis_shard_ports=redis_shard_ports, + num_redis_shards=num_redis_shards, + redis_max_clients=None, + ) + + # Fail early when starting a new cluster when one is already running + if address is None: + default_address = f"{ray_params.node_ip_address}:{port}" + bootstrap_address = services.find_bootstrap_address(temp_dir) + if ( + default_address == bootstrap_address + and bootstrap_address in services.find_gcs_addresses() + ): + # The default address is already in use by a local running GCS + # instance. + raise ConnectionError( + f"Ray is trying to start at {default_address}, " + f"but is already running at {bootstrap_address}. " + "Please specify a different port using the `--port`" + " flag of `ray start` command." + ) + + node = ray._private.node.Node( + ray_params, head=True, shutdown_at_exit=block, spawn_reaper=block + ) + + bootstrap_address = node.address + + # this is a noop if new-style is not set, so the old logger calls + # are still in place + cli_logger.newline() + startup_msg = "Ray runtime started." + cli_logger.success("-" * len(startup_msg)) + cli_logger.success(startup_msg) + cli_logger.success("-" * len(startup_msg)) + cli_logger.newline() + with cli_logger.group("Next steps"): + dashboard_url = node.address_info["webui_url"] + if ray_constants.ENABLE_RAY_CLUSTER: + cli_logger.print("To add another node to this Ray cluster, run") + # NOTE(kfstorm): Java driver rely on this line to get the address + # of the cluster. Please be careful when updating this line. + cli_logger.print( + cf.bold(" {} ray start --address='{}'"), + f" {ray_constants.ENABLE_RAY_CLUSTERS_ENV_VAR}=1" + if ray_constants.IS_WINDOWS_OR_OSX + else "", + bootstrap_address, + ) + + cli_logger.newline() + cli_logger.print("To connect to this Ray cluster:") + with cli_logger.indented(): + cli_logger.print("{} ray", cf.magenta("import")) + cli_logger.print( + "ray{}init({})", + cf.magenta("."), + "_node_ip_address{}{}".format( + cf.magenta("="), cf.yellow("'" + node_ip_address + "'") + ) + if include_node_ip_address + else "", + ) + + if dashboard_url: + cli_logger.newline() + cli_logger.print("To submit a Ray job using the Ray Jobs CLI:") + cli_logger.print( + cf.bold( + " RAY_ADDRESS='http://{}' ray job submit " + "--working-dir . " + "-- python my_script.py" + ), + dashboard_url, + ) + cli_logger.newline() + cli_logger.print( + "See https://docs.ray.io/en/latest/cluster/running-applications" + "/job-submission/index.html " + ) + cli_logger.print( + "for more information on submitting Ray jobs to the Ray cluster." + ) + + cli_logger.newline() + cli_logger.print("To terminate the Ray runtime, run") + cli_logger.print(cf.bold(" ray stop")) + + cli_logger.newline() + cli_logger.print("To view the status of the cluster, use") + cli_logger.print(" {}".format(cf.bold("ray status"))) + + if dashboard_url: + cli_logger.newline() + cli_logger.print("To monitor and debug Ray, view the dashboard at ") + cli_logger.print( + " {}".format( + cf.bold(dashboard_url), + ) + ) + + cli_logger.newline() + cli_logger.print( + cf.underlined( + "If connection to the dashboard fails, check your " + "firewall settings and " + "network configuration." + ) + ) + ray_params.gcs_address = bootstrap_address + else: + # Start worker node. + if not ray_constants.ENABLE_RAY_CLUSTER: + cli_logger.abort( + "Multi-node Ray clusters are not supported on Windows and OSX. " + "Restart the Ray cluster with the environment variable `{}=1` " + "to proceed anyway.", + cf.bold(ray_constants.ENABLE_RAY_CLUSTERS_ENV_VAR), + ) + raise Exception( + "Multi-node Ray clusters are not supported on Windows and OSX. " + "Restart the Ray cluster with the environment variable " + f"`{ray_constants.ENABLE_RAY_CLUSTERS_ENV_VAR}=1` to proceed " + "anyway.", + ) + + # Ensure `--address` flag is specified. + if address is None: + cli_logger.abort( + "`{}` is a required flag unless starting a head node with `{}`.", + cf.bold("--address"), + cf.bold("--head"), + ) + raise Exception( + "`--address` is a required flag unless starting a " + "head node with `--head`." + ) + + # Raise error if any head-only flag are specified. + head_only_flags = { + "--port": port, + "--redis-shard-ports": redis_shard_ports, + "--include-dashboard": include_dashboard, + } + for flag, val in head_only_flags.items(): + if val is None: + continue + cli_logger.abort( + "`{}` should only be specified when starting head node with `{}`.", + cf.bold(flag), + cf.bold("--head"), + ) + raise ValueError( + f"{flag} should only be specified when starting head node " + "with `--head`." + ) + + # Start Ray on a non-head node. + bootstrap_address = services.canonicalize_bootstrap_address( + address, temp_dir=temp_dir + ) + + if bootstrap_address is None: + cli_logger.abort( + "Cannot canonicalize address `{}={}`.", + cf.bold("--address"), + cf.bold(address), + ) + raise Exception("Cannot canonicalize address " f"`--address={address}`.") + + ray_params.gcs_address = bootstrap_address + + # Get the node IP address if one is not provided. + ray_params.update_if_absent( + node_ip_address=services.get_node_ip_address(bootstrap_address) + ) + + cli_logger.labeled_value("Local node IP", ray_params.node_ip_address) + + node = ray._private.node.Node( + ray_params, head=False, shutdown_at_exit=block, spawn_reaper=block + ) + temp_dir = node.get_temp_dir_path() + + # TODO(hjiang): Validate whether specified resource is true for physical + # resource. + + # Ray and Python versions should probably be checked before + # initializing Node. + node.check_version_info() + + cli_logger.newline() + startup_msg = "Ray runtime started." + cli_logger.success("-" * len(startup_msg)) + cli_logger.success(startup_msg) + cli_logger.success("-" * len(startup_msg)) + cli_logger.newline() + cli_logger.print("To terminate the Ray runtime, run") + cli_logger.print(cf.bold(" ray stop")) + cli_logger.flush() + + assert ray_params.gcs_address is not None + ray._private.utils.write_ray_address(ray_params.gcs_address, temp_dir) + + if block: + cli_logger.newline() + with cli_logger.group(cf.bold("--block")): + cli_logger.print( + "This command will now block forever until terminated by a signal." + ) + cli_logger.print( + "Running subprocesses are monitored and a message will be " + "printed if any of them terminate unexpectedly. Subprocesses " + "exit with SIGTERM will be treated as graceful, thus NOT reported." + ) + cli_logger.flush() + + while True: + time.sleep(1) + deceased = node.dead_processes() + + # Report unexpected exits of subprocesses with unexpected return codes. + # We are explicitly expecting SIGTERM because this is how `ray stop` sends + # shutdown signal to subprocesses, i.e. log_monitor, raylet... + # NOTE(rickyyx): We are treating 128+15 as an expected return code since + # this is what autoscaler/_private/monitor.py does upon SIGTERM + # handling. + expected_return_codes = [ + 0, + signal.SIGTERM, + -1 * signal.SIGTERM, + 128 + signal.SIGTERM, + ] + unexpected_deceased = [ + (process_type, process) + for process_type, process in deceased + if process.returncode not in expected_return_codes + ] + if len(unexpected_deceased) > 0: + cli_logger.newline() + cli_logger.error("Some Ray subprocesses exited unexpectedly:") + + with cli_logger.indented(): + for process_type, process in unexpected_deceased: + cli_logger.error( + "{}", + cf.bold(str(process_type)), + _tags={"exit code": str(process.returncode)}, + ) + + cli_logger.newline() + cli_logger.error("Remaining processes will be killed.") + # explicitly kill all processes since atexit handlers + # will not exit with errors. + node.kill_all_processes(check_alive=False, allow_graceful=False) + os._exit(1) + # not-reachable + + +@cli.command() +@click.option( + "-f", + "--force", + is_flag=True, + help="If set, ray will send SIGKILL instead of SIGTERM.", +) +@click.option( + "-g", + "--grace-period", + default=16, + help=( + "The time in seconds ray waits for processes to be properly terminated. " + "If processes are not terminated within the grace period, " + "they are forcefully terminated after the grace period. " + ), +) +@add_click_logging_options +@PublicAPI +def stop(force: bool, grace_period: int): + """Stop Ray processes manually on the local machine.""" + is_linux = sys.platform.startswith("linux") + total_procs_found = 0 + total_procs_stopped = 0 + procs_not_gracefully_killed = [] + + def kill_procs( + force: bool, grace_period: int, processes_to_kill: List[str] + ) -> Tuple[int, int, List[psutil.Process]]: + """Find all processes from `processes_to_kill` and terminate them. + + Unless `force` is specified, it gracefully kills processes. If + processes are not cleaned within `grace_period`, it force kill all + remaining processes. + + Returns: + total_procs_found: Total number of processes found from + `processes_to_kill` is added. + total_procs_stopped: Total number of processes gracefully + stopped from `processes_to_kill` is added. + procs_not_gracefully_killed: If processes are not killed + gracefully, they are added here. + """ + process_infos = [] + for proc in psutil.process_iter(["name", "cmdline"]): + try: + process_infos.append((proc, proc.name(), proc.cmdline())) + except psutil.Error: + pass + + stopped = [] + for keyword, filter_by_cmd in processes_to_kill: + if filter_by_cmd and is_linux and len(keyword) > 15: + # getting here is an internal bug, so we do not use cli_logger + msg = ( + "The filter string should not be more than {} " + "characters. Actual length: {}. Filter: {}" + ).format(15, len(keyword), keyword) + raise ValueError(msg) + + found = [] + for candidate in process_infos: + proc, proc_cmd, proc_args = candidate + corpus = ( + proc_cmd if filter_by_cmd else subprocess.list2cmdline(proc_args) + ) + if keyword in corpus: + found.append(candidate) + for proc, proc_cmd, proc_args in found: + proc_string = str(subprocess.list2cmdline(proc_args)) + try: + if force: + proc.kill() + else: + # TODO(mehrdadn): On Windows, this is forceful termination. + # We don't want CTRL_BREAK_EVENT, because that would + # terminate the entire process group. What to do? + proc.terminate() + + if force: + cli_logger.verbose( + "Killed `{}` {} ", + cf.bold(proc_string), + cf.dimmed("(via SIGKILL)"), + ) + else: + cli_logger.verbose( + "Send termination request to `{}` {}", + cf.bold(proc_string), + cf.dimmed("(via SIGTERM)"), + ) + + stopped.append(proc) + except psutil.NoSuchProcess: + cli_logger.verbose( + "Attempted to stop `{}`, but process was already dead.", + cf.bold(proc_string), + ) + except (psutil.Error, OSError) as ex: + cli_logger.error( + "Could not terminate `{}` due to {}", + cf.bold(proc_string), + str(ex), + ) + + # Wait for the processes to actually stop. + # Dedup processes. + stopped, alive = psutil.wait_procs(stopped, timeout=0) + procs_to_kill = stopped + alive + total_found = len(procs_to_kill) + + # Wait for grace period to terminate processes. + gone_procs = set() + + def on_terminate(proc): + gone_procs.add(proc) + cli_logger.print(f"{len(gone_procs)}/{total_found} stopped.", end="\r") + + stopped, alive = psutil.wait_procs( + procs_to_kill, timeout=grace_period, callback=on_terminate + ) + total_stopped = len(stopped) + + # For processes that are not killed within the grace period, + # we send force termination signals. + for proc in alive: + proc.kill() + # Wait a little bit to make sure processes are killed forcefully. + psutil.wait_procs(alive, timeout=2) + return total_found, total_stopped, alive + + # Process killing procedure: we put processes into 3 buckets. + # Bucket 1: raylet + # Bucket 2: all other processes, e.g. dashboard, runtime env agents + # Bucket 3: gcs_server. + # + # For each bucket, we send sigterm to all processes, then wait for 30s, then if + # they are still alive, send sigkill. + processes_to_kill = RAY_PROCESSES + # Raylet should exit before all other processes exit. + # Otherwise, fate-sharing agents will complain and exit. + assert processes_to_kill[0][0] == "raylet" + + # GCS should exit after all other processes exit. + # Otherwise, some of processes may exit with an unexpected + # exit code which breaks ray start --block. + assert processes_to_kill[-1][0] == "gcs_server" + + buckets = [[processes_to_kill[0]], processes_to_kill[1:-1], [processes_to_kill[-1]]] + + for bucket in buckets: + found, stopped, alive = kill_procs(force, grace_period / len(buckets), bucket) + total_procs_found += found + total_procs_stopped += stopped + procs_not_gracefully_killed.extend(alive) + + # Print the termination result. + if total_procs_found == 0: + cli_logger.print("Did not find any active Ray processes.") + else: + if total_procs_stopped == total_procs_found: + cli_logger.success("Stopped all {} Ray processes.", total_procs_stopped) + else: + cli_logger.warning( + f"Stopped only {total_procs_stopped} out of {total_procs_found} " + f"Ray processes within the grace period {grace_period} seconds. " + f"Set `{cf.bold('-v')}` to see more details. " + f"Remaining processes {procs_not_gracefully_killed} " + "will be forcefully terminated.", + ) + cli_logger.warning( + f"You can also use `{cf.bold('--force')}` to forcefully terminate " + "processes or set higher `--grace-period` to wait longer time for " + "proper termination." + ) + + # NOTE(swang): This will not reset the cluster address for a user-defined + # temp_dir. This is fine since it will get overwritten the next time we + # call `ray start`. + ray._common.utils.reset_ray_address() + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--min-workers", + required=False, + type=int, + help="Override the configured min worker node count for the cluster.", +) +@click.option( + "--max-workers", + required=False, + type=int, + help="Override the configured max worker node count for the cluster.", +) +@click.option( + "--no-restart", + is_flag=True, + default=False, + help=( + "Whether to skip restarting Ray services during the update. " + "This avoids interrupting running jobs." + ), +) +@click.option( + "--restart-only", + is_flag=True, + default=False, + help=( + "Whether to skip running setup commands and only restart Ray. " + "This cannot be used with 'no-restart'." + ), +) +@click.option( + "--yes", "-y", is_flag=True, default=False, help="Don't ask for confirmation." +) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--no-config-cache", + is_flag=True, + default=False, + help="Disable the local cluster config cache.", +) +@click.option( + "--redirect-command-output", + is_flag=True, + default=False, + help="Whether to redirect command output to a file.", +) +@click.option( + "--use-login-shells/--use-normal-shells", + is_flag=True, + default=True, + help=( + "Ray uses login shells (bash --login -i) to run cluster commands " + "by default. If your workflow is compatible with normal shells, " + "this can be disabled for a better user experience." + ), +) +@click.option( + "--disable-usage-stats", + is_flag=True, + default=False, + help="If True, the usage stats collection will be disabled.", +) +@add_click_logging_options +@PublicAPI +def up( + cluster_config_file, + min_workers, + max_workers, + no_restart, + restart_only, + yes, + cluster_name, + no_config_cache, + redirect_command_output, + use_login_shells, + disable_usage_stats, +): + """Create or update a Ray cluster.""" + if disable_usage_stats: + usage_lib.set_usage_stats_enabled_via_env_var(False) + + if restart_only or no_restart: + cli_logger.doassert( + restart_only != no_restart, + "`{}` is incompatible with `{}`.", + cf.bold("--restart-only"), + cf.bold("--no-restart"), + ) + assert ( + restart_only != no_restart + ), "Cannot set both 'restart_only' and 'no_restart' at the same time!" + + if urllib.parse.urlparse(cluster_config_file).scheme in ("http", "https"): + try: + response = urllib.request.urlopen(cluster_config_file, timeout=5) + content = response.read() + file_name = cluster_config_file.split("/")[-1] + with open(file_name, "wb") as f: + f.write(content) + cluster_config_file = file_name + except urllib.error.HTTPError as e: + cli_logger.warning("{}", str(e)) + cli_logger.warning("Could not download remote cluster configuration file.") + create_or_update_cluster( + config_file=cluster_config_file, + override_min_workers=min_workers, + override_max_workers=max_workers, + no_restart=no_restart, + restart_only=restart_only, + yes=yes, + override_cluster_name=cluster_name, + no_config_cache=no_config_cache, + redirect_command_output=redirect_command_output, + use_login_shells=use_login_shells, + ) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--yes", "-y", is_flag=True, default=False, help="Don't ask for confirmation." +) +@click.option( + "--workers-only", is_flag=True, default=False, help="Only destroy the workers." +) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--keep-min-workers", + is_flag=True, + default=False, + help="Retain the minimal amount of workers specified in the config.", +) +@add_click_logging_options +@PublicAPI +def down(cluster_config_file, yes, workers_only, cluster_name, keep_min_workers): + """Tear down a Ray cluster.""" + teardown_cluster( + cluster_config_file, yes, workers_only, cluster_name, keep_min_workers + ) + + +@cli.command(hidden=True) +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--yes", "-y", is_flag=True, default=False, help="Don't ask for confirmation." +) +@click.option( + "--hard", + is_flag=True, + default=False, + help="Terminates the node via node provider (defaults to a 'soft kill'" + " which terminates Ray but does not actually delete the instances).", +) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +def kill_random_node(cluster_config_file, yes, hard, cluster_name): + """Kills a random Ray node. For testing purposes only.""" + click.echo( + "Killed node with IP " + kill_node(cluster_config_file, yes, hard, cluster_name) + ) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--lines", required=False, default=100, type=int, help="Number of lines to tail." +) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@add_click_logging_options +def monitor(cluster_config_file, lines, cluster_name): + """Tails the autoscaler logs of a Ray cluster.""" + monitor_cluster(cluster_config_file, lines, cluster_name) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--start", is_flag=True, default=False, help="Start the cluster if needed." +) +@click.option( + "--screen", is_flag=True, default=False, help="Run the command in screen." +) +@click.option("--tmux", is_flag=True, default=False, help="Run the command in tmux.") +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--no-config-cache", + is_flag=True, + default=False, + help="Disable the local cluster config cache.", +) +@click.option("--new", "-N", is_flag=True, help="Force creation of a new screen.") +@click.option( + "--port-forward", + "-p", + required=False, + multiple=True, + type=int, + help="Port to forward. Use this multiple times to forward multiple ports.", +) +@add_click_logging_options +@PublicAPI +def attach( + cluster_config_file, + start, + screen, + tmux, + cluster_name, + no_config_cache, + new, + port_forward, +): + """Create or attach to a SSH session to a Ray cluster.""" + port_forward = [(port, port) for port in list(port_forward)] + attach_cluster( + cluster_config_file, + start, + screen, + tmux, + cluster_name, + no_config_cache=no_config_cache, + new=new, + port_forward=port_forward, + ) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.argument("source", required=False, type=str) +@click.argument("target", required=False, type=str) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@add_click_logging_options +def rsync_down(cluster_config_file, source, target, cluster_name): + """Download specific files from a Ray cluster.""" + rsync(cluster_config_file, source, target, cluster_name, down=True) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.argument("source", required=False, type=str) +@click.argument("target", required=False, type=str) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--all-nodes", + "-A", + is_flag=True, + required=False, + help="Upload to all nodes (workers and head).", +) +@add_click_logging_options +def rsync_up(cluster_config_file, source, target, cluster_name, all_nodes): + """Upload specific files to a Ray cluster.""" + if all_nodes: + cli_logger.warning( + "WARNING: the `all_nodes` option is deprecated and will be " + "removed in the future. " + "Rsync to worker nodes is not reliable since workers may be " + "added during autoscaling. Please use the `file_mounts` " + "feature instead for consistent file sync in autoscaling clusters" + ) + + rsync( + cluster_config_file, + source, + target, + cluster_name, + down=False, + all_nodes=all_nodes, + ) + + +@cli.command(context_settings={"ignore_unknown_options": True}) +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--stop", + is_flag=True, + default=False, + help="Stop the cluster after the command finishes running.", +) +@click.option( + "--start", is_flag=True, default=False, help="Start the cluster if needed." +) +@click.option( + "--screen", is_flag=True, default=False, help="Run the command in a screen." +) +@click.option("--tmux", is_flag=True, default=False, help="Run the command in tmux.") +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--no-config-cache", + is_flag=True, + default=False, + help="Disable the local cluster config cache.", +) +@click.option( + "--port-forward", + "-p", + required=False, + multiple=True, + type=int, + help="Port to forward. Use this multiple times to forward multiple ports.", +) +@click.argument("script", required=True, type=str) +@click.option( + "--args", + required=False, + type=str, + help="(deprecated) Use '-- --arg1 --arg2' for script args.", +) +@click.argument("script_args", nargs=-1) +@click.option( + "--disable-usage-stats", + is_flag=True, + default=False, + help="If True, the usage stats collection will be disabled.", +) +@click.option( + "--extra-screen-args", + default=None, + help="if screen is enabled, add the provided args to it. A useful example " + "usage scenario is passing --extra-screen-args='-Logfile /full/path/blah_log.txt'" + " as it redirects screen output also to a custom file", +) +@add_click_logging_options +def submit( + cluster_config_file, + screen, + tmux, + stop, + start, + cluster_name, + no_config_cache, + port_forward, + script, + args, + script_args, + disable_usage_stats, + extra_screen_args: Optional[str] = None, +): + """Uploads and runs a script on the specified cluster. + + The script is automatically synced to the following location: + + os.path.join("~", os.path.basename(script)) + + Example: + ray submit [CLUSTER.YAML] experiment.py -- --smoke-test + """ + cli_logger.doassert( + not (screen and tmux), + "`{}` and `{}` are incompatible.", + cf.bold("--screen"), + cf.bold("--tmux"), + ) + cli_logger.doassert( + not (script_args and args), + "`{0}` and `{1}` are incompatible. Use only `{1}`.\nExample: `{2}`", + cf.bold("--args"), + cf.bold("-- "), + cf.bold("ray submit script.py -- --arg=123 --flag"), + ) + + assert not (screen and tmux), "Can specify only one of `screen` or `tmux`." + assert not (script_args and args), "Use -- --arg1 --arg2 for script args." + + if (extra_screen_args is not None) and (not screen): + cli_logger.abort( + "To use extra_screen_args, it is required to use the --screen flag" + ) + + if args: + cli_logger.warning( + "`{}` is deprecated and will be removed in the future.", cf.bold("--args") + ) + cli_logger.warning( + "Use `{}` instead. Example: `{}`.", + cf.bold("-- "), + cf.bold("ray submit script.py -- --arg=123 --flag"), + ) + cli_logger.newline() + + if start: + if disable_usage_stats: + usage_lib.set_usage_stats_enabled_via_env_var(False) + + create_or_update_cluster( + config_file=cluster_config_file, + override_min_workers=None, + override_max_workers=None, + no_restart=False, + restart_only=False, + yes=True, + override_cluster_name=cluster_name, + no_config_cache=no_config_cache, + redirect_command_output=False, + use_login_shells=True, + ) + target = os.path.basename(script) + target = os.path.join("~", target) + rsync( + cluster_config_file, + script, + target, + cluster_name, + no_config_cache=no_config_cache, + down=False, + ) + + command_parts = ["python", target] + if script_args: + command_parts += list(script_args) + elif args is not None: + command_parts += [args] + + port_forward = [(port, port) for port in list(port_forward)] + cmd = " ".join(command_parts) + exec_cluster( + cluster_config_file, + cmd=cmd, + run_env="docker", + screen=screen, + tmux=tmux, + stop=stop, + start=False, + override_cluster_name=cluster_name, + no_config_cache=no_config_cache, + port_forward=port_forward, + extra_screen_args=extra_screen_args, + ) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.argument("cmd", required=True, type=str) +@click.option( + "--run-env", + required=False, + type=click.Choice(RUN_ENV_TYPES), + default="auto", + help="Choose whether to execute this command in a container or directly on" + " the cluster head. Only applies when docker is configured in the YAML.", +) +@click.option( + "--stop", + is_flag=True, + default=False, + help="Stop the cluster after the command finishes running.", +) +@click.option( + "--start", is_flag=True, default=False, help="Start the cluster if needed." +) +@click.option( + "--screen", is_flag=True, default=False, help="Run the command in a screen." +) +@click.option("--tmux", is_flag=True, default=False, help="Run the command in tmux.") +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--no-config-cache", + is_flag=True, + default=False, + help="Disable the local cluster config cache.", +) +@click.option( + "--port-forward", + "-p", + required=False, + multiple=True, + type=int, + help="Port to forward. Use this multiple times to forward multiple ports.", +) +@click.option( + "--disable-usage-stats", + is_flag=True, + default=False, + help="If True, the usage stats collection will be disabled.", +) +@add_click_logging_options +def exec( + cluster_config_file, + cmd, + run_env, + screen, + tmux, + stop, + start, + cluster_name, + no_config_cache, + port_forward, + disable_usage_stats, +): + """Execute a command via SSH on a Ray cluster.""" + port_forward = [(port, port) for port in list(port_forward)] + + if start: + if disable_usage_stats: + usage_lib.set_usage_stats_enabled_via_env_var(False) + + exec_cluster( + cluster_config_file, + cmd=cmd, + run_env=run_env, + screen=screen, + tmux=tmux, + stop=stop, + start=start, + override_cluster_name=cluster_name, + no_config_cache=no_config_cache, + port_forward=port_forward, + _allow_uninitialized_state=True, + ) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +def get_head_ip(cluster_config_file, cluster_name): + """Return the head node IP of a Ray cluster.""" + click.echo(get_head_node_ip(cluster_config_file, cluster_name)) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +def get_worker_ips(cluster_config_file, cluster_name): + """Return the list of worker IPs of a Ray cluster.""" + worker_ips = get_worker_node_ips(cluster_config_file, cluster_name) + click.echo("\n".join(worker_ips)) + + +@cli.command() +def disable_usage_stats(): + """Disable usage stats collection. + + This will not affect the current running clusters + but clusters launched in the future. + """ + usage_lib.set_usage_stats_enabled_via_config(enabled=False) + print( + "Usage stats disabled for future clusters. " + "Restart any current running clusters for this to take effect." + ) + + +@cli.command() +def enable_usage_stats(): + """Enable usage stats collection. + + This will not affect the current running clusters + but clusters launched in the future. + """ + usage_lib.set_usage_stats_enabled_via_config(enabled=True) + print( + "Usage stats enabled for future clusters. " + "Restart any current running clusters for this to take effect." + ) + + +@cli.command() +def stack(): + """Take a stack dump of all Python workers on the local machine.""" + COMMAND = """ +pyspy=`which py-spy` +if [ ! -e "$pyspy" ]; then + echo "ERROR: Please 'pip install py-spy'" \ + "or 'pip install ray[default]' first." + exit 1 +fi +# Set IFS to iterate over lines instead of over words. +export IFS=" +" +# Call sudo to prompt for password before anything has been printed. +sudo true +workers=$( + ps aux | grep -E ' ray::|default_worker.py' | grep -v raylet | grep -v grep +) +for worker in $workers; do + echo "Stack dump for $worker"; + pid=`echo $worker | awk '{print $2}'`; + case "$(uname -s)" in + Linux*) native=--native;; + *) native=;; + esac + sudo $pyspy dump --pid $pid $native; + echo; +done + """ + subprocess.call(COMMAND, shell=True) + + +@cli.command() +def microbenchmark(): + """Run a local Ray microbenchmark on the current machine.""" + from ray._private.ray_perf import main + + main() + + +@cli.command() +@click.option( + "--address", + required=False, + type=str, + help="Override the Ray address to connect to.", +) +def timeline(address): + """Take a Chrome tracing timeline for a Ray cluster.""" + address = services.canonicalize_bootstrap_address_or_die(address) + logger.info(f"Connecting to Ray instance at {address}.") + ray.init(address=address) + time = datetime.today().strftime("%Y-%m-%d_%H-%M-%S") + filename = os.path.join( + ray._common.utils.get_user_temp_dir(), f"ray-timeline-{time}.json" + ) + ray.timeline(filename=filename) + size = os.path.getsize(filename) + logger.info(f"Trace file written to {filename} ({size} bytes).") + logger.info("You can open this with chrome://tracing in the Chrome browser.") + + +@cli.command() +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +@click.option( + "--group-by", + type=click.Choice(["NODE_ADDRESS", "STACK_TRACE"]), + default="NODE_ADDRESS", + help="Group object references by a GroupByType \ +(e.g. NODE_ADDRESS or STACK_TRACE).", +) +@click.option( + "--sort-by", + type=click.Choice(["PID", "OBJECT_SIZE", "REFERENCE_TYPE"]), + default="OBJECT_SIZE", + help="Sort object references in ascending order by a SortingType \ +(e.g. PID, OBJECT_SIZE, or REFERENCE_TYPE).", +) +@click.option( + "--units", + type=click.Choice(["B", "KB", "MB", "GB"]), + default="B", + help="Specify unit metrics for displaying object sizes \ +(e.g. B, KB, MB, GB).", +) +@click.option( + "--no-format", + is_flag=True, + type=bool, + default=True, + help="Display unformatted results. Defaults to true when \ +terminal width is less than 137 characters.", +) +@click.option( + "--stats-only", is_flag=True, default=False, help="Display plasma store stats only." +) +@click.option( + "--num-entries", + "--n", + type=int, + default=None, + help="Specify number of sorted entries per group.", +) +def memory( + address, + group_by, + sort_by, + units, + no_format, + stats_only, + num_entries, +): + """Print object references held in a Ray cluster.""" + address = services.canonicalize_bootstrap_address_or_die(address) + gcs_client = ray._raylet.GcsClient(address=address) + _check_ray_version(gcs_client) + time = datetime.now() + header = "=" * 8 + f" Object references status: {time} " + "=" * 8 + mem_stats = memory_summary( + address, + group_by, + sort_by, + units, + no_format, + stats_only, + num_entries, + ) + print(f"{header}\n{mem_stats}") + + +@cli.command() +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +@click.option( + "-v", + "--verbose", + required=False, + is_flag=True, + hidden=True, + help="Experimental: Display additional debuggging information.", +) +@PublicAPI +def status(address: str, verbose: bool): + """Print cluster status, including autoscaling info.""" + address = services.canonicalize_bootstrap_address_or_die(address) + gcs_client = ray._raylet.GcsClient(address=address) + _check_ray_version(gcs_client) + ray.experimental.internal_kv._initialize_internal_kv(gcs_client) + status = gcs_client.internal_kv_get(ray_constants.DEBUG_AUTOSCALING_STATUS.encode()) + error = gcs_client.internal_kv_get(ray_constants.DEBUG_AUTOSCALING_ERROR.encode()) + print(debug_status(status, error, verbose=verbose, address=address)) + + +@cli.command(hidden=True) +@click.option( + "--stream", + "-S", + required=False, + type=bool, + is_flag=True, + default=False, + help="If True, will stream the binary archive contents to stdout", +) +@click.option( + "--output", "-o", required=False, type=str, default=None, help="Output file." +) +@click.option( + "--logs/--no-logs", + is_flag=True, + default=True, + help="Collect logs from ray session dir", +) +@click.option( + "--debug-state/--no-debug-state", + is_flag=True, + default=True, + help="Collect debug_state.txt from ray session dir", +) +@click.option( + "--pip/--no-pip", is_flag=True, default=True, help="Collect installed pip packages" +) +@click.option( + "--processes/--no-processes", + is_flag=True, + default=True, + help="Collect info on running processes", +) +@click.option( + "--processes-verbose/--no-processes-verbose", + is_flag=True, + default=True, + help="Increase process information verbosity", +) +@click.option( + "--tempfile", + "-T", + required=False, + type=str, + default=None, + help="Temporary file to use", +) +def local_dump( + stream: bool = False, + output: Optional[str] = None, + logs: bool = True, + debug_state: bool = True, + pip: bool = True, + processes: bool = True, + processes_verbose: bool = False, + tempfile: Optional[str] = None, +): + """Collect local data and package into an archive. + + Usage: + + ray local-dump [--stream/--output file] + + This script is called on remote nodes to fetch their data. + """ + # This may stream data to stdout, so no printing here + get_local_dump_archive( + stream=stream, + output=output, + logs=logs, + debug_state=debug_state, + pip=pip, + processes=processes, + processes_verbose=processes_verbose, + tempfile=tempfile, + ) + + +@cli.command() +@click.argument("cluster_config_file", required=False, type=str) +@click.option( + "--host", + "-h", + required=False, + type=str, + help="Single or list of hosts, separated by comma.", +) +@click.option( + "--ssh-user", + "-U", + required=False, + type=str, + default=None, + help="Username of the SSH user.", +) +@click.option( + "--ssh-key", + "-K", + required=False, + type=str, + default=None, + help="Path to the SSH key file.", +) +@click.option( + "--docker", + "-d", + required=False, + type=str, + default=None, + help="Name of the docker container, if applicable.", +) +@click.option( + "--local", + "-L", + required=False, + type=bool, + is_flag=True, + default=None, + help="Also include information about the local node.", +) +@click.option( + "--output", "-o", required=False, type=str, default=None, help="Output file." +) +@click.option( + "--logs/--no-logs", + is_flag=True, + default=True, + help="Collect logs from ray session dir", +) +@click.option( + "--debug-state/--no-debug-state", + is_flag=True, + default=True, + help="Collect debug_state.txt from ray log dir", +) +@click.option( + "--pip/--no-pip", is_flag=True, default=True, help="Collect installed pip packages" +) +@click.option( + "--processes/--no-processes", + is_flag=True, + default=True, + help="Collect info on running processes", +) +@click.option( + "--processes-verbose/--no-processes-verbose", + is_flag=True, + default=True, + help="Increase process information verbosity", +) +@click.option( + "--tempfile", + "-T", + required=False, + type=str, + default=None, + help="Temporary file to use", +) +def cluster_dump( + cluster_config_file: Optional[str] = None, + host: Optional[str] = None, + ssh_user: Optional[str] = None, + ssh_key: Optional[str] = None, + docker: Optional[str] = None, + local: Optional[bool] = None, + output: Optional[str] = None, + logs: bool = True, + debug_state: bool = True, + pip: bool = True, + processes: bool = True, + processes_verbose: bool = False, + tempfile: Optional[str] = None, +): + """Get log data from one or more nodes. + + Best used with Ray cluster configs: + + ray cluster-dump [cluster.yaml] + + Include the --local flag to also collect and include data from the + local node. + + Missing fields will be tried to be auto-filled. + + You can also manually specify a list of hosts using the + ``--host `` parameter. + """ + archive_path = get_cluster_dump_archive( + cluster_config_file=cluster_config_file, + host=host, + ssh_user=ssh_user, + ssh_key=ssh_key, + docker=docker, + local=local, + output=output, + logs=logs, + debug_state=debug_state, + pip=pip, + processes=processes, + processes_verbose=processes_verbose, + tempfile=tempfile, + ) + if archive_path: + click.echo(f"Created archive: {archive_path}") + else: + click.echo("Could not create archive.") + + +@cli.command(hidden=True) +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +def global_gc(address): + """Trigger Python garbage collection on all cluster workers.""" + ray.init(address=address) + ray._private.internal_api.global_gc() + print("Triggered gc.collect() on all workers.") + + +@cli.command(hidden=True) +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +@click.option( + "--node-id", + required=False, + type=str, + help="Hex ID of the worker node to be drained. Will default to current node if not provided.", +) +@click.option( + "--reason", + required=True, + type=click.Choice( + [ + item[0] + for item in autoscaler_pb2.DrainNodeReason.items() + if item[1] != autoscaler_pb2.DRAIN_NODE_REASON_UNSPECIFIED + ] + ), + help="The reason why the node will be drained.", +) +@click.option( + "--reason-message", + required=True, + type=str, + help="The detailed drain reason message.", +) +@click.option( + "--deadline-remaining-seconds", + required=False, + type=int, + default=None, + help="Inform GCS that the node to be drained will be force killed " + "after this many of seconds. " + "Default is None which means there is no deadline. " + "Note: This command doesn't actually force kill the node after the deadline, " + "it's the caller's responsibility to do that.", +) +def drain_node( + address: str, + node_id: str, + reason: str, + reason_message: str, + deadline_remaining_seconds: int, +): + """ + This is NOT a public API. + + Manually drain a worker node. + """ + # This should be before get_runtime_context() so get_runtime_context() + # doesn't start a new worker here. + address = services.canonicalize_bootstrap_address_or_die(address) + + if node_id is None: + node_id = ray.get_runtime_context().get_node_id() + deadline_timestamp_ms = 0 + if deadline_remaining_seconds is not None: + if deadline_remaining_seconds < 0: + raise click.BadParameter( + "--deadline-remaining-seconds cannot be negative, " + f"got {deadline_remaining_seconds}" + ) + deadline_timestamp_ms = (time.time_ns() // 1000000) + ( + deadline_remaining_seconds * 1000 + ) + + if ray.NodeID.from_hex(node_id) == ray.NodeID.nil(): + raise click.BadParameter(f"Invalid hex ID of a Ray node, got {node_id}") + + gcs_client = ray._raylet.GcsClient(address=address) + _check_ray_version(gcs_client) + is_accepted, rejection_error_message = gcs_client.drain_node( + node_id, + autoscaler_pb2.DrainNodeReason.Value(reason), + reason_message, + deadline_timestamp_ms, + ) + + if not is_accepted: + raise click.ClickException( + f"The drain request is not accepted: {rejection_error_message}" + ) + + +@cli.command(name="kuberay-autoscaler", hidden=True) +@click.option( + "--cluster-name", + required=True, + type=str, + help="The name of the Ray Cluster.\n" + "Should coincide with the `metadata.name` of the RayCluster CR.", +) +@click.option( + "--cluster-namespace", + required=True, + type=str, + help="The Kubernetes namespace the Ray Cluster lives in.\n" + "Should coincide with the `metadata.namespace` of the RayCluster CR.", +) +def kuberay_autoscaler(cluster_name: str, cluster_namespace: str) -> None: + """Runs the autoscaler for a Ray cluster managed by the KubeRay operator. + + `ray kuberay-autoscaler` is meant to be used as an entry point in + KubeRay cluster configs. + `ray kuberay-autoscaler` is NOT a public CLI. + """ + # Delay import to avoid introducing Ray core dependency on the Python Kubernetes + # client. + from ray.autoscaler._private.kuberay.run_autoscaler import run_kuberay_autoscaler + + run_kuberay_autoscaler(cluster_name, cluster_namespace) + + +@cli.command(name="health-check", hidden=True) +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +@click.option( + "--component", + required=False, + type=str, + help="Health check for a specific component. Currently supports: " + "[ray_client_server]", +) +@click.option( + "--skip-version-check", + is_flag=True, + default=False, + help="Skip comparison of GCS version with local Ray version.", +) +def healthcheck(address, component, skip_version_check): + """ + This is NOT a public API. + + Health check a Ray or a specific component. Exit code 0 is healthy. + """ + + address = services.canonicalize_bootstrap_address_or_die(address) + gcs_client = ray._raylet.GcsClient(address=address) + if not skip_version_check: + _check_ray_version(gcs_client) + + if not component: + sys.exit(0) + + report_str = gcs_client.internal_kv_get( + component.encode(), namespace=ray_constants.KV_NAMESPACE_HEALTHCHECK + ) + if not report_str: + # Status was never updated + sys.exit(1) + + report = json.loads(report_str) + + # TODO (Alex): We probably shouldn't rely on time here, but cloud providers + # have very well synchronized NTP servers, so this should be fine in + # practice. + cur_time = time.time() + report_time = float(report["time"]) + + # If the status is too old, the service has probably already died. + delta = cur_time - report_time + time_ok = delta < ray._private.ray_constants.HEALTHCHECK_EXPIRATION_S + + if time_ok: + sys.exit(0) + else: + sys.exit(1) + + +@cli.command() +@click.option("-v", "--verbose", is_flag=True) +@click.option( + "--dryrun", + is_flag=True, + help="Identifies the wheel but does not execute the installation.", +) +def install_nightly(verbose, dryrun): + """Install the latest wheels for Ray. + + This uses the same python environment as the one that Ray is currently + installed in. Make sure that there is no Ray processes on this + machine (ray stop) when running this command. + """ + raydir = os.path.abspath(os.path.dirname(ray.__file__)) + all_wheels_path = os.path.join(raydir, "nightly-wheels.yaml") + + wheels = None + if os.path.exists(all_wheels_path): + with open(all_wheels_path) as f: + wheels = yaml.safe_load(f) + + if not wheels: + raise click.ClickException( + f"Wheels not found in '{all_wheels_path}'! " + "Please visit https://docs.ray.io/en/master/installation.html to " + "obtain the latest wheels." + ) + + platform = sys.platform + py_version = "{0}.{1}".format(*sys.version_info[:2]) + + matching_wheel = None + for target_platform, wheel_map in wheels.items(): + if verbose: + print(f"Evaluating os={target_platform}, python={list(wheel_map)}") + if platform.startswith(target_platform): + if py_version in wheel_map: + matching_wheel = wheel_map[py_version] + break + if verbose: + print("Not matched.") + + if matching_wheel is None: + raise click.ClickException( + "Unable to identify a matching platform. " + "Please visit https://docs.ray.io/en/master/installation.html to " + "obtain the latest wheels." + ) + if dryrun: + print(f"Found wheel: {matching_wheel}") + else: + cmd = [sys.executable, "-m", "pip", "install", "-U", matching_wheel] + print(f"Running: {' '.join(cmd)}.") + subprocess.check_call(cmd) + + +@cli.command() +@click.option( + "--show-library-path", + "-show", + required=False, + is_flag=True, + help="Show the cpp include path and library path, if provided.", +) +@click.option( + "--generate-bazel-project-template-to", + "-gen", + required=False, + type=str, + help="The directory to generate the bazel project template to, if provided.", +) +@add_click_logging_options +def cpp(show_library_path, generate_bazel_project_template_to): + """Show the cpp library path and generate the bazel project template.""" + if sys.platform == "win32": + cli_logger.error("Ray C++ API is not supported on Windows currently.") + sys.exit(1) + if not show_library_path and not generate_bazel_project_template_to: + raise ValueError( + "Please input at least one option of '--show-library-path'" + " and '--generate-bazel-project-template-to'." + ) + raydir = os.path.abspath(os.path.dirname(ray.__file__)) + cpp_dir = os.path.join(raydir, "cpp") + cpp_templete_dir = os.path.join(cpp_dir, "example") + include_dir = os.path.join(cpp_dir, "include") + lib_dir = os.path.join(cpp_dir, "lib") + if not os.path.isdir(cpp_dir): + raise ValueError('Please install ray with C++ API by "pip install ray[cpp]".') + if show_library_path: + cli_logger.print("Ray C++ include path {} ", cf.bold(f"{include_dir}")) + cli_logger.print("Ray C++ library path {} ", cf.bold(f"{lib_dir}")) + if generate_bazel_project_template_to: + # copytree expects that the dst dir doesn't exist + # so we manually delete it if it exists. + if os.path.exists(generate_bazel_project_template_to): + shutil.rmtree(generate_bazel_project_template_to) + shutil.copytree(cpp_templete_dir, generate_bazel_project_template_to) + out_include_dir = os.path.join( + generate_bazel_project_template_to, "thirdparty/include" + ) + if os.path.exists(out_include_dir): + shutil.rmtree(out_include_dir) + shutil.copytree(include_dir, out_include_dir) + out_lib_dir = os.path.join(generate_bazel_project_template_to, "thirdparty/lib") + if os.path.exists(out_lib_dir): + shutil.rmtree(out_lib_dir) + shutil.copytree(lib_dir, out_lib_dir) + + cli_logger.print( + "Project template generated to {}", + cf.bold(f"{os.path.abspath(generate_bazel_project_template_to)}"), + ) + cli_logger.print("To build and run this template, run") + cli_logger.print( + cf.bold( + f" cd {os.path.abspath(generate_bazel_project_template_to)}" + " && bash run.sh" + ) + ) + + +@click.group(name="metrics") +def metrics_group(): + pass + + +@metrics_group.command(name="launch-prometheus") +def launch_prometheus(): + install_and_start_prometheus.main() + + +@metrics_group.command(name="shutdown-prometheus") +def shutdown_prometheus(): + try: + requests.post("http://localhost:9090/-/quit") + except requests.exceptions.RequestException as e: + print(f"An error occurred: {e}") + sys.exit(1) + + +def add_command_alias(command, name, hidden): + new_command = copy.deepcopy(command) + new_command.hidden = hidden + cli.add_command(new_command, name=name) + + +cli.add_command(dashboard) +cli.add_command(debug) +cli.add_command(start) +cli.add_command(stop) +cli.add_command(up) +add_command_alias(up, name="create_or_update", hidden=True) +cli.add_command(attach) +cli.add_command(exec) +add_command_alias(exec, name="exec_cmd", hidden=True) +add_command_alias(rsync_down, name="rsync_down", hidden=True) +add_command_alias(rsync_up, name="rsync_up", hidden=True) +cli.add_command(submit) +cli.add_command(down) +add_command_alias(down, name="teardown", hidden=True) +cli.add_command(kill_random_node) +add_command_alias(get_head_ip, name="get_head_ip", hidden=True) +cli.add_command(get_worker_ips) +cli.add_command(microbenchmark) +cli.add_command(stack) +cli.add_command(status) +cli.add_command(memory) +cli.add_command(local_dump) +cli.add_command(cluster_dump) +cli.add_command(global_gc) +cli.add_command(timeline) +cli.add_command(install_nightly) +cli.add_command(cpp) +cli.add_command(disable_usage_stats) +cli.add_command(enable_usage_stats) +cli.add_command(metrics_group) +cli.add_command(drain_node) +cli.add_command(check_open_ports) + +try: + from ray.util.state.state_cli import ( + ray_get, + ray_list, + logs_state_cli_group, + summary_state_cli_group, + ) + + cli.add_command(ray_list, name="list") + cli.add_command(ray_get, name="get") + add_command_alias(summary_state_cli_group, name="summary", hidden=False) + add_command_alias(logs_state_cli_group, name="logs", hidden=False) +except ImportError as e: + logger.debug(f"Integrating ray state command line tool failed: {e}") + + +try: + from ray.dashboard.modules.job.cli import job_cli_group + + add_command_alias(job_cli_group, name="job", hidden=False) +except Exception as e: + logger.debug(f"Integrating ray jobs command line tool failed with {e}") + + +try: + from ray.serve.scripts import serve_cli + + cli.add_command(serve_cli) +except Exception as e: + logger.debug(f"Integrating ray serve command line tool failed with {e}") + + +def main(): + return cli() + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/ray/serve/__init__.py b/venv/lib/python3.10/site-packages/ray/serve/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d5b38cf84feb7b5fd1a89577345a6481cffff31 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/__init__.py @@ -0,0 +1,63 @@ +import ray._private.worker + +try: + from ray.serve._private.logging_utils import configure_default_serve_logger + from ray.serve.api import ( + Application, + Deployment, + RunTarget, + _run, + _run_many, + delete, + deployment, + get_app_handle, + get_deployment_handle, + get_multiplexed_model_id, + get_replica_context, + ingress, + multiplexed, + run, + run_many, + shutdown, + start, + status, + ) + from ray.serve.batching import batch + from ray.serve.config import HTTPOptions + +except ModuleNotFoundError as e: + e.msg += ( + '. You can run `pip install "ray[serve]"` to install all Ray Serve' + " dependencies." + ) + raise e + +# Setup default ray.serve logger to ensure all serve module logs are captured. +configure_default_serve_logger() + +# Mute the warning because Serve sometimes intentionally calls +# ray.get inside async actors. +ray._private.worker.blocking_get_inside_async_warned = True + +__all__ = [ + "_run", + "_run_many", + "batch", + "start", + "HTTPOptions", + "get_replica_context", + "shutdown", + "ingress", + "deployment", + "run", + "run_many", + "RunTarget", + "delete", + "Application", + "Deployment", + "multiplexed", + "get_multiplexed_model_id", + "status", + "get_app_handle", + "get_deployment_handle", +] diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbffb595348ad2bbae2255a29e149fad0c4ca33a Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/api.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebd2cafb6d7eff92fab261dabcb3e19502606b57 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/api.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/autoscaling_policy.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/autoscaling_policy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c67ac4fc521dfae645fbe40116aeb34bf86ad211 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/autoscaling_policy.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/batching.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/batching.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e7d5999c96b98c41d95b69b199a082fe4cfe08d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/batching.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05660014ce02435485a7c241ed496220c6d5e4dc Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/context.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e166f167741cee2a73409a80e032678dca78957a Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/context.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/dag.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/dag.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4622d4b2abb4a35ea5cf8e5ee2e6b21857515772 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/dag.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/deployment.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/deployment.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9351ba8768416189e0db97144f6b08f2c060c426 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/deployment.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67f5e19b1208df0375e444d2a134f3058eea251f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/exceptions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/gradio_integrations.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/gradio_integrations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a8dde158b31c8fca8515aa6e1e28def12fbc572 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/gradio_integrations.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/grpc_util.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/grpc_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2f1068ed4c7332a4774aad314265831edf5b91b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/grpc_util.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/handle.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/handle.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87958adf8a6d318e47e49f2352e6c75ccd8ad1bb Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/handle.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/metrics.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/metrics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16486e69c47c8859bd2431ca99248bf6bc500e0c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/metrics.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/multiplex.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/multiplex.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5df4297c7f4738c4bf84f290690ae44e6aac28d5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/multiplex.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/request_router.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/request_router.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94695eefb592a792d34b3c8b478f7508544f790b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/request_router.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/schema.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/schema.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e360b74f6575524cdbeae4340e23fb09500696a0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/schema.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/__pycache__/scripts.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/scripts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..263305c20eacdc8fe126066520c91b1b12eecbde Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/__pycache__/scripts.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__init__.py b/venv/lib/python3.10/site-packages/ray/serve/_private/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e7ebce79dd826b347bf180c220c116c0c0174b0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/api.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7a04d860ff24260700b5f87dda6bc283352ecef Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/api.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/application_state.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/application_state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e98704389725b774aec98fbbccc4eef4547c1db0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/application_state.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/autoscaling_state.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/autoscaling_state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea9fd35619812a8bd600c7321c19363fb4b69d13 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/autoscaling_state.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/build_app.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/build_app.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6022293fabbf830181f1d16abd8130f3db17de93 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/build_app.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/client.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f9a5272afe616e566b72052b096104d47bceca8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/client.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/cluster_node_info_cache.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/cluster_node_info_cache.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a31a0f4700d2c04cbb4a176e4e11a0bc97ea2ba Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/cluster_node_info_cache.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/common.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b03157e193c06ec18d63a4c372ccb031b0816c21 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/common.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fc546039609cc0ad70880255838b39ed4b8f5fb Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/constants.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a436fd2be4cd510e6b3da9d30a1aa6b6451a97d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/constants.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/controller.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/controller.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f69c80254c50cb799aae0109d82ea38d36ab1d6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/controller.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/controller_avatar.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/controller_avatar.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4df8cf6356bb48dcfe551a9a4398b47dbfce99b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/controller_avatar.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/default_impl.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/default_impl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ced77cfbfecc7688a6f4c88b4943d25bc872ce70 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/default_impl.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deploy_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deploy_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcd6e74cd9f2db3ed3c4eee0c0ef65ad062d9ee0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deploy_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_info.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_info.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f24208ffb724d67f579bd6560c0dee7c4f03cd9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_info.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_node.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_node.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f67c4b2896543dd46c81d58627f10c7cfb01f11 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_node.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_scheduler.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..feb2e26469ec1e0238ee55354fd17135cfe1c0c6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_scheduler.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91f0856c07dc9381c7f799b0fa13d601f82fa243 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/endpoint_state.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/endpoint_state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..802a1fa9e5499381aec6f37897c69e58d22aea09 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/endpoint_state.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/grpc_util.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/grpc_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c01bf4fdf29ed3cc8b85841c54c45c6610245108 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/grpc_util.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/handle_options.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/handle_options.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffa9a7cacb5e59b1030bcbd95909fc73d0e28963 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/handle_options.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/http_util.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/http_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb937cab0b8a25b3a3d2d10a87c1fc67991aabe3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/http_util.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/local_testing_mode.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/local_testing_mode.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5df0d7f2e0245654cee811f2df656f0c8a79a826 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/local_testing_mode.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/logging_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/logging_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44e7886abfbc081ddae0b6aad8f3b159834d3e1c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/logging_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/long_poll.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/long_poll.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00d62c0def71f18bae9ae30c25cbd95b14619f98 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/long_poll.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/metrics_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/metrics_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e3c9c2ce239f92d04afadce2e5d9c6372d29f12 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/metrics_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9aea76530062f5189f254bf3d6139b14e41a071 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_request_response.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_request_response.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..561590999b9e73f5b6df506a5537a53469f8dd81 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_request_response.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_response_generator.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_response_generator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5de8b51784e13d7bae067517b1b7774eac4e9e9a Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_response_generator.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_router.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_router.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0d276d7fcb1e2159730001e76432ff51bdf3fdf Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_router.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_state.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f38c25e19c007cb45f4483d1b8492701db8224f6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/proxy_state.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/replica.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/replica.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1d7662dee11bb59f58aa9b73f6c04f0310461f0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/replica.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/replica_result.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/replica_result.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f40c96ce5298323e17cab00886111b1dfa2f7379 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/replica_result.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/router.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/router.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82face10dd49336505db300664a7287f3c07e9e9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/router.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/test_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/test_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57c7dad0b0b15271672d9f30d03bcecd5549c2b9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/test_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/usage.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/usage.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35469e708ac3e9f18575b165482334aa1317944d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/usage.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5699ea606af605bf5c1c5a5b24d833ef6cb2ac6b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/version.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..323bc65bf49cd42f86b4c626c6bd8c86c29aad24 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/__pycache__/version.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/api.py b/venv/lib/python3.10/site-packages/ray/serve/_private/api.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc1a79995f22c7401bf8454b718bdacc96d21e2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/api.py @@ -0,0 +1,281 @@ +import inspect +import logging +from types import FunctionType +from typing import Any, Dict, Union + +import ray +from ray._common.pydantic_compat import is_subclass_of_base_model +from ray._private.usage import usage_lib +from ray.actor import ActorHandle +from ray.serve._private.client import ServeControllerClient +from ray.serve._private.constants import ( + HTTP_PROXY_TIMEOUT, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.default_impl import get_controller_impl +from ray.serve.config import HTTPOptions, gRPCOptions +from ray.serve.context import _get_global_client, _set_global_client +from ray.serve.deployment import Application +from ray.serve.exceptions import RayServeException +from ray.serve.schema import LoggingConfig + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +def _check_http_options( + client: ServeControllerClient, http_options: Union[dict, HTTPOptions] +) -> None: + if http_options: + client_http_options = client.http_config + new_http_options = ( + http_options + if isinstance(http_options, HTTPOptions) + else HTTPOptions.parse_obj(http_options) + ) + different_fields = [] + all_http_option_fields = new_http_options.__dict__ + for field in all_http_option_fields: + if getattr(new_http_options, field) != getattr(client_http_options, field): + different_fields.append(field) + + if len(different_fields): + logger.warning( + "The new client HTTP config differs from the existing one " + f"in the following fields: {different_fields}. " + "The new HTTP config is ignored." + ) + + +def _start_controller( + http_options: Union[None, dict, HTTPOptions] = None, + grpc_options: Union[None, dict, gRPCOptions] = None, + global_logging_config: Union[None, dict, LoggingConfig] = None, + **kwargs, +) -> ActorHandle: + """Start Ray Serve controller. + + The function makes sure controller is ready to start deploying apps + after it returns. + + Parameters are same as ray.serve._private.api.serve_start(). + + Returns: controller actor handle. + """ + + # Initialize ray if needed. + ray._private.worker.global_worker._filter_logs_by_job = False + if not ray.is_initialized(): + ray.init(namespace=SERVE_NAMESPACE) + + # Legacy http proxy actor check + http_deprecated_args = ["http_host", "http_port", "http_middlewares"] + for key in http_deprecated_args: + if key in kwargs: + raise ValueError( + f"{key} is deprecated, please use serve.start(http_options=" + f'{{"{key}": {kwargs[key]}}}) instead.' + ) + + if isinstance(http_options, dict): + http_options = HTTPOptions.parse_obj(http_options) + if http_options is None: + http_options = HTTPOptions() + + if isinstance(grpc_options, dict): + grpc_options = gRPCOptions(**grpc_options) + + if global_logging_config is None: + global_logging_config = LoggingConfig() + elif isinstance(global_logging_config, dict): + global_logging_config = LoggingConfig(**global_logging_config) + + controller_impl = get_controller_impl() + controller = controller_impl.remote( + http_options=http_options, + grpc_options=grpc_options, + global_logging_config=global_logging_config, + ) + + proxy_handles = ray.get(controller.get_proxies.remote()) + if len(proxy_handles) > 0: + try: + ray.get( + [handle.ready.remote() for handle in proxy_handles.values()], + timeout=HTTP_PROXY_TIMEOUT, + ) + except ray.exceptions.GetTimeoutError: + raise TimeoutError( + f"HTTP proxies not available after {HTTP_PROXY_TIMEOUT}s." + ) + return controller + + +async def serve_start_async( + http_options: Union[None, dict, HTTPOptions] = None, + grpc_options: Union[None, dict, gRPCOptions] = None, + global_logging_config: Union[None, dict, LoggingConfig] = None, + **kwargs, +) -> ServeControllerClient: + """Initialize a serve instance asynchronously. + + This function is not thread-safe. The caller should maintain the async lock in order + to start the serve instance asynchronously. + + This function has the same functionality as ray.serve._private.api.serve_start(). + + Parameters & Returns are same as ray.serve._private.api.serve_start(). + """ + + usage_lib.record_library_usage("serve") + + try: + client = _get_global_client(_health_check_controller=True) + logger.info( + f'Connecting to existing Serve app in namespace "{SERVE_NAMESPACE}".' + " New http options will not be applied." + ) + if http_options: + _check_http_options(client, http_options) + return client + except RayServeException: + pass + + controller = ( + await ray.remote(_start_controller) + .options(num_cpus=0) + .remote(http_options, grpc_options, global_logging_config, **kwargs) + ) + + client = ServeControllerClient( + controller, + ) + _set_global_client(client) + logger.info(f'Started Serve in namespace "{SERVE_NAMESPACE}".') + return client + + +def serve_start( + http_options: Union[None, dict, HTTPOptions] = None, + grpc_options: Union[None, dict, gRPCOptions] = None, + global_logging_config: Union[None, dict, LoggingConfig] = None, + **kwargs, +) -> ServeControllerClient: + """Initialize a serve instance. + + By default, the instance will be scoped to the lifetime of the returned + Client object (or when the script exits). This is + only relevant if connecting to a long-running Ray cluster (e.g., with + ray.init(address="auto") or ray.init("ray://")). + + Args: + http_options (Optional[Dict, serve.HTTPOptions]): Configuration options + for HTTP proxy. You can pass in a dictionary or HTTPOptions object + with fields: + + - host(str, None): Host for HTTP servers to listen on. Defaults to + "127.0.0.1". To expose Serve publicly, you probably want to set + this to "0.0.0.0". + - port(int): Port for HTTP server. Defaults to 8000. + - root_path(str): Root path to mount the serve application + (for example, "/serve"). All deployment routes will be prefixed + with this path. Defaults to "". + - middlewares(list): A list of Starlette middlewares that will be + applied to the HTTP servers in the cluster. Defaults to []. + - location(str, serve.config.DeploymentMode): The deployment + location of HTTP servers: + + - "HeadOnly": start one HTTP server on the head node. Serve + assumes the head node is the node you executed serve.start + on. This is the default. + - "EveryNode": start one HTTP server per node. + - "NoServer" or None: disable HTTP server. + - num_cpus (int): The number of CPU cores to reserve for each + internal Serve HTTP proxy actor. Defaults to 0. + grpc_options: [Experimental] Configuration options for gRPC proxy. + You can pass in a gRPCOptions object with fields: + + - port(int): Port for gRPC server. Defaults to 9000. + - grpc_servicer_functions(list): List of import paths for gRPC + `add_servicer_to_server` functions to add to Serve's gRPC proxy. + Default empty list, meaning not to start the gRPC server. + """ + + usage_lib.record_library_usage("serve") + + try: + client = _get_global_client(_health_check_controller=True) + logger.info( + f'Connecting to existing Serve app in namespace "{SERVE_NAMESPACE}".' + " New http options will not be applied." + ) + if http_options: + _check_http_options(client, http_options) + return client + except RayServeException: + pass + + controller = _start_controller( + http_options, grpc_options, global_logging_config, **kwargs + ) + + client = ServeControllerClient( + controller, + ) + _set_global_client(client) + logger.info(f'Started Serve in namespace "{SERVE_NAMESPACE}".') + return client + + +def call_user_app_builder_with_args_if_necessary( + builder: Union[Application, FunctionType], + args: Dict[str, Any], +) -> Application: + """Calls a user-provided function that returns Serve application. + + If an Application object is passed, this is a no-op. + + Else, we validate the signature of the function, convert the args dictionary to + the user-annotated Pydantic model if provided, and call the function. + + The output of the function is returned (must be an Application). + """ + if isinstance(builder, Application): + if len(args) > 0: + raise ValueError( + "Arguments can only be passed to an application builder function, " + "not an already built application." + ) + return builder + elif not isinstance(builder, FunctionType): + raise TypeError( + "Expected a built Serve application or an application builder function " + f"but got: {type(builder)}." + ) + + # Check that the builder only takes a single argument. + # TODO(edoakes): we may want to loosen this to allow optional kwargs in the future. + signature = inspect.signature(builder) + if len(signature.parameters) != 1: + raise TypeError( + "Application builder functions should take exactly one parameter, " + "a dictionary containing the passed arguments." + ) + + # If the sole argument to the builder is a pydantic model, convert the args dict to + # that model. This will perform standard pydantic validation (e.g., raise an + # exception if required fields are missing). + param = signature.parameters[list(signature.parameters.keys())[0]] + if inspect.isclass(param.annotation) and is_subclass_of_base_model( + param.annotation + ): + args = param.annotation.parse_obj(args) + + app = builder(args) + if not isinstance(app, Application): + raise TypeError( + "Application builder functions must return an `Application` returned " + f"`from `Deployment.bind()`, but got: {type(app)}." + ) + + return app diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/application_state.py b/venv/lib/python3.10/site-packages/ray/serve/_private/application_state.py new file mode 100644 index 0000000000000000000000000000000000000000..f9af04ef10857febe9f8be83fb919935405a2a10 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/application_state.py @@ -0,0 +1,1389 @@ +import inspect +import json +import logging +import os +import time +import traceback +from copy import deepcopy +from dataclasses import asdict, dataclass, field +from enum import Enum +from typing import Dict, List, Optional, Tuple + +import ray +from ray import cloudpickle +from ray._common.utils import import_attr +from ray.exceptions import RuntimeEnvSetupError +from ray.serve._private.build_app import BuiltApplication, build_app +from ray.serve._private.common import ( + DeploymentID, + DeploymentStatus, + DeploymentStatusInfo, + DeploymentStatusTrigger, + EndpointInfo, + TargetCapacityDirection, +) +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import RAY_SERVE_ENABLE_TASK_EVENTS, SERVE_LOGGER_NAME +from ray.serve._private.deploy_utils import ( + deploy_args_to_deployment_info, + get_app_code_version, + get_deploy_args, +) +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.deployment_state import DeploymentStateManager +from ray.serve._private.endpoint_state import EndpointState +from ray.serve._private.logging_utils import configure_component_logger +from ray.serve._private.storage.kv_store import KVStoreBase +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + DEFAULT, + check_obj_ref_ready_nowait, + override_runtime_envs_except_env_vars, + validate_route_prefix, +) +from ray.serve.api import ASGIAppReplicaWrapper +from ray.serve.config import AutoscalingConfig +from ray.serve.exceptions import RayServeException +from ray.serve.generated.serve_pb2 import ( + ApplicationStatus as ApplicationStatusProto, + ApplicationStatusInfo as ApplicationStatusInfoProto, + DeploymentLanguage, + DeploymentStatusInfoList as DeploymentStatusInfoListProto, + StatusOverview as StatusOverviewProto, +) +from ray.serve.schema import ( + APIType, + ApplicationStatus, + DeploymentDetails, + LoggingConfig, + ServeApplicationSchema, +) +from ray.types import ObjectRef + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +CHECKPOINT_KEY = "serve-application-state-checkpoint" + + +class BuildAppStatus(Enum): + """Status of the build application task.""" + + NO_TASK_IN_PROGRESS = 1 + IN_PROGRESS = 2 + SUCCEEDED = 3 + FAILED = 4 + + +@dataclass +class BuildAppTaskInfo: + """Stores info on the current in-progress build app task. + + We use a class instead of only storing the task object ref because + when a new config is deployed, there can be an outdated in-progress + build app task. We attach the code version to the task info to + distinguish outdated build app tasks. + """ + + obj_ref: ObjectRef + code_version: str + config: ServeApplicationSchema + target_capacity: Optional[float] + target_capacity_direction: Optional[TargetCapacityDirection] + finished: bool + + +@dataclass(eq=True) +class ApplicationStatusInfo: + status: ApplicationStatus + message: str = "" + deployment_timestamp: float = 0 + + def debug_string(self): + return json.dumps(asdict(self), indent=4) + + def to_proto(self): + return ApplicationStatusInfoProto( + status=f"APPLICATION_STATUS_{self.status.name}", + message=self.message, + deployment_timestamp=self.deployment_timestamp, + ) + + @classmethod + def from_proto(cls, proto: ApplicationStatusInfoProto): + status = ApplicationStatusProto.Name(proto.status)[len("APPLICATION_STATUS_") :] + return cls( + status=ApplicationStatus(status), + message=proto.message, + deployment_timestamp=proto.deployment_timestamp, + ) + + +@dataclass(eq=True) +class StatusOverview: + app_status: ApplicationStatusInfo + name: str = "" + deployment_statuses: List[DeploymentStatusInfo] = field(default_factory=list) + + def debug_string(self): + return json.dumps(asdict(self), indent=4) + + def get_deployment_status(self, name: str) -> Optional[DeploymentStatusInfo]: + """Get a deployment's status by name. + + Args: + name: Deployment's name. + + Returns: + Optional[DeploymentStatusInfo]: The status of the deployment if it exists, + otherwise None. + """ + + for deployment_status in self.deployment_statuses: + if name == deployment_status.name: + return deployment_status + + return None + + def to_proto(self): + # Create a protobuf for the Serve Application info + app_status_proto = self.app_status.to_proto() + + # Create protobufs for all individual deployment statuses + deployment_status_protos = map( + lambda status: status.to_proto(), self.deployment_statuses + ) + + # Create a protobuf list containing all the deployment status protobufs + deployment_status_proto_list = DeploymentStatusInfoListProto() + deployment_status_proto_list.deployment_status_infos.extend( + deployment_status_protos + ) + + # Return protobuf encapsulating application and deployment protos + return StatusOverviewProto( + name=self.name, + app_status=app_status_proto, + deployment_statuses=deployment_status_proto_list, + ) + + @classmethod + def from_proto(cls, proto: StatusOverviewProto) -> "StatusOverview": + # Recreate Serve Application info + app_status = ApplicationStatusInfo.from_proto(proto.app_status) + + # Recreate deployment statuses + deployment_statuses = [] + for info_proto in proto.deployment_statuses.deployment_status_infos: + deployment_statuses.append(DeploymentStatusInfo.from_proto(info_proto)) + + # Recreate StatusInfo + return cls( + app_status=app_status, + deployment_statuses=deployment_statuses, + name=proto.name, + ) + + +@dataclass +class ApplicationTargetState: + """Defines target state of application. + + Target state can become inconsistent if the code version doesn't + match that of the config. When that happens, a new build app task + should be kicked off to reconcile the inconsistency. + + deployment_infos: map of deployment name to deployment info. This is + - None if a config was deployed but the app hasn't finished + building yet, + - An empty dict if the app is deleting. + code_version: Code version of all deployments in target state. None + if application was deployed through serve.run. + config: application config deployed by user. None if application was + deployed through serve.run. + target_capacity: the target_capacity to use when adjusting num_replicas. + target_capacity_direction: the scale direction to use when + running the Serve autoscaler. + deleting: whether the application is being deleted. + """ + + deployment_infos: Optional[Dict[str, DeploymentInfo]] + code_version: Optional[str] + config: Optional[ServeApplicationSchema] + target_capacity: Optional[float] + target_capacity_direction: Optional[TargetCapacityDirection] + deleting: bool + api_type: APIType + + +class ApplicationState: + """Manage single application states with all operations""" + + def __init__( + self, + name: str, + deployment_state_manager: DeploymentStateManager, + endpoint_state: EndpointState, + logging_config: LoggingConfig, + ): + """ + Args: + name: Application name. + deployment_state_manager: State manager for all deployments + in the cluster. + endpoint_state: State manager for endpoints in the system. + """ + + self._name = name + self._status_msg = "" + self._deployment_state_manager = deployment_state_manager + self._endpoint_state = endpoint_state + self._route_prefix: Optional[str] = None + self._docs_path: Optional[str] = None + self._ingress_deployment_name: Optional[str] = None + + self._status: ApplicationStatus = ApplicationStatus.DEPLOYING + self._deployment_timestamp = time.time() + + self._build_app_task_info: Optional[BuildAppTaskInfo] = None + # Before a deploy app task finishes, we don't know what the + # target deployments are, so set deployment_infos=None + self._target_state: ApplicationTargetState = ApplicationTargetState( + deployment_infos=None, + code_version=None, + config=None, + target_capacity=None, + target_capacity_direction=None, + deleting=False, + api_type=APIType.UNKNOWN, + ) + self._logging_config = logging_config + + @property + def route_prefix(self) -> Optional[str]: + return self._route_prefix + + @property + def docs_path(self) -> Optional[str]: + # if the docs path is set during the deploy app task, use that + # TODO (abrar): this can be dropped completely in favor of the + # deployment state manager once we have migrated all the tests + # to the new API. + if self._docs_path is not None: + return self._docs_path + + # else get the docs path from the running deployments + # we are making an assumption that the docs path can only be set + # on ingress deployments with fastapi. + ingress_deployment = DeploymentID(self._ingress_deployment_name, self._name) + return self._deployment_state_manager.get_deployment_docs_path( + ingress_deployment + ) + + @property + def status(self) -> ApplicationStatus: + """Status of the application. + + DEPLOYING: The build task is still running, or the deployments + have started deploying but aren't healthy yet. + RUNNING: All deployments are healthy. + DEPLOY_FAILED: The build task failed or one or more deployments + became unhealthy in the process of deploying + UNHEALTHY: While the application was running, one or more + deployments transition from healthy to unhealthy. + DELETING: Application and its deployments are being deleted. + """ + return self._status + + @property + def deployment_timestamp(self) -> float: + return self._deployment_timestamp + + @property + def target_deployments(self) -> List[str]: + """List of target deployment names in application.""" + if self._target_state.deployment_infos is None: + return [] + return list(self._target_state.deployment_infos.keys()) + + @property + def ingress_deployment(self) -> Optional[str]: + return self._ingress_deployment_name + + @property + def api_type(self) -> APIType: + return self._target_state.api_type + + def recover_target_state_from_checkpoint( + self, checkpoint_data: ApplicationTargetState + ): + logger.info( + f"Recovering target state for application '{self._name}' from checkpoint." + ) + self._set_target_state( + checkpoint_data.deployment_infos, + api_type=checkpoint_data.api_type, + code_version=checkpoint_data.code_version, + target_config=checkpoint_data.config, + target_capacity=checkpoint_data.target_capacity, + target_capacity_direction=checkpoint_data.target_capacity_direction, + deleting=checkpoint_data.deleting, + ) + + # Restore route prefix and docs path from checkpointed deployments when + # the imperatively started application is restarting with controller. + if checkpoint_data.deployment_infos is not None: + self._route_prefix, self._docs_path = self._check_routes( + checkpoint_data.deployment_infos + ) + + def _set_target_state( + self, + deployment_infos: Optional[Dict[str, DeploymentInfo]], + *, + api_type: APIType, + code_version: Optional[str], + target_config: Optional[ServeApplicationSchema], + target_capacity: Optional[float] = None, + target_capacity_direction: Optional[TargetCapacityDirection] = None, + deleting: bool = False, + ): + """Set application target state. + + While waiting for build task to finish, this should be + (None, False) + When build task has finished and during normal operation, this should be + (target_deployments, False) + When a request to delete the application has been received, this should be + ({}, True) + """ + if deleting: + self._update_status(ApplicationStatus.DELETING) + else: + self._update_status(ApplicationStatus.DEPLOYING) + + if deployment_infos is None: + self._ingress_deployment_name = None + else: + for name, info in deployment_infos.items(): + if info.ingress: + self._ingress_deployment_name = name + + target_state = ApplicationTargetState( + deployment_infos, + code_version, + target_config, + target_capacity, + target_capacity_direction, + deleting, + api_type=api_type, + ) + + self._target_state = target_state + + def _set_target_state_deleting(self): + """Set target state to deleting. + + Wipes the target deployment infos, code version, and config. + """ + self._set_target_state( + deployment_infos={}, + api_type=self._target_state.api_type, + code_version=None, + target_config=None, + deleting=True, + ) + + def _clear_target_state_and_store_config( + self, + target_config: Optional[ServeApplicationSchema], + ): + """Clears the target state and stores the config. + + NOTE: this currently assumes that this method is *only* called when managing + apps deployed with the declarative API. + """ + self._set_target_state( + deployment_infos=None, + api_type=APIType.DECLARATIVE, + code_version=None, + target_config=target_config, + deleting=False, + ) + + def _delete_deployment(self, name): + id = DeploymentID(name=name, app_name=self._name) + self._endpoint_state.delete_endpoint(id) + self._deployment_state_manager.delete_deployment(id) + + def delete(self): + """Delete the application""" + if self._status != ApplicationStatus.DELETING: + logger.info( + f"Deleting app '{self._name}'.", + extra={"log_to_stderr": False}, + ) + self._set_target_state_deleting() + + def is_deleted(self) -> bool: + """Check whether the application is already deleted. + + For an application to be considered deleted, the target state has to be set to + deleting and all deployments have to be deleted. + """ + return self._target_state.deleting and len(self._get_live_deployments()) == 0 + + def apply_deployment_info( + self, + deployment_name: str, + deployment_info: DeploymentInfo, + ) -> None: + """Deploys a deployment in the application.""" + route_prefix = deployment_info.route_prefix + if route_prefix is not None and not route_prefix.startswith("/"): + raise RayServeException( + f'Invalid route prefix "{route_prefix}", it must start with "/"' + ) + + deployment_id = DeploymentID(name=deployment_name, app_name=self._name) + + self._deployment_state_manager.deploy(deployment_id, deployment_info) + + if deployment_info.route_prefix is not None: + config = deployment_info.deployment_config + self._endpoint_state.update_endpoint( + deployment_id, + # The current meaning of the "is_cross_language" field is ambiguous. + # We will work on optimizing and removing this field in the future. + # Instead of using the "is_cross_language" field, we will directly + # compare if the replica is Python, which will assist the Python + # router in determining if the replica invocation is a cross-language + # operation. + EndpointInfo( + route=deployment_info.route_prefix, + app_is_cross_language=config.deployment_language + != DeploymentLanguage.PYTHON, + ), + ) + else: + self._endpoint_state.delete_endpoint(deployment_id) + + def deploy_app(self, deployment_infos: Dict[str, DeploymentInfo]): + """(Re-)deploy the application from list of deployment infos. + + This function should only be called to deploy an app from an + imperative API (i.e., `serve.run` or Java API). + + Raises: RayServeException if there is more than one route prefix + or docs path. + """ + + self._check_ingress_deployments(deployment_infos) + # Check routes are unique in deployment infos + self._route_prefix, self._docs_path = self._check_routes(deployment_infos) + + self._set_target_state( + deployment_infos=deployment_infos, + api_type=APIType.IMPERATIVE, + code_version=None, + target_config=None, + target_capacity=None, + target_capacity_direction=None, + ) + + def apply_app_config( + self, + config: ServeApplicationSchema, + target_capacity: Optional[float], + target_capacity_direction: Optional[TargetCapacityDirection], + deployment_time: float, + ) -> None: + """Apply the config to the application. + + If the code version matches that of the current live deployments + then it only applies the updated config to the deployment state + manager. If the code version doesn't match, this will re-build + the application. + + This function should only be called to (re-)deploy an app from + the declarative API (i.e., through the REST API). + """ + + self._deployment_timestamp = deployment_time + + config_version = get_app_code_version(config) + if config_version == self._target_state.code_version: + try: + overrided_infos = override_deployment_info( + self._target_state.deployment_infos, + config, + ) + self._route_prefix, self._docs_path = self._check_routes( + overrided_infos + ) + self._set_target_state( + # Code version doesn't change. + code_version=self._target_state.code_version, + api_type=APIType.DECLARATIVE, + # Everything else must reflect the new config. + deployment_infos=overrided_infos, + target_config=config, + target_capacity=target_capacity, + target_capacity_direction=target_capacity_direction, + ) + except (TypeError, ValueError, RayServeException): + self._clear_target_state_and_store_config(config) + self._update_status( + ApplicationStatus.DEPLOY_FAILED, traceback.format_exc() + ) + except Exception: + self._clear_target_state_and_store_config(config) + self._update_status( + ApplicationStatus.DEPLOY_FAILED, + ( + f"Unexpected error occurred while applying config for " + f"application '{self._name}': \n{traceback.format_exc()}" + ), + ) + else: + # If there is an in progress build task, cancel it. + if self._build_app_task_info and not self._build_app_task_info.finished: + logger.info( + f"Received new config for application '{self._name}'. " + "Cancelling previous request." + ) + ray.cancel(self._build_app_task_info.obj_ref) + + # Halt reconciliation of target deployments. A new target state + # will be set once the new app has finished building. + self._clear_target_state_and_store_config(config) + + # Record telemetry for container runtime env feature + if self._target_state.config.runtime_env.get( + "container" + ) or self._target_state.config.runtime_env.get("image_uri"): + ServeUsageTag.APP_CONTAINER_RUNTIME_ENV_USED.record("1") + + # Kick off new build app task + logger.info(f"Importing and building app '{self._name}'.") + build_app_obj_ref = build_serve_application.options( + runtime_env=config.runtime_env, + enable_task_events=RAY_SERVE_ENABLE_TASK_EVENTS, + ).remote( + config.import_path, + config_version, + config.name, + config.args, + self._logging_config, + ) + self._build_app_task_info = BuildAppTaskInfo( + obj_ref=build_app_obj_ref, + code_version=config_version, + config=config, + target_capacity=target_capacity, + target_capacity_direction=target_capacity_direction, + finished=False, + ) + + def _get_live_deployments(self) -> List[str]: + return self._deployment_state_manager.get_deployments_in_application(self._name) + + def _determine_app_status(self) -> Tuple[ApplicationStatus, str]: + """Check deployment statuses and target state, and determine the + corresponding application status. + + Returns: + Status (ApplicationStatus): + RUNNING: all deployments are healthy or autoscaling. + DEPLOYING: there is one or more updating deployments, + and there are no unhealthy deployments. + DEPLOY_FAILED: one or more deployments became unhealthy + while the application was deploying. + UNHEALTHY: one or more deployments became unhealthy + while the application was running. + DELETING: the application is being deleted. + Error message (str): + Non-empty string if status is DEPLOY_FAILED or UNHEALTHY + """ + + if self._target_state.deleting: + return ApplicationStatus.DELETING, "" + + # Get the lowest rank, i.e. highest priority, deployment status info object + # The deployment status info with highest priority determines the corresponding + # application status to set. + deployment_statuses = self.get_deployments_statuses() + lowest_rank_status = min(deployment_statuses, key=lambda info: info.rank) + if lowest_rank_status.status == DeploymentStatus.DEPLOY_FAILED: + failed_deployments = [ + s.name + for s in deployment_statuses + if s.status == DeploymentStatus.DEPLOY_FAILED + ] + return ( + ApplicationStatus.DEPLOY_FAILED, + f"Failed to update the deployments {failed_deployments}.", + ) + elif lowest_rank_status.status == DeploymentStatus.UNHEALTHY: + unhealthy_deployment_names = [ + s.name + for s in deployment_statuses + if s.status == DeploymentStatus.UNHEALTHY + ] + return ( + ApplicationStatus.UNHEALTHY, + f"The deployments {unhealthy_deployment_names} are UNHEALTHY.", + ) + elif lowest_rank_status.status == DeploymentStatus.UPDATING: + return ApplicationStatus.DEPLOYING, "" + elif ( + lowest_rank_status.status + in [DeploymentStatus.UPSCALING, DeploymentStatus.DOWNSCALING] + and lowest_rank_status.status_trigger + == DeploymentStatusTrigger.CONFIG_UPDATE_STARTED + ): + return ApplicationStatus.DEPLOYING, "" + else: + return ApplicationStatus.RUNNING, "" + + def _reconcile_build_app_task(self) -> Tuple[Optional[Dict], BuildAppStatus, str]: + """If necessary, reconcile the in-progress build task. + + Returns: + Deploy arguments (Dict[str, DeploymentInfo]): + The deploy arguments returned from the build app task + and their code version. + Status (BuildAppStatus): + NO_TASK_IN_PROGRESS: There is no build task to reconcile. + SUCCEEDED: Task finished successfully. + FAILED: An error occurred during execution of build app task + IN_PROGRESS: Task hasn't finished yet. + Error message (str): + Non-empty string if status is DEPLOY_FAILED or UNHEALTHY + """ + if self._build_app_task_info is None or self._build_app_task_info.finished: + return None, BuildAppStatus.NO_TASK_IN_PROGRESS, "" + + if not check_obj_ref_ready_nowait(self._build_app_task_info.obj_ref): + return None, BuildAppStatus.IN_PROGRESS, "" + + # Retrieve build app task result + self._build_app_task_info.finished = True + try: + args, err = ray.get(self._build_app_task_info.obj_ref) + if err is None: + logger.info(f"Imported and built app '{self._name}' successfully.") + else: + return ( + None, + BuildAppStatus.FAILED, + f"Deploying app '{self._name}' failed with exception:\n{err}", + ) + except RuntimeEnvSetupError: + error_msg = ( + f"Runtime env setup for app '{self._name}' failed:\n" + + traceback.format_exc() + ) + return None, BuildAppStatus.FAILED, error_msg + except Exception: + error_msg = ( + f"Unexpected error occurred while deploying application " + f"'{self._name}': \n{traceback.format_exc()}" + ) + return None, BuildAppStatus.FAILED, error_msg + + # Convert serialized deployment args (returned by build app task) + # to deployment infos and apply option overrides from config + try: + deployment_infos = { + params["deployment_name"]: deploy_args_to_deployment_info( + **params, app_name=self._name + ) + for params in args + } + overrided_infos = override_deployment_info( + deployment_infos, self._build_app_task_info.config + ) + self._route_prefix, self._docs_path = self._check_routes(overrided_infos) + return overrided_infos, BuildAppStatus.SUCCEEDED, "" + except (TypeError, ValueError, RayServeException): + return None, BuildAppStatus.FAILED, traceback.format_exc() + except Exception: + error_msg = ( + f"Unexpected error occurred while applying config for application " + f"'{self._name}': \n{traceback.format_exc()}" + ) + return None, BuildAppStatus.FAILED, error_msg + + def _check_ingress_deployments( + self, deployment_infos: Dict[str, DeploymentInfo] + ) -> None: + """Check @serve.ingress of deployments in app. + + Raises: RayServeException if more than one @serve.ingress + is found among deployments. + """ + num_ingress_deployments = 0 + for info in deployment_infos.values(): + if inspect.isclass(info.replica_config.deployment_def) and issubclass( + info.replica_config.deployment_def, ASGIAppReplicaWrapper + ): + num_ingress_deployments += 1 + + if num_ingress_deployments > 1: + raise RayServeException( + f'Found multiple FastAPI deployments in application "{self._name}".' + "Please only include one deployment with @serve.ingress" + "in your application to avoid this issue." + ) + + def _check_routes( + self, deployment_infos: Dict[str, DeploymentInfo] + ) -> Tuple[str, str]: + """Check route prefixes and docs paths of deployments in app. + + There should only be one non-null route prefix. If there is one, + set it as the application route prefix. This function must be + run every control loop iteration because the target config could + be updated without kicking off a new task. + + Returns: tuple of route prefix, docs path. + Raises: RayServeException if more than one route prefix or docs + path is found among deployments. + """ + num_route_prefixes = 0 + num_docs_paths = 0 + route_prefix = None + # TODO(Ziy1-Tan): `docs_path` will be removed when + # https://github.com/ray-project/ray/issues/53023 is resolved. + # We can get it from DeploymentStateManager directly. + docs_path = None + for info in deployment_infos.values(): + # Update route prefix of application, which may be updated + # through a redeployed config. + if info.route_prefix is not None: + route_prefix = info.route_prefix + num_route_prefixes += 1 + if info.docs_path is not None: + docs_path = info.docs_path + num_docs_paths += 1 + + if num_route_prefixes > 1: + raise RayServeException( + f'Found multiple route prefixes from application "{self._name}",' + " Please specify only one route prefix for the application " + "to avoid this issue." + ) + # NOTE(zcin) This will not catch multiple FastAPI deployments in the application + # if user sets the docs path to None in their FastAPI app. + if num_docs_paths > 1: + raise RayServeException( + f'Found multiple deployments in application "{self._name}" that have ' + "a docs path. This may be due to using multiple FastAPI deployments " + "in your application. Please only include one deployment with a docs " + "path in your application to avoid this issue." + ) + + return route_prefix, docs_path + + def _reconcile_target_deployments(self) -> None: + """Reconcile target deployments in application target state. + + Ensure each deployment is running on up-to-date info, and + remove outdated deployments from the application. + """ + + # Set target state for each deployment + for deployment_name, info in self._target_state.deployment_infos.items(): + deploy_info = deepcopy(info) + + # Apply the target capacity information to the deployment info. + deploy_info.set_target_capacity( + new_target_capacity=self._target_state.target_capacity, + new_target_capacity_direction=( + self._target_state.target_capacity_direction + ), + ) + + # Apply the application logging config to the deployment logging config + # if it is not set. + if ( + self._target_state.config + and self._target_state.config.logging_config + and deploy_info.deployment_config.logging_config is None + ): + deploy_info.deployment_config.logging_config = ( + self._target_state.config.logging_config + ) + self.apply_deployment_info(deployment_name, deploy_info) + + # Delete outdated deployments + for deployment_name in self._get_live_deployments(): + if deployment_name not in self.target_deployments: + self._delete_deployment(deployment_name) + + def update(self) -> bool: + """Attempts to reconcile this application to match its target state. + + Updates the application status and status message based on the + current state of the system. + + Returns: + A boolean indicating whether the application is ready to be + deleted. + """ + + infos, task_status, msg = self._reconcile_build_app_task() + if task_status == BuildAppStatus.SUCCEEDED: + self._set_target_state( + deployment_infos=infos, + code_version=self._build_app_task_info.code_version, + api_type=self._target_state.api_type, + target_config=self._build_app_task_info.config, + target_capacity=self._build_app_task_info.target_capacity, + target_capacity_direction=( + self._build_app_task_info.target_capacity_direction + ), + ) + elif task_status == BuildAppStatus.FAILED: + self._update_status(ApplicationStatus.DEPLOY_FAILED, msg) + + # Only reconcile deployments when the build app task is finished. If + # it's not finished, we don't know what the target list of deployments + # is, so we don't perform any reconciliation. + if self._target_state.deployment_infos is not None: + self._reconcile_target_deployments() + status, status_msg = self._determine_app_status() + self._update_status(status, status_msg) + + # Check if app is ready to be deleted + if self._target_state.deleting: + return self.is_deleted() + return False + + def get_checkpoint_data(self) -> ApplicationTargetState: + return self._target_state + + def get_deployments_statuses(self) -> List[DeploymentStatusInfo]: + """Return all deployment status information""" + deployments = [ + DeploymentID(name=deployment, app_name=self._name) + for deployment in self.target_deployments + ] + return self._deployment_state_manager.get_deployment_statuses(deployments) + + def get_application_status_info(self) -> ApplicationStatusInfo: + """Return the application status information""" + return ApplicationStatusInfo( + self._status, + message=self._status_msg, + deployment_timestamp=self._deployment_timestamp, + ) + + def list_deployment_details(self) -> Dict[str, DeploymentDetails]: + """Gets detailed info on all live deployments in this application. + (Does not include deleted deployments.) + + Returns: + A dictionary of deployment infos. The set of deployment info returned + may not be the full list of deployments that are part of the application. + This can happen when the application is still deploying and bringing up + deployments, or when the application is deleting and some deployments have + been deleted. + """ + details = { + deployment_name: self._deployment_state_manager.get_deployment_details( + DeploymentID(name=deployment_name, app_name=self._name) + ) + for deployment_name in self.target_deployments + } + return {k: v for k, v in details.items() if v is not None} + + def _update_status(self, status: ApplicationStatus, status_msg: str = "") -> None: + if ( + status_msg + and status + in [ + ApplicationStatus.DEPLOY_FAILED, + ApplicationStatus.UNHEALTHY, + ] + and status_msg != self._status_msg + ): + logger.error(status_msg) + + self._status = status + self._status_msg = status_msg + + +class ApplicationStateManager: + def __init__( + self, + deployment_state_manager: DeploymentStateManager, + endpoint_state: EndpointState, + kv_store: KVStoreBase, + logging_config: LoggingConfig, + ): + self._deployment_state_manager = deployment_state_manager + self._endpoint_state = endpoint_state + self._kv_store = kv_store + self._logging_config = logging_config + + self._shutting_down = False + + self._application_states: Dict[str, ApplicationState] = {} + self._recover_from_checkpoint() + + def _recover_from_checkpoint(self): + checkpoint = self._kv_store.get(CHECKPOINT_KEY) + if checkpoint is not None: + application_state_info = cloudpickle.loads(checkpoint) + + for app_name, checkpoint_data in application_state_info.items(): + app_state = ApplicationState( + app_name, + self._deployment_state_manager, + self._endpoint_state, + self._logging_config, + ) + app_state.recover_target_state_from_checkpoint(checkpoint_data) + self._application_states[app_name] = app_state + + def delete_app(self, name: str) -> None: + """Delete application by name""" + if name not in self._application_states: + return + self._application_states[name].delete() + + def deploy_apps(self, name_to_deployment_args: Dict[str, List[Dict]]) -> None: + live_route_prefixes: Dict[str, str] = { + app_state.route_prefix: app_name + for app_name, app_state in self._application_states.items() + if app_state.route_prefix is not None + and not app_state.status == ApplicationStatus.DELETING + } + + for name, deployment_args in name_to_deployment_args.items(): + for deploy_param in deployment_args: + # Make sure route_prefix is not being used by other application. + deploy_app_prefix = deploy_param.get("route_prefix") + if deploy_app_prefix is None: + continue + + existing_app_name = live_route_prefixes.get(deploy_app_prefix) + # It's ok to redeploy an app with the same prefix + # if it has the same name as the app already using that prefix. + if existing_app_name is not None and existing_app_name != name: + raise RayServeException( + f"Prefix {deploy_app_prefix} is being used by application " + f'"{existing_app_name}". Failed to deploy application "{name}".' + ) + + # We might be deploying more than one app, + # so we need to add this app's prefix to the + # set of live route prefixes that we're checking + # against during this batch operation. + live_route_prefixes[deploy_app_prefix] = name + + if name not in self._application_states: + self._application_states[name] = ApplicationState( + name, + self._deployment_state_manager, + self._endpoint_state, + self._logging_config, + ) + ServeUsageTag.NUM_APPS.record(str(len(self._application_states))) + + deployment_infos = { + params["deployment_name"]: deploy_args_to_deployment_info( + **params, app_name=name + ) + for params in deployment_args + } + self._application_states[name].deploy_app(deployment_infos) + + def deploy_app(self, name: str, deployment_args: List[Dict]) -> None: + """Deploy the specified app to the list of deployment arguments. + + This function should only be called if the app is being deployed + through serve.run instead of from a config. + + Args: + name: application name + deployment_args_list: arguments for deploying a list of deployments. + + Raises: + RayServeException: If the list of deployments is trying to + use a route prefix that is already used by another application + """ + self.deploy_apps({name: deployment_args}) + + def apply_app_configs( + self, + app_configs: List[ServeApplicationSchema], + *, + deployment_time: float = 0, + target_capacity: Optional[float] = None, + target_capacity_direction: Optional[TargetCapacityDirection] = None, + ): + """Declaratively apply the list of application configs. + + The applications will be reconciled to match the target state of the config. + + Any applications previously deployed declaratively that are *not* present in + the list will be deleted. + """ + for app_config in app_configs: + if app_config.name not in self._application_states: + logger.info(f"Deploying new app '{app_config.name}'.") + self._application_states[app_config.name] = ApplicationState( + app_config.name, + self._deployment_state_manager, + endpoint_state=self._endpoint_state, + logging_config=self._logging_config, + ) + + self._application_states[app_config.name].apply_app_config( + app_config, + target_capacity, + target_capacity_direction, + deployment_time=deployment_time, + ) + + # Delete all apps that were previously deployed via the declarative API + # but are not in the config being applied. + existing_apps = { + name + for name, app_state in self._application_states.items() + if app_state.api_type == APIType.DECLARATIVE + } + apps_in_config = {app_config.name for app_config in app_configs} + for app_to_delete in existing_apps - apps_in_config: + self.delete_app(app_to_delete) + + ServeUsageTag.NUM_APPS.record(str(len(self._application_states))) + + def get_deployments(self, app_name: str) -> List[str]: + """Return all deployment names by app name""" + if app_name not in self._application_states: + return [] + return self._application_states[app_name].target_deployments + + def get_deployments_statuses(self, app_name: str) -> List[DeploymentStatusInfo]: + """Return all deployment statuses by app name""" + if app_name not in self._application_states: + return [] + return self._application_states[app_name].get_deployments_statuses() + + def get_app_status(self, name: str) -> ApplicationStatus: + if name not in self._application_states: + return ApplicationStatus.NOT_STARTED + + return self._application_states[name].status + + def get_app_status_info(self, name: str) -> ApplicationStatusInfo: + if name not in self._application_states: + return ApplicationStatusInfo( + ApplicationStatus.NOT_STARTED, + message=f"Application {name} doesn't exist", + deployment_timestamp=0, + ) + return self._application_states[name].get_application_status_info() + + def get_docs_path(self, app_name: str) -> Optional[str]: + return self._application_states[app_name].docs_path + + def get_route_prefix(self, name: str) -> Optional[str]: + return self._application_states[name].route_prefix + + def get_ingress_deployment_name(self, name: str) -> Optional[str]: + if name not in self._application_states: + return None + + return self._application_states[name].ingress_deployment + + def get_app_source(self, name: str) -> APIType: + return self._application_states[name].api_type + + def list_app_statuses(self) -> Dict[str, ApplicationStatusInfo]: + """Return a dictionary with {app name: application info}""" + return { + name: self._application_states[name].get_application_status_info() + for name in self._application_states + } + + def list_deployment_details(self, name: str) -> Dict[str, DeploymentDetails]: + """Gets detailed info on all deployments in specified application.""" + if name not in self._application_states: + return {} + return self._application_states[name].list_deployment_details() + + def update(self): + """Update each application state""" + apps_to_be_deleted = [] + for name, app in self._application_states.items(): + ready_to_be_deleted = app.update() + if ready_to_be_deleted: + apps_to_be_deleted.append(name) + logger.debug(f"Application '{name}' deleted successfully.") + + if len(apps_to_be_deleted) > 0: + for app_name in apps_to_be_deleted: + del self._application_states[app_name] + ServeUsageTag.NUM_APPS.record(str(len(self._application_states))) + + def shutdown(self) -> None: + self._shutting_down = True + + for app_state in self._application_states.values(): + app_state.delete() + + self._kv_store.delete(CHECKPOINT_KEY) + + def is_ready_for_shutdown(self) -> bool: + """Return whether all applications have shut down. + + Iterate through all application states and check if all their applications + are deleted. + """ + return self._shutting_down and all( + app_state.is_deleted() for app_state in self._application_states.values() + ) + + def save_checkpoint(self) -> None: + """Write a checkpoint of all application states.""" + if self._shutting_down: + # Once we're told to shut down, stop writing checkpoints. + # Calling .shutdown() deletes any existing checkpoint. + return + + application_state_info = { + app_name: app_state.get_checkpoint_data() + for app_name, app_state in self._application_states.items() + } + + self._kv_store.put( + CHECKPOINT_KEY, + cloudpickle.dumps(application_state_info), + ) + + +@ray.remote(num_cpus=0, max_calls=1) +def build_serve_application( + import_path: str, + code_version: str, + name: str, + args: Dict, + logging_config: LoggingConfig, +) -> Tuple[Optional[List[Dict]], Optional[str]]: + """Import and build a Serve application. + + Args: + import_path: import path to top-level bound deployment. + code_version: code version inferred from app config. All + deployment versions are set to this code version. + name: application name. If specified, application will be deployed + without removing existing applications. + args: Arguments to be passed to the application builder. + logging_config: the logging config for the build app task. + Returns: + Deploy arguments: a list of deployment arguments if application + was built successfully, otherwise None. + Error message: a string if an error was raised, otherwise None. + """ + configure_component_logger( + component_name="controller", + component_id=f"build_{name}_{os.getpid()}", + logging_config=logging_config, + ) + + try: + from ray.serve._private.api import call_user_app_builder_with_args_if_necessary + + # Import and build the application. + args_info_str = f" with arguments {args}" if args else "" + logger.info(f"Importing application '{name}'{args_info_str}.") + + app = call_user_app_builder_with_args_if_necessary( + import_attr(import_path), args + ) + + deploy_args_list = [] + built_app: BuiltApplication = build_app( + app, + name=name, + default_runtime_env=ray.get_runtime_context().runtime_env, + ) + num_ingress_deployments = 0 + for deployment in built_app.deployments: + if inspect.isclass(deployment.func_or_class) and issubclass( + deployment.func_or_class, ASGIAppReplicaWrapper + ): + num_ingress_deployments += 1 + is_ingress = deployment.name == built_app.ingress_deployment_name + deploy_args_list.append( + get_deploy_args( + name=deployment._name, + replica_config=deployment._replica_config, + ingress=is_ingress, + deployment_config=deployment._deployment_config, + version=code_version, + route_prefix="/" if is_ingress else None, + docs_path=deployment._docs_path, + ) + ) + if num_ingress_deployments > 1: + return None, ( + f'Found multiple FastAPI deployments in application "{built_app.name}". ' + "Please only include one deployment with @serve.ingress " + "in your application to avoid this issue." + ) + return deploy_args_list, None + except KeyboardInterrupt: + # Error is raised when this task is canceled with ray.cancel(), which + # happens when deploy_apps() is called. + logger.info( + "Existing config deployment request terminated because of keyboard " + "interrupt." + ) + return None, None + except Exception: + logger.error( + f"Exception importing application '{name}'.\n{traceback.format_exc()}" + ) + return None, traceback.format_exc() + + +def override_deployment_info( + deployment_infos: Dict[str, DeploymentInfo], + override_config: Optional[ServeApplicationSchema], +) -> Dict[str, DeploymentInfo]: + """Override deployment infos with options from app config. + + Args: + app_name: application name + deployment_infos: deployment info loaded from code + override_config: application config deployed by user with + options to override those loaded from code. + + Returns: the updated deployment infos. + + Raises: + ValueError: If config options have invalid values. + TypeError: If config options have invalid types. + """ + + deployment_infos = deepcopy(deployment_infos) + if override_config is None: + return deployment_infos + + config_dict = override_config.dict(exclude_unset=True) + deployment_override_options = config_dict.get("deployments", []) + + # Override options for each deployment listed in the config. + for options in deployment_override_options: + if "max_ongoing_requests" in options: + options["max_ongoing_requests"] = options.get("max_ongoing_requests") + + deployment_name = options["name"] + if deployment_name not in deployment_infos: + raise ValueError( + f"Deployment '{deployment_name}' does not exist. " + f"Available: {list(deployment_infos.keys())}" + ) + + info = deployment_infos[deployment_name] + original_options = info.deployment_config.dict() + original_options["user_configured_option_names"].update(set(options)) + + # Override `max_ongoing_requests` and `autoscaling_config` if + # `num_replicas="auto"` + if options.get("num_replicas") == "auto": + options["num_replicas"] = None + + new_config = AutoscalingConfig.default().dict() + # If `autoscaling_config` is specified, its values override + # the default `num_replicas="auto"` configuration + autoscaling_config = ( + options.get("autoscaling_config") + or info.deployment_config.autoscaling_config + ) + if autoscaling_config: + new_config.update(autoscaling_config) + + options["autoscaling_config"] = AutoscalingConfig(**new_config) + + ServeUsageTag.AUTO_NUM_REPLICAS_USED.record("1") + + # What to pass to info.update + override_options = {} + + # Merge app-level and deployment-level runtime_envs. + replica_config = info.replica_config + app_runtime_env = override_config.runtime_env + if "ray_actor_options" in options: + # If specified, get ray_actor_options from config + override_actor_options = options.pop("ray_actor_options", {}) + else: + # Otherwise, get options from application code (and default to {} + # if the code sets options to None). + override_actor_options = replica_config.ray_actor_options or {} + + override_placement_group_bundles = options.pop( + "placement_group_bundles", replica_config.placement_group_bundles + ) + override_placement_group_strategy = options.pop( + "placement_group_strategy", replica_config.placement_group_strategy + ) + + override_max_replicas_per_node = options.pop( + "max_replicas_per_node", replica_config.max_replicas_per_node + ) + + # Record telemetry for container runtime env feature at deployment level + if override_actor_options.get("runtime_env") and ( + override_actor_options["runtime_env"].get("container") + or override_actor_options["runtime_env"].get("image_uri") + ): + ServeUsageTag.DEPLOYMENT_CONTAINER_RUNTIME_ENV_USED.record("1") + + merged_env = override_runtime_envs_except_env_vars( + app_runtime_env, override_actor_options.get("runtime_env", {}) + ) + override_actor_options.update({"runtime_env": merged_env}) + + replica_config.update( + ray_actor_options=override_actor_options, + placement_group_bundles=override_placement_group_bundles, + placement_group_strategy=override_placement_group_strategy, + max_replicas_per_node=override_max_replicas_per_node, + ) + override_options["replica_config"] = replica_config + + # Override deployment config options + options.pop("name", None) + original_options.update(options) + override_options["deployment_config"] = DeploymentConfig(**original_options) + deployment_infos[deployment_name] = info.update(**override_options) + + deployment_config = deployment_infos[deployment_name].deployment_config + if ( + deployment_config.autoscaling_config is not None + and deployment_config.max_ongoing_requests + < deployment_config.autoscaling_config.get_target_ongoing_requests() + ): + logger.warning( + "Autoscaling will never happen, " + "because 'max_ongoing_requests' is less than " + "'target_ongoing_requests' now." + ) + + # Overwrite ingress route prefix + app_route_prefix = config_dict.get("route_prefix", DEFAULT.VALUE) + validate_route_prefix(app_route_prefix) + for deployment in list(deployment_infos.values()): + if ( + app_route_prefix is not DEFAULT.VALUE + and deployment.route_prefix is not None + ): + deployment.route_prefix = app_route_prefix + + return deployment_infos diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/autoscaling_state.py b/venv/lib/python3.10/site-packages/ray/serve/_private/autoscaling_state.py new file mode 100644 index 0000000000000000000000000000000000000000..e8adb956299831ef4a60dee787369e974a35b8ce --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/autoscaling_state.py @@ -0,0 +1,426 @@ +import logging +import time +from dataclasses import dataclass +from typing import Dict, List, Optional, Set + +from ray.serve._private.common import ( + DeploymentHandleSource, + DeploymentID, + ReplicaID, + TargetCapacityDirection, +) +from ray.serve._private.constants import ( + RAY_SERVE_MIN_HANDLE_METRICS_TIMEOUT_S, + SERVE_LOGGER_NAME, +) +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.utils import get_capacity_adjusted_num_replicas + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@dataclass +class HandleMetricReport: + """Report from a deployment handle on queued and ongoing requests. + + Args: + actor_id: If the deployment handle (from which this metric was + sent) lives on an actor, the actor ID of that actor. + handle_source: Describes what kind of entity holds this + deployment handle: a Serve proxy, a Serve replica, or + unknown. + queued_requests: The current number of queued requests at the + handle, i.e. requests that haven't been assigned to any + replica yet. + running_requests: A map of replica ID to the average number of + requests, assigned through the handle, running at that + replica. + timestamp: The time at which this report was received. + """ + + actor_id: Optional[str] + handle_source: DeploymentHandleSource + queued_requests: float + running_requests: Dict[ReplicaID, float] + timestamp: float + + @property + def total_requests(self) -> float: + """Total number of queued and running requests.""" + return self.queued_requests + sum(self.running_requests.values()) + + @property + def is_serve_component_source(self) -> bool: + """Whether the handle source is a Serve actor. + + More specifically, this returns whether a Serve actor tracked + by the controller holds the deployment handle that sent this + report. If the deployment handle lives on a driver, a Ray task, + or an actor that's not a Serve replica, then this returns False. + """ + return self.handle_source in [ + DeploymentHandleSource.PROXY, + DeploymentHandleSource.REPLICA, + ] + + +@dataclass +class ReplicaMetricReport: + """Report from a replica on ongoing requests. + + Args: + running_requests: Average number of running requests at the + replica. + timestamp: The time at which this report was received. + """ + + running_requests: float + timestamp: float + + +class AutoscalingState: + """Manages autoscaling for a single deployment.""" + + def __init__(self, deployment_id: DeploymentID): + self._deployment_id = deployment_id + + # Map from handle ID to handle request metric report. Metrics + # are removed from this dict either when the actor on which the + # handle lived dies, or after a period of no updates. + self._handle_requests: Dict[str, HandleMetricReport] = dict() + # Map from replica ID to replica request metric report. Metrics + # are removed from this dict when a replica is stopped. + self._replica_requests: Dict[ReplicaID, ReplicaMetricReport] = dict() + + self._deployment_info = None + self._config = None + self._policy = None + self._running_replicas: List[ReplicaID] = [] + self._target_capacity: Optional[float] = None + self._target_capacity_direction: Optional[TargetCapacityDirection] = None + + def register(self, info: DeploymentInfo, curr_target_num_replicas: int) -> int: + """Registers an autoscaling deployment's info. + + Returns the number of replicas the target should be set to. + """ + + config = info.deployment_config.autoscaling_config + if ( + self._deployment_info is None or self._deployment_info.config_changed(info) + ) and config.initial_replicas is not None: + target_num_replicas = config.initial_replicas + else: + target_num_replicas = curr_target_num_replicas + + self._deployment_info = info + self._config = config + self._policy = self._config.get_policy() + self._target_capacity = info.target_capacity + self._target_capacity_direction = info.target_capacity_direction + self._policy_state = {} + + return self.apply_bounds(target_num_replicas) + + def on_replica_stopped(self, replica_id: ReplicaID): + if replica_id in self._replica_requests: + del self._replica_requests[replica_id] + + def get_num_replicas_lower_bound(self) -> int: + if self._config.initial_replicas is not None and ( + self._target_capacity_direction == TargetCapacityDirection.UP + ): + return get_capacity_adjusted_num_replicas( + self._config.initial_replicas, + self._target_capacity, + ) + else: + return get_capacity_adjusted_num_replicas( + self._config.min_replicas, + self._target_capacity, + ) + + def get_num_replicas_upper_bound(self) -> int: + return get_capacity_adjusted_num_replicas( + self._config.max_replicas, + self._target_capacity, + ) + + def update_running_replica_ids(self, running_replicas: List[ReplicaID]): + """Update cached set of running replica IDs for this deployment.""" + self._running_replicas = running_replicas + + def is_within_bounds(self, num_replicas_running_at_target_version: int): + """Whether or not this deployment is within the autoscaling bounds. + + Returns: True if the number of running replicas for the current + deployment version is within the autoscaling bounds. False + otherwise. + """ + + return ( + self.apply_bounds(num_replicas_running_at_target_version) + == num_replicas_running_at_target_version + ) + + def apply_bounds(self, num_replicas: int) -> int: + """Clips a replica count with current autoscaling bounds. + + This takes into account target capacity. + """ + + return max( + self.get_num_replicas_lower_bound(), + min(self.get_num_replicas_upper_bound(), num_replicas), + ) + + def record_request_metrics_for_replica( + self, replica_id: ReplicaID, window_avg: Optional[float], send_timestamp: float + ) -> None: + """Records average number of ongoing requests at a replica.""" + + if window_avg is None: + return + + if ( + replica_id not in self._replica_requests + or send_timestamp > self._replica_requests[replica_id].timestamp + ): + self._replica_requests[replica_id] = ReplicaMetricReport( + running_requests=window_avg, + timestamp=send_timestamp, + ) + + def record_request_metrics_for_handle( + self, + *, + handle_id: str, + actor_id: Optional[str], + handle_source: DeploymentHandleSource, + queued_requests: float, + running_requests: Dict[ReplicaID, float], + send_timestamp: float, + ) -> None: + """Records average number of queued and running requests at a handle for this + deployment. + """ + + if ( + handle_id not in self._handle_requests + or send_timestamp > self._handle_requests[handle_id].timestamp + ): + self._handle_requests[handle_id] = HandleMetricReport( + actor_id=actor_id, + handle_source=handle_source, + queued_requests=queued_requests, + running_requests=running_requests, + timestamp=send_timestamp, + ) + + def drop_stale_handle_metrics(self, alive_serve_actor_ids: Set[str]) -> None: + """Drops handle metrics that are no longer valid. + + This includes handles that live on Serve Proxy or replica actors + that have died AND handles from which the controller hasn't + received an update for too long. + """ + + timeout_s = max( + 2 * self._config.metrics_interval_s, + RAY_SERVE_MIN_HANDLE_METRICS_TIMEOUT_S, + ) + for handle_id, handle_metric in list(self._handle_requests.items()): + # Drop metrics for handles that are on Serve proxy/replica + # actors that have died + if ( + handle_metric.is_serve_component_source + and handle_metric.actor_id is not None + and handle_metric.actor_id not in alive_serve_actor_ids + ): + del self._handle_requests[handle_id] + if handle_metric.total_requests > 0: + logger.debug( + f"Dropping metrics for handle '{handle_id}' because the Serve " + f"actor it was on ({handle_metric.actor_id}) is no longer " + f"alive. It had {handle_metric.total_requests} ongoing requests" + ) + # Drop metrics for handles that haven't sent an update in a while. + # This is expected behavior for handles that were on replicas or + # proxies that have been shut down. + elif time.time() - handle_metric.timestamp >= timeout_s: + del self._handle_requests[handle_id] + if handle_metric.total_requests > 0: + actor_id = handle_metric.actor_id + actor_info = f"on actor '{actor_id}' " if actor_id else "" + logger.info( + f"Dropping stale metrics for handle '{handle_id}' {actor_info}" + f"because no update was received for {timeout_s:.1f}s. " + f"Ongoing requests was: {handle_metric.total_requests}." + ) + + def get_decision_num_replicas( + self, curr_target_num_replicas: int, _skip_bound_check: bool = False + ) -> int: + """Decide the target number of replicas to autoscale to. + + The decision is based off of the number of requests received + for this deployment. After the decision number of replicas is + returned by the policy, it is then bounded by the bounds min + and max adjusted by the target capacity and returned. If + `_skip_bound_check` is True, then the bounds are not applied. + """ + + decision_num_replicas = self._policy( + curr_target_num_replicas=curr_target_num_replicas, + total_num_requests=self.get_total_num_requests(), + num_running_replicas=len(self._running_replicas), + config=self._config, + capacity_adjusted_min_replicas=self.get_num_replicas_lower_bound(), + capacity_adjusted_max_replicas=self.get_num_replicas_upper_bound(), + policy_state=self._policy_state, + ) + + if _skip_bound_check: + return decision_num_replicas + + return self.apply_bounds(decision_num_replicas) + + def get_total_num_requests(self) -> float: + """Get average total number of requests aggregated over the past + `look_back_period_s` number of seconds. + + If there are 0 running replicas, then returns the total number + of requests queued at handles + + This code assumes that the metrics are either emmited on handles + or on replicas, but not both. Its the responsibility of the writer + to ensure enclusivity of the metrics. + """ + + total_requests = 0 + + for id in self._running_replicas: + if id in self._replica_requests: + total_requests += self._replica_requests[id].running_requests + + metrics_collected_on_replicas = total_requests > 0 + for handle_metric in self._handle_requests.values(): + total_requests += handle_metric.queued_requests + + if not metrics_collected_on_replicas: + for id in self._running_replicas: + if id in handle_metric.running_requests: + total_requests += handle_metric.running_requests[id] + + return total_requests + + +class AutoscalingStateManager: + """Manages all things autoscaling related. + + Keeps track of request metrics for each deployment and decides on + the target number of replicas to autoscale to based on those metrics. + """ + + def __init__(self): + self._autoscaling_states: Dict[DeploymentID, AutoscalingState] = {} + + def register_deployment( + self, + deployment_id: DeploymentID, + info: DeploymentInfo, + curr_target_num_replicas: int, + ) -> int: + """Register autoscaling deployment info.""" + assert info.deployment_config.autoscaling_config + if deployment_id not in self._autoscaling_states: + self._autoscaling_states[deployment_id] = AutoscalingState(deployment_id) + return self._autoscaling_states[deployment_id].register( + info, curr_target_num_replicas + ) + + def deregister_deployment(self, deployment_id: DeploymentID): + """Remove deployment from tracking.""" + self._autoscaling_states.pop(deployment_id, None) + + def update_running_replica_ids( + self, deployment_id: DeploymentID, running_replicas: List[ReplicaID] + ): + self._autoscaling_states[deployment_id].update_running_replica_ids( + running_replicas + ) + + def on_replica_stopped(self, replica_id: ReplicaID): + deployment_id = replica_id.deployment_id + if deployment_id in self._autoscaling_states: + self._autoscaling_states[deployment_id].on_replica_stopped(replica_id) + + def get_metrics(self) -> Dict[DeploymentID, float]: + return { + deployment_id: self.get_total_num_requests(deployment_id) + for deployment_id in self._autoscaling_states + } + + def get_target_num_replicas( + self, deployment_id: DeploymentID, curr_target_num_replicas: int + ) -> int: + return self._autoscaling_states[deployment_id].get_decision_num_replicas( + curr_target_num_replicas=curr_target_num_replicas, + ) + + def get_total_num_requests(self, deployment_id: DeploymentID) -> float: + return self._autoscaling_states[deployment_id].get_total_num_requests() + + def is_within_bounds( + self, deployment_id: DeploymentID, num_replicas_running_at_target_version: int + ) -> bool: + return self._autoscaling_states[deployment_id].is_within_bounds( + num_replicas_running_at_target_version + ) + + def record_request_metrics_for_replica( + self, replica_id: ReplicaID, window_avg: Optional[float], send_timestamp: float + ) -> None: + deployment_id = replica_id.deployment_id + # Defensively guard against delayed replica metrics arriving + # after the deployment's been deleted + if deployment_id in self._autoscaling_states: + self._autoscaling_states[deployment_id].record_request_metrics_for_replica( + replica_id=replica_id, + window_avg=window_avg, + send_timestamp=send_timestamp, + ) + + def record_request_metrics_for_handle( + self, + *, + deployment_id: str, + handle_id: str, + actor_id: Optional[str], + handle_source: DeploymentHandleSource, + queued_requests: float, + running_requests: Dict[ReplicaID, float], + send_timestamp: float, + ) -> None: + """Update request metric for a specific handle.""" + + if deployment_id in self._autoscaling_states: + self._autoscaling_states[deployment_id].record_request_metrics_for_handle( + handle_id=handle_id, + actor_id=actor_id, + handle_source=handle_source, + queued_requests=queued_requests, + running_requests=running_requests, + send_timestamp=send_timestamp, + ) + + def drop_stale_handle_metrics(self, alive_serve_actor_ids: Set[str]) -> None: + """Drops handle metrics that are no longer valid. + + This includes handles that live on Serve Proxy or replica actors + that have died AND handles from which the controller hasn't + received an update for too long. + """ + + for autoscaling_state in self._autoscaling_states.values(): + autoscaling_state.drop_stale_handle_metrics(alive_serve_actor_ids) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__init__.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0280bc6ae21ce3fce67bbd07fb6828c28ccdfc74 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/common.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7471637362bffc3430db8fcb37d6e04663ae83f0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/common.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_noop_latency.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_noop_latency.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e7ab393a0248af88a37c7ace65f9423db7ec4b9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_noop_latency.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_throughput.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_throughput.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..364587ab150f21de7aad0a32b838a8443307099c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/handle_throughput.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/http_noop_latency.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/http_noop_latency.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a15ec5c0d630ecec338c262ad8588cd3547fb997 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/http_noop_latency.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/microbenchmark.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/microbenchmark.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a26fd198a96b269c4b98a84411a83cc553ee921 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/microbenchmark.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/proxy_benchmark.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/proxy_benchmark.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..add427ed5220db7d548e7bb83757cd5f5857f673 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/__pycache__/proxy_benchmark.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/common.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/common.py new file mode 100644 index 0000000000000000000000000000000000000000..f5daad3d493f112563e2c129aabbe54de1eed54d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/common.py @@ -0,0 +1,276 @@ +import asyncio +import inspect +import logging +import random +import string +import time +from functools import partial +from typing import Any, Callable, Coroutine, List, Optional, Tuple + +import aiohttp +import aiohttp.client_exceptions +import grpc +import numpy as np +import pandas as pd +from starlette.responses import StreamingResponse +from tqdm import tqdm + +from ray import serve +from ray.serve.generated import serve_pb2, serve_pb2_grpc +from ray.serve.handle import DeploymentHandle + + +async def run_latency_benchmark( + f: Callable, num_requests: int, *, num_warmup_requests: int = 100 +) -> pd.Series: + if inspect.iscoroutinefunction(f): + to_call = f + else: + + async def to_call(): + f() + + latencies = [] + for i in tqdm(range(num_requests + num_warmup_requests)): + start = time.perf_counter() + await to_call() + end = time.perf_counter() + + # Don't include warm-up requests. + if i >= num_warmup_requests: + latencies.append(1000 * (end - start)) + + return pd.Series(latencies) + + +async def run_throughput_benchmark( + fn: Callable[[], List[float]], + multiplier: int = 1, + num_trials: int = 10, + trial_runtime: float = 1, +) -> Tuple[float, float, pd.Series]: + """Benchmarks throughput of a function. + + Args: + fn: The function to benchmark. If this returns anything, it must + return a list of latencies. + multiplier: The number of requests or tokens (or whatever unit + is appropriate for this throughput benchmark) that is + completed in one call to `fn`. + num_trials: The number of trials to run. + trial_runtime: How long each trial should run for. During the + duration of one trial, `fn` will be repeatedly called. + + Returns (mean, stddev, latencies). + """ + # Warmup + start = time.time() + while time.time() - start < 0.1: + await fn() + + # Benchmark + stats = [] + latencies = [] + for _ in tqdm(range(num_trials)): + start = time.perf_counter() + count = 0 + while time.perf_counter() - start < trial_runtime: + res = await fn() + if res: + latencies.extend(res) + + count += 1 + end = time.perf_counter() + stats.append(multiplier * count / (end - start)) + + return round(np.mean(stats), 2), round(np.std(stats), 2), pd.Series(latencies) + + +async def do_single_http_batch( + *, + batch_size: int = 100, + url: str = "http://localhost:8000", + stream: bool = False, +) -> List[float]: + """Sends a batch of http requests and returns e2e latencies.""" + + # By default, aiohttp limits the number of client connections to 100. + # We need to use TCPConnector to configure the limit if batch size + # is greater than 100. + connector = aiohttp.TCPConnector(limit=batch_size) + async with aiohttp.ClientSession( + connector=connector, raise_for_status=True + ) as session: + + async def do_query(): + start = time.perf_counter() + try: + if stream: + async with session.get(url) as r: + async for chunk, _ in r.content.iter_chunks(): + pass + else: + await session.get(url) + except aiohttp.client_exceptions.ClientConnectionError: + pass + + end = time.perf_counter() + return 1000 * (end - start) + + return await asyncio.gather(*[do_query() for _ in range(batch_size)]) + + +async def do_single_grpc_batch( + *, batch_size: int = 100, target: str = "localhost:9000" +): + channel = grpc.aio.insecure_channel(target) + stub = serve_pb2_grpc.RayServeBenchmarkServiceStub(channel) + payload = serve_pb2.StringData(data="") + + async def do_query(): + start = time.perf_counter() + + await stub.grpc_call(payload) + + end = time.perf_counter() + return 1000 * (end - start) + + return await asyncio.gather(*[do_query() for _ in range(batch_size)]) + + +async def collect_profile_events(coro: Coroutine): + """Collects profiling events using Viztracer""" + + from viztracer import VizTracer + + tracer = VizTracer() + tracer.start() + + await coro + + tracer.stop() + tracer.save() + + +def generate_payload(size: int = 100, chars=string.ascii_uppercase + string.digits): + return "".join(random.choice(chars) for _ in range(size)) + + +class Blackhole: + def sink(self, o): + pass + + +@serve.deployment +class Noop: + def __init__(self): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + def __call__(self, *args, **kwargs): + return b"" + + +@serve.deployment +class Streamer: + def __init__(self, tokens_per_request: int, inter_token_delay_ms: int = 10): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + self._tokens_per_request = tokens_per_request + self._inter_token_delay_s = inter_token_delay_ms / 1000 + + async def stream(self): + for _ in range(self._tokens_per_request): + await asyncio.sleep(self._inter_token_delay_s) + yield b"hi" + + async def __call__(self): + return StreamingResponse(self.stream()) + + +@serve.deployment +class IntermediateRouter: + def __init__(self, handle: DeploymentHandle): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + self._handle = handle.options(stream=True) + + async def stream(self): + async for token in self._handle.stream.remote(): + yield token + + def __call__(self): + return StreamingResponse(self.stream()) + + +@serve.deployment +class Benchmarker: + def __init__( + self, + handle: DeploymentHandle, + stream: bool = False, + ): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + self._handle = handle.options(stream=stream) + self._stream = stream + + async def do_single_request(self, payload: Any = None) -> float: + """Completes a single unary request. Returns e2e latency in ms.""" + start = time.perf_counter() + + if payload is None: + await self._handle.remote() + else: + await self._handle.remote(payload) + + end = time.perf_counter() + return 1000 * (end - start) + + async def _do_single_stream(self) -> float: + """Consumes a single streaming request. Returns e2e latency in ms.""" + start = time.perf_counter() + + async for r in self._handle.stream.remote(): + pass + + end = time.perf_counter() + return 1000 * (end - start) + + async def _do_single_batch(self, batch_size: int) -> List[float]: + if self._stream: + return await asyncio.gather( + *[self._do_single_stream() for _ in range(batch_size)] + ) + else: + return await asyncio.gather( + *[self.do_single_request() for _ in range(batch_size)] + ) + + async def run_latency_benchmark( + self, *, num_requests: int, payload: Any = None + ) -> pd.Series: + async def f(): + await self.do_single_request(payload) + + return await run_latency_benchmark(f, num_requests=num_requests) + + async def run_throughput_benchmark( + self, + *, + batch_size: int, + num_trials: int, + trial_runtime: float, + tokens_per_request: Optional[float] = None, + ) -> Tuple[float, float]: + if self._stream: + assert tokens_per_request + multiplier = tokens_per_request * batch_size + else: + multiplier = batch_size + + return await run_throughput_benchmark( + fn=partial( + self._do_single_batch, + batch_size=batch_size, + ), + multiplier=multiplier, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/handle_noop_latency.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/handle_noop_latency.py new file mode 100644 index 0000000000000000000000000000000000000000..313e467c6ff0e38f3da21c3dcb40e8b700f9cddf --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/handle_noop_latency.py @@ -0,0 +1,34 @@ +import time + +import click +import pandas as pd + +from ray import serve +from ray.serve._private.benchmarks.common import Benchmarker, Noop +from ray.serve.handle import DeploymentHandle + + +@click.command(help="Benchmark no-op DeploymentHandle latency.") +@click.option("--num-replicas", type=int, default=1) +@click.option("--num-requests", type=int, default=100) +def main(num_replicas: int, num_requests: int): + h: DeploymentHandle = serve.run( + Benchmarker.bind(Noop.options(num_replicas=num_replicas).bind()) + ) + + latencies: pd.Series = h.run_latency_benchmark.remote( + num_requests, + ).result() + + # Let the logs flush to avoid interwoven output. + time.sleep(1) + + print( + "Latency (ms) for noop DeploymentHandle requests " + f"(num_replicas={num_replicas},num_requests={num_requests}):" + ) + print(latencies.describe(percentiles=[0.5, 0.9, 0.95, 0.99])) + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/handle_throughput.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/handle_throughput.py new file mode 100644 index 0000000000000000000000000000000000000000..08aa3c215224745cae5bdf7432798dae933b182e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/handle_throughput.py @@ -0,0 +1,62 @@ +import click + +from ray import serve +from ray.serve._private.benchmarks.common import Benchmarker, Hello +from ray.serve.handle import DeploymentHandle + + +@click.command(help="Benchmark deployment handle throughput.") +@click.option( + "--batch-size", + type=int, + default=100, + help="Number of requests to send to downstream deployment in each trial.", +) +@click.option( + "--num-replicas", + type=int, + default=1, + help="Number of replicas in the downstream deployment.", +) +@click.option( + "--num-trials", + type=int, + default=5, + help="Number of trials of the benchmark to run.", +) +@click.option( + "--trial-runtime", + type=int, + default=1, + help="Duration to run each trial of the benchmark for (seconds).", +) +def main( + batch_size: int, + num_replicas: int, + num_trials: int, + trial_runtime: float, +): + app = Benchmarker.bind( + Hello.options( + num_replicas=num_replicas, ray_actor_options={"num_cpus": 0} + ).bind(), + ) + h: DeploymentHandle = serve.run(app) + + mean, stddev = h.run_throughput_benchmark.remote( + batch_size=batch_size, + num_trials=num_trials, + trial_runtime=trial_runtime, + ).result() + + print( + "DeploymentHandle throughput {}: {} +- {} requests/s".format( + f"(num_replicas={num_replicas}, batch_size={batch_size})", + mean, + stddev, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/http_noop_latency.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/http_noop_latency.py new file mode 100644 index 0000000000000000000000000000000000000000..ab85f5f882da6ace9d771eb2185154fedd90ffd0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/http_noop_latency.py @@ -0,0 +1,32 @@ +import asyncio + +import click +import pandas as pd +import requests + +from ray import serve +from ray.serve._private.benchmarks.common import Noop, run_latency_benchmark + + +@click.command(help="Benchmark no-op HTTP latency.") +@click.option("--num-replicas", type=int, default=1) +@click.option("--num-requests", type=int, default=100) +def main(num_replicas: int, num_requests: int): + serve.run(Noop.options(num_replicas=num_replicas).bind()) + + latencies: pd.Series = asyncio.new_event_loop().run_until_complete( + run_latency_benchmark( + lambda: requests.get("http://localhost:8000"), + num_requests=num_requests, + ) + ) + + print( + "Latency (ms) for noop HTTP requests " + f"(num_replicas={num_replicas},num_requests={num_requests}):" + ) + print(latencies.describe(percentiles=[0.5, 0.9, 0.95, 0.99])) + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/microbenchmark.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/microbenchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..176298d0f26dd979bc93366e24605a73bd3c85c5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/microbenchmark.py @@ -0,0 +1,182 @@ +# Runs several scenarios with varying max batch size, max concurrent queries, +# number of replicas, and with intermediate serve handles (to simulate ensemble +# models) either on or off. + +import asyncio +import logging +from pprint import pprint +from typing import Dict, Union + +import aiohttp +from starlette.requests import Request + +import ray +from ray import serve +from ray.serve._private.benchmarks.common import run_throughput_benchmark +from ray.serve.handle import DeploymentHandle + +NUM_CLIENTS = 8 +CALLS_PER_BATCH = 100 + + +async def fetch(session, data): + async with session.get("http://localhost:8000/", data=data) as response: + response = await response.text() + assert response == "ok", response + + +@ray.remote +class Client: + def ready(self): + return "ok" + + async def do_queries(self, num, data): + async with aiohttp.ClientSession() as session: + for _ in range(num): + await fetch(session, data) + + +def build_app( + intermediate_handles: bool, + num_replicas: int, + max_batch_size: int, + max_ongoing_requests: int, +): + @serve.deployment(max_ongoing_requests=1000) + class Upstream: + def __init__(self, handle: DeploymentHandle): + self._handle = handle + + # Turn off access log. + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + async def __call__(self, req: Request): + return await self._handle.remote(await req.body()) + + @serve.deployment( + num_replicas=num_replicas, + max_ongoing_requests=max_ongoing_requests, + ) + class Downstream: + def __init__(self): + # Turn off access log. + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + @serve.batch(max_batch_size=max_batch_size) + async def batch(self, reqs): + return [b"ok"] * len(reqs) + + async def __call__(self, req: Union[bytes, Request]): + if max_batch_size > 1: + return await self.batch(req) + else: + return b"ok" + + if intermediate_handles: + return Upstream.bind(Downstream.bind()) + else: + return Downstream.bind() + + +async def trial( + intermediate_handles: bool, + num_replicas: int, + max_batch_size: int, + max_ongoing_requests: int, + data_size: str, +) -> Dict[str, float]: + results = {} + + trial_key_base = ( + f"replica:{num_replicas}/batch_size:{max_batch_size}/" + f"concurrent_queries:{max_ongoing_requests}/" + f"data_size:{data_size}/intermediate_handle:{intermediate_handles}" + ) + + print( + f"intermediate_handles={intermediate_handles}," + f"num_replicas={num_replicas}," + f"max_batch_size={max_batch_size}," + f"max_ongoing_requests={max_ongoing_requests}," + f"data_size={data_size}" + ) + + app = build_app( + intermediate_handles, num_replicas, max_batch_size, max_ongoing_requests + ) + serve.run(app) + + if data_size == "small": + data = None + elif data_size == "large": + data = b"a" * 1024 * 1024 + else: + raise ValueError("data_size should be 'small' or 'large'.") + + async with aiohttp.ClientSession() as session: + + async def single_client(): + for _ in range(CALLS_PER_BATCH): + await fetch(session, data) + + single_client_avg_tps, single_client_std_tps = await run_throughput_benchmark( + single_client, + multiplier=CALLS_PER_BATCH, + ) + print( + "\t{} {} +- {} requests/s".format( + "single client {} data".format(data_size), + single_client_avg_tps, + single_client_std_tps, + ) + ) + key = f"num_client:1/{trial_key_base}" + results[key] = single_client_avg_tps + + clients = [Client.remote() for _ in range(NUM_CLIENTS)] + ray.get([client.ready.remote() for client in clients]) + + async def many_clients(): + ray.get([a.do_queries.remote(CALLS_PER_BATCH, data) for a in clients]) + + multi_client_avg_tps, _ = await run_throughput_benchmark( + many_clients, + multiplier=CALLS_PER_BATCH * len(clients), + ) + + results[f"num_client:{len(clients)}/{trial_key_base}"] = multi_client_avg_tps + return results + + +async def main(): + results = {} + for intermediate_handles in [False, True]: + for num_replicas in [1, 8]: + for max_batch_size, max_ongoing_requests in [ + (1, 1), + (1, 10000), + (10000, 10000), + ]: + # TODO(edoakes): large data causes broken pipe errors. + for data_size in ["small"]: + results.update( + await trial( + intermediate_handles, + num_replicas, + max_batch_size, + max_ongoing_requests, + data_size, + ) + ) + + print("Results from all conditions:") + pprint(results) + return results + + +if __name__ == "__main__": + ray.init() + serve.start() + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + loop.run_until_complete(main()) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/proxy_benchmark.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/proxy_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3eca322f29c1c030637195f89308ea1a3e1238 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/proxy_benchmark.py @@ -0,0 +1,294 @@ +# Runs some request ping to compare HTTP and gRPC performances in TPS and latency. +# Note: this takes around 1 hour to run. + +import asyncio +import json +import logging +import time +from random import random +from typing import Callable, Dict + +import aiohttp +import numpy as np +import pandas as pd +from grpc import aio +from starlette.requests import Request + +import ray +from ray import serve +from ray.serve._private.common import RequestProtocol +from ray.serve.config import gRPCOptions +from ray.serve.generated import serve_pb2, serve_pb2_grpc +from ray.serve.handle import DeploymentHandle + +CALLS_PER_BATCH = 100 +DELTA = 10**-7 + + +async def get_query_tps(name: str, fn: Callable, multiplier: int = CALLS_PER_BATCH): + """Get query TPS. + + Run the function for 0.5 seconds 10 times to calculate how many requests can + be completed. And use those stats to calculate the mean and std of TPS. + """ + # warmup + start = time.time() + while time.time() - start < 0.1: + await fn() + # real run + stats = [] + for _ in range(10): + count = 0 + start = time.time() + while time.time() - start < 0.5: + await fn() + count += 1 + end = time.time() + stats.append(multiplier * count / (end - start)) + tps_mean = round(np.mean(stats), 2) + tps_std = round(np.std(stats), 2) + print(f"\t{name} {tps_mean} +- {tps_std} requests/s") + + return tps_mean, tps_std + + +async def get_query_latencies(name: str, fn: Callable): + """Get query latencies. + + Take all the latencies from the function and calculate the mean and std. + """ + many_client_results = np.asarray(await fn()) + many_client_results.flatten() + latency_ms_mean = round(np.mean(many_client_results) * 1000, 2) + latency_ms_std = round(np.std(many_client_results) * 1000, 2) + print(f"\t{name} {latency_ms_mean} +- {latency_ms_std} ms") + + return latency_ms_mean, latency_ms_std + + +async def fetch_http(session, data): + data_json = {"nums": data} + response = await session.get("http://localhost:8000/", json=data_json) + response_text = await response.read() + float(response_text.decode()) + + +async def fetch_grpc(stub, data): + result = await stub.grpc_call(serve_pb2.RawData(nums=data)) + _ = result.output + + +@ray.remote +class HTTPClient: + def ready(self): + return "ok" + + async def do_queries(self, num, data): + async with aiohttp.ClientSession() as session: + for _ in range(num): + await fetch_http(session, data) + + async def time_queries(self, num, data): + stats = [] + async with aiohttp.ClientSession() as session: + for _ in range(num): + start = time.time() + await fetch_http(session, data) + end = time.time() + stats.append(end - start) + + return stats + + +@ray.remote +class gRPCClient: + def __init__(self): + channel = aio.insecure_channel("localhost:9000") + self.stub = serve_pb2_grpc.RayServeBenchmarkServiceStub(channel) + + def ready(self): + return "ok" + + async def do_queries(self, num, data): + for _ in range(num): + await fetch_grpc(self.stub, data) + + async def time_queries(self, num, data): + stats = [] + for _ in range(num): + start = time.time() + await fetch_grpc(self.stub, data) + end = time.time() + stats.append(end - start) + return stats + + +def build_app( + num_replicas: int, + max_ongoing_requests: int, + data_size: int, +): + @serve.deployment(max_ongoing_requests=1000) + class DataPreprocessing: + def __init__(self, handle: DeploymentHandle): + self._handle = handle + + # Turn off access log. + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + def normalize(self, raw: np.ndarray) -> np.ndarray: + return (raw - np.min(raw)) / (np.max(raw) - np.min(raw) + DELTA) + + async def __call__(self, req: Request): + """HTTP entrypoint. + + It parses the request, normalize the data, and send to model for inference. + """ + body = json.loads(await req.body()) + raw = np.asarray(body["nums"]) + processed = self.normalize(raw) + return await self._handle.remote(processed) + + async def grpc_call(self, raq_data): + """gRPC entrypoint. + + It parses the request, normalize the data, and send to model for inference. + """ + raw = np.asarray(raq_data.nums) + processed = self.normalize(raw) + output = await self._handle.remote(processed) + return serve_pb2.ModelOutput(output=output) + + async def call_with_string(self, raq_data): + """gRPC entrypoint.""" + return serve_pb2.ModelOutput(output=0) + + @serve.deployment( + num_replicas=num_replicas, + max_ongoing_requests=max_ongoing_requests, + ) + class ModelInference: + def __init__(self): + # Turn off access log. + logging.getLogger("ray.serve").setLevel(logging.WARNING) + self._model = np.random.randn(data_size, data_size) + + async def __call__(self, processed: np.ndarray) -> float: + # Run a dot product with a random matrix to simulate a model inference. + model_output = np.dot(processed, self._model) + return sum(model_output) + + return DataPreprocessing.bind(ModelInference.bind()) + + +async def trial( + num_replicas: int, + max_ongoing_requests: int, + data_size: int, + num_clients: int, + proxy: RequestProtocol, +) -> Dict[str, float]: + # Generate input data as array of random floats. + data = [random() for _ in range(data_size)] + + # Build and deploy the app. + app = build_app( + num_replicas=num_replicas, + max_ongoing_requests=max_ongoing_requests, + data_size=data_size, + ) + serve.run(app) + + # Start clients. + if proxy == RequestProtocol.GRPC: + clients = [gRPCClient.remote() for _ in range(num_clients)] + elif proxy == RequestProtocol.HTTP: + clients = [HTTPClient.remote() for _ in range(num_clients)] + ray.get([client.ready.remote() for client in clients]) + + async def client_time_queries(): + return ray.get([a.time_queries.remote(CALLS_PER_BATCH, data) for a in clients]) + + async def client_do_queries(): + ray.get([a.do_queries.remote(CALLS_PER_BATCH, data) for a in clients]) + + trial_key_base = ( + f"proxy:{proxy}/" + f"num_client:{num_clients}/" + f"replica:{num_replicas}/" + f"concurrent_queries:{max_ongoing_requests}/" + f"data_size:{data_size}" + ) + tps_mean, tps_sdt = await get_query_tps( + trial_key_base, + client_do_queries, + ) + latency_ms_mean, latency_ms_std = await get_query_latencies( + trial_key_base, + client_time_queries, + ) + + results = { + "proxy": proxy.value, + "num_client": num_clients, + "replica": num_replicas, + "concurrent_queries": max_ongoing_requests, + "data_size": data_size, + "tps_mean": tps_mean, + "tps_sdt": tps_sdt, + "latency_ms_mean": latency_ms_mean, + "latency_ms_std": latency_ms_std, + } + + return results + + +async def main(): + start_time = time.time() + results = [] + for num_replicas in [1, 8]: + for max_ongoing_requests in [1, 10_000]: + for data_size in [1, 100, 10_000]: + for num_clients in [1, 8]: + for proxy in [RequestProtocol.GRPC, RequestProtocol.HTTP]: + results.append( + await trial( + num_replicas=num_replicas, + max_ongoing_requests=max_ongoing_requests, + data_size=data_size, + num_clients=num_clients, + proxy=proxy, + ) + ) + + print(f"Total time: {time.time() - start_time}s") + print("results", results) + + df = pd.DataFrame.from_dict(results) + df = df.sort_values( + by=["proxy", "num_client", "replica", "concurrent_queries", "data_size"] + ) + print("Results from all conditions:") + # Print the results in with tab separated so we can copy into google sheets. + for i in range(len(df.index)): + row = list(df.iloc[i]) + print("\t".join(map(str, row))) + + +if __name__ == "__main__": + ray.init() + + grpc_port = 9000 + grpc_servicer_functions = [ + "ray.serve.generated.serve_pb2_grpc." + "add_RayServeBenchmarkServiceServicer_to_server", + ] + serve.start( + grpc_options=gRPCOptions( + port=grpc_port, + grpc_servicer_functions=grpc_servicer_functions, + ) + ) + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + loop.run_until_complete(main()) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/__init__.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f205896ead8326e247a8af7fa10078e1fd7d31c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/common.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4391a99efc82e371b65777a647601ee8efc3fb9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/common.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/serialization_benchmark.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/serialization_benchmark.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6edc39d230c0e4e6c91c44128c539bfc68d049db Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/__pycache__/serialization_benchmark.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/common.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/common.py new file mode 100644 index 0000000000000000000000000000000000000000..41d535ceaf365044226661c9244312f14d2b260a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/common.py @@ -0,0 +1,29 @@ +from dataclasses import dataclass +from typing import List, Optional + +from pydantic import BaseModel + +# +# NOTE: PLEASE READ CAREFULLY BEFORE CHANGING +# +# Payloads in this module are purposefully extracted from benchmark file to force +# Ray's cloudpickle behavior when it does NOT serialize the class definition itself +# along with its payload (instead relying on it being imported) +# + + +class PayloadPydantic(BaseModel): + text: Optional[str] = None + floats: Optional[List[float]] = None + ints: Optional[List[int]] = None + ts: Optional[float] = None + reason: Optional[str] = None + + +@dataclass +class PayloadDataclass: + text: Optional[str] = None + floats: Optional[List[float]] = None + ints: Optional[List[int]] = None + ts: Optional[float] = None + reason: Optional[str] = None diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/serialization_benchmark.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/serialization_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..12e600758c2213b9c000c2cdc041433f2dff3323 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/serialization/serialization_benchmark.py @@ -0,0 +1,163 @@ +import asyncio +import enum +import pickle +import time +from typing import Any, Callable + +import click +import msgpack + +from ray._private.serialization import SerializationContext +from ray.cloudpickle import cloudpickle_fast +from ray.serve._private.benchmarks.common import ( + collect_profile_events, + run_latency_benchmark, +) +from ray.serve._private.benchmarks.serialization.common import ( + PayloadDataclass, + PayloadPydantic, +) + + +class PayloadType(enum.Enum): + PYDANTIC = "pydantic" + DATACLASS = "dataclass" + + +class SerializerType(enum.Enum): + RAY = "ray" + PICKLE = "pickle" + CLOUDPICKLE = "cloudpickle" + MSGPACK = "msgpack" + + +_PERCENTILES = [0.5, 0.99] + + +sc = SerializationContext(None) + + +def _create_model(cls): + return cls( + text="Test output", + floats=[float(f) for f in range(1, 100)], + ints=list(range(1, 100)), + ts=time.time(), + reason="Success!", + ) + + +def _blackhole(o): + """Placeholder to be used in the benchmark to make sure runtime + doesn't optimize out unused results""" + pass + + +async def run_serializer_benchmark( + model, serializer: Callable[[Any], bytes], iterations: int +): + def _serde_loop(): + bs = serializer(model) + _blackhole(bs) + + pd = await run_latency_benchmark(_serde_loop, iterations) + + print("Latencies (ms):\n", pd.describe(percentiles=_PERCENTILES)) + + +@click.command(help="Benchmark serialization latency") +@click.option( + "--trials", + type=int, + default=1000, + help="Total number of trials to run in a single benchmark run", +) +@click.option( + "--batch-size", + type=int, + default=10, + help="Controls how many objects are contained in a serialized batch", +) +@click.option( + "--payload-type", + type=PayloadType, + help="Target type of the payload to be benchmarked (supported: pydantic, " + "dataclass)", +) +@click.option( + "--serializer", + type=SerializerType, + help="Target type of the serializer to be benchmarked (supported: ray, pickle, " + "cloudpickle, msgpack)", +) +@click.option( + "--profile-events", + type=bool, + default=False, +) +def main( + trials: int, + batch_size: int, + payload_type: PayloadType, + serializer: SerializerType, + profile_events: bool, +): + if serializer == SerializerType.RAY: + + def _serialize(obj): + so = sc.serialize(obj) + bs = so.to_bytes() + return bs + + elif serializer == SerializerType.CLOUDPICKLE: + + def _serialize(obj): + bs = cloudpickle_fast.dumps(obj) + return bs + + elif serializer == SerializerType.PICKLE: + + def _serialize(obj): + bs = pickle.dumps(obj) + return bs + + elif serializer == SerializerType.MSGPACK: + + def _dumps(obj): + bs = msgpack.dumps(obj.__dict__) + # print(f"Bytes ({len(bs)}): ", bs) + return bs + + def _loads(bs): + dict = msgpack.loads(bs) + return PayloadPydantic(**dict) + + sc._register_cloudpickle_serializer(PayloadPydantic, _dumps, _loads) + + def _serialize(obj): + so = sc.serialize(obj) + bs = so.to_bytes() + return bs + + else: + raise NotImplementedError(serializer) + + if payload_type == PayloadType.PYDANTIC: + model = _create_model(PayloadPydantic) + elif payload_type == PayloadType.DATACLASS: + model = _create_model(PayloadDataclass) + else: + raise NotImplementedError(f"Not supported ({payload_type})") + + payload = [model.copy(deep=True) for _ in range(batch_size)] + + routine = run_serializer_benchmark(payload, _serialize, trials) + + if profile_events: + routine = collect_profile_events(routine) + + asyncio.run(routine) + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__init__.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4068c49e49c2e8c5efcc38ae9194fe5ce736739d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/common.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd8fad406fd747799985e36d17b08f3c32070ba8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/common.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_core_throughput.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_core_throughput.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23822f5e1d1b1f1a4206fbd145c63022431ecf32 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_core_throughput.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_grpc_throughput.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_grpc_throughput.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbcf196b8ec8ca69b72e95751e5b5860c3384e62 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_grpc_throughput.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_handle_throughput.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_handle_throughput.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcf525806593693779c8ffda8f2ed6d854ecbade Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_handle_throughput.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_http_throughput.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_http_throughput.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55781fd599aeb7f325f034bf5aa7afd01f345926 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/__pycache__/streaming_http_throughput.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__init__.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b24e77b6560e0f4c71432b11bb6564a6e14d477f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/grpc_server.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/grpc_server.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65f24ef83977b05a9f9334d3bbdc42707f36be75 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/grpc_server.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/test_server_pb2_grpc.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/test_server_pb2_grpc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..048bb97859e6d905a59133d33527088062538c67 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/__pycache__/test_server_pb2_grpc.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/grpc_server.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/grpc_server.py new file mode 100644 index 0000000000000000000000000000000000000000..40f183216c79c545e623b1e3158c3de9138c439a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/grpc_server.py @@ -0,0 +1,60 @@ +import grpc + +from ray.serve._private.benchmarks.streaming._grpc import ( + test_server_pb2, + test_server_pb2_grpc, +) + + +async def _async_list(async_iterator): + items = [] + async for item in async_iterator: + items.append(item) + + return items + + +class TestGRPCServer(test_server_pb2_grpc.GRPCTestServerServicer): + def __init__(self, tokens_per_request): + self._tokens_per_request = tokens_per_request + + async def Unary(self, request, context): + if request.request_data == "error": + await context.abort( + code=grpc.StatusCode.INTERNAL, + details="unary rpc error", + ) + + return test_server_pb2.Response(response_data="OK") + + async def ClientStreaming(self, request_iterator, context): + data = await _async_list(request_iterator) + + if data and data[0].request_data == "error": + await context.abort( + code=grpc.StatusCode.INTERNAL, + details="client streaming rpc error", + ) + + return test_server_pb2.Response(response_data="OK") + + async def ServerStreaming(self, request, context): + if request.request_data == "error": + await context.abort( + code=grpc.StatusCode.INTERNAL, + details="OK", + ) + + for i in range(self._tokens_per_request): + yield test_server_pb2.Response(response_data="OK") + + async def BidiStreaming(self, request_iterator, context): + data = await _async_list(request_iterator) + if data and data[0].request_data == "error": + await context.abort( + code=grpc.StatusCode.INTERNAL, + details="bidi-streaming rpc error", + ) + + for i in range(self._tokens_per_request): + yield test_server_pb2.Response(response_data="OK") diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/test_server_pb2_grpc.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/test_server_pb2_grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..96d5ebfbfd531cdb730b3f5e77b38c8982a09d57 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/_grpc/test_server_pb2_grpc.py @@ -0,0 +1,216 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc + +from ray.serve._private.benchmarks.streaming._grpc import ( + test_server_pb2 as backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2, +) + + +class GRPCTestServerStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.Unary = channel.unary_unary( + "/GRPCTestServer/Unary", + request_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + response_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + ) + self.ClientStreaming = channel.stream_unary( + "/GRPCTestServer/ClientStreaming", + request_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + response_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + ) + self.ServerStreaming = channel.unary_stream( + "/GRPCTestServer/ServerStreaming", + request_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + response_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + ) + self.BidiStreaming = channel.stream_stream( + "/GRPCTestServer/BidiStreaming", + request_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + response_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + ) + + +class GRPCTestServerServicer(object): + """Missing associated documentation comment in .proto file.""" + + def Unary(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def ClientStreaming(self, request_iterator, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def ServerStreaming(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def BidiStreaming(self, request_iterator, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + +def add_GRPCTestServerServicer_to_server(servicer, server): + rpc_method_handlers = { + "Unary": grpc.unary_unary_rpc_method_handler( + servicer.Unary, + request_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.FromString, + response_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.SerializeToString, + ), + "ClientStreaming": grpc.stream_unary_rpc_method_handler( + servicer.ClientStreaming, + request_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.FromString, + response_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.SerializeToString, + ), + "ServerStreaming": grpc.unary_stream_rpc_method_handler( + servicer.ServerStreaming, + request_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.FromString, + response_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.SerializeToString, + ), + "BidiStreaming": grpc.stream_stream_rpc_method_handler( + servicer.BidiStreaming, + request_deserializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.FromString, + response_serializer=backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + "GRPCTestServer", rpc_method_handlers + ) + server.add_generic_rpc_handlers((generic_handler,)) + + +# This class is part of an EXPERIMENTAL API. +class GRPCTestServer(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def Unary( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.unary_unary( + request, + target, + "/GRPCTestServer/Unary", + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) + + @staticmethod + def ClientStreaming( + request_iterator, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.stream_unary( + request_iterator, + target, + "/GRPCTestServer/ClientStreaming", + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) + + @staticmethod + def ServerStreaming( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.unary_stream( + request, + target, + "/GRPCTestServer/ServerStreaming", + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) + + @staticmethod + def BidiStreaming( + request_iterator, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.stream_stream( + request_iterator, + target, + "/GRPCTestServer/BidiStreaming", + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Request.SerializeToString, + backend_dot_server_dot_common_dot_clients_dot_grpc_dot_proto_dot_test__server__pb2.Response.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/common.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/common.py new file mode 100644 index 0000000000000000000000000000000000000000..f5378565f0f089568c530b43167b770ed7db4315 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/common.py @@ -0,0 +1,123 @@ +import abc +import asyncio +import enum +import logging +import time +from typing import Tuple, Union + +import numpy as np + +from ray.actor import ActorHandle +from ray.runtime_env import RuntimeEnv +from ray.serve._private.benchmarks.common import Blackhole, run_throughput_benchmark +from ray.serve._private.benchmarks.serialization.common import PayloadPydantic +from ray.serve.handle import DeploymentHandle + +GRPC_DEBUG_RUNTIME_ENV = RuntimeEnv( + env_vars={"GRPC_TRACE": "http", "GRPC_VERBOSITY": "debug"}, +) + + +class IOMode(enum.Enum): + SYNC = "SYNC" + ASYNC = "ASYNC" + + +class Endpoint: + def __init__(self, tokens_per_request: int): + self._tokens_per_request = tokens_per_request + # Switch off logging to minimize its impact + logging.getLogger("ray").setLevel(logging.WARNING) + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + def stream(self): + payload = PayloadPydantic( + text="Test output", + floats=[float(f) for f in range(1, 100)], + ints=list(range(1, 100)), + ts=time.time(), + reason="Success!", + ) + + for i in range(self._tokens_per_request): + yield payload + + async def aio_stream(self): + payload = PayloadPydantic( + text="Test output", + floats=[float(f) for f in range(1, 100)], + ints=list(range(1, 100)), + ts=time.time(), + reason="Success!", + ) + + for i in range(self._tokens_per_request): + yield payload + + +class Caller(Blackhole): + def __init__( + self, + downstream: Union[ActorHandle, DeploymentHandle], + *, + mode: IOMode, + tokens_per_request: int, + batch_size: int, + num_trials: int, + trial_runtime: float, + ): + self._h = downstream + self._mode = mode + self._tokens_per_request = tokens_per_request + self._batch_size = batch_size + self._num_trials = num_trials + self._trial_runtime = trial_runtime + self._durations = [] + + # Switch off logging to minimize its impact + logging.getLogger("ray").setLevel(logging.WARNING) + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + def _get_remote_method(self): + if self._mode == IOMode.SYNC: + return self._h.stream + elif self._mode == IOMode.ASYNC: + return self._h.aio_stream + else: + raise NotImplementedError(f"Streaming mode not supported ({self._mode})") + + @abc.abstractmethod + async def _consume_single_stream(self): + pass + + async def _do_single_batch(self): + durations = await asyncio.gather( + *[ + self._execute(self._consume_single_stream) + for _ in range(self._batch_size) + ] + ) + + self._durations.extend(durations) + + async def _execute(self, fn): + start = time.monotonic() + await fn() + dur_s = time.monotonic() - start + return dur_s * 1000 # ms + + async def run_benchmark(self) -> Tuple[float, float]: + coro = run_throughput_benchmark( + fn=self._do_single_batch, + multiplier=self._batch_size * self._tokens_per_request, + num_trials=self._num_trials, + trial_runtime=self._trial_runtime, + ) + # total_runtime = await collect_profile_events(coro) + total_runtime = await coro + + p50, p75, p99 = np.percentile(self._durations, [50, 75, 99]) + + print(f"Individual request quantiles:\n\tP50={p50}\n\tP75={p75}\n\tP99={p99}") + + return total_runtime diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_core_throughput.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_core_throughput.py new file mode 100644 index 0000000000000000000000000000000000000000..4447d9996caab67918c8760964e6d5e8ee9de0c1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_core_throughput.py @@ -0,0 +1,95 @@ +import click + +import ray +from ray.serve._private.benchmarks.streaming.common import Caller, Endpoint, IOMode + + +# @ray.remote(runtime_env=GRPC_DEBUG_RUNTIME_ENV) +@ray.remote +class EndpointActor(Endpoint): + pass + + +# @ray.remote(runtime_env=GRPC_DEBUG_RUNTIME_ENV) +@ray.remote +class CallerActor(Caller): + async def _consume_single_stream(self): + method = self._get_remote_method() + async for ref in method.options(num_returns="streaming").remote(): + r = ray.get(ref) + + # self.sink(str(r, 'utf-8')) + self.sink(r) + + +@click.command(help="Benchmark streaming deployment handle throughput.") +@click.option( + "--tokens-per-request", + type=int, + default=1000, + help="Number of tokens (per request) to stream from downstream deployment", +) +@click.option( + "--batch-size", + type=int, + default=10, + help="Number of requests to send to downstream deployment in each batch.", +) +@click.option( + "--num-replicas", + type=int, + default=1, + help="Number of replicas in the downstream deployment.", +) +@click.option( + "--num-trials", + type=int, + default=5, + help="Number of trials of the benchmark to run.", +) +@click.option( + "--trial-runtime", + type=int, + default=5, + help="Duration to run each trial of the benchmark for (seconds).", +) +@click.option( + "--io-mode", + type=str, + default="async", + help="Controls mode of the streaming generation (either 'sync' or 'async')", +) +def main( + tokens_per_request: int, + batch_size: int, + num_replicas: int, + num_trials: int, + trial_runtime: float, + io_mode: str, +): + h = CallerActor.remote( + EndpointActor.remote( + tokens_per_request=tokens_per_request, + ), + mode=IOMode(io_mode.upper()), + tokens_per_request=tokens_per_request, + batch_size=batch_size, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) + + mean, stddev = ray.get(h.run_benchmark.remote()) + print( + "Core Actors streaming throughput ({}) {}: {} +- {} tokens/s".format( + io_mode.upper(), + f"(num_replicas={num_replicas}, " + f"tokens_per_request={tokens_per_request}, " + f"batch_size={batch_size})", + mean, + stddev, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_grpc_throughput.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_grpc_throughput.py new file mode 100644 index 0000000000000000000000000000000000000000..5d6e264437cd939ed6139d2a7f126c090a825f8f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_grpc_throughput.py @@ -0,0 +1,218 @@ +import asyncio +import logging +import time +from concurrent import futures +from tempfile import TemporaryDirectory + +import click +import grpc + +import ray +from ray.serve._private.benchmarks.streaming._grpc import ( + test_server_pb2, + test_server_pb2_grpc, +) +from ray.serve._private.benchmarks.streaming._grpc.grpc_server import TestGRPCServer +from ray.serve._private.benchmarks.streaming.common import Caller, IOMode + + +# @ray.remote(runtime_env=GRPC_DEBUG_RUNTIME_ENV) +@ray.remote +class EndpointActor: + async def __init__(self, tokens_per_request, socket_type, tempdir): + # Switch off logging to minimize its impact + logging.getLogger("ray").setLevel(logging.WARNING) + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + self.server = await self.start_server(tokens_per_request, socket_type, tempdir) + + print("gRPC server started!") + + @staticmethod + async def start_server(tokens_per_request, socket_type, tempdir): + server = grpc.aio.server(futures.ThreadPoolExecutor(max_workers=1)) + + addr, server_creds, _ = _gen_addr_creds(socket_type, tempdir) + + server.add_secure_port(addr, server_creds) + + await server.start() + + test_server_pb2_grpc.add_GRPCTestServerServicer_to_server( + TestGRPCServer(tokens_per_request), server + ) + + return server + + +# @ray.remote(runtime_env=GRPC_DEBUG_RUNTIME_ENV) +@ray.remote +class GrpcCallerActor(Caller): + def __init__( + self, + tempdir, + socket_type, + *, + mode: IOMode, + tokens_per_request: int, + batch_size: int, + num_trials: int, + trial_runtime: float, + ): + super().__init__( + self.create_downstream(socket_type, tempdir), + mode=mode, + tokens_per_request=tokens_per_request, + batch_size=batch_size, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) + + @staticmethod + def create_downstream(socket_type, tempdir): + addr, _, channel_creds = _gen_addr_creds(socket_type, tempdir) + + channel = grpc.aio.secure_channel( + addr, credentials=channel_creds, interceptors=[] + ) + + return test_server_pb2_grpc.GRPCTestServerStub(channel) + + async def _consume_single_stream(self): + try: + async for r in self._h.ServerStreaming(test_server_pb2.Request()): + self.sink(r) + except Exception as e: + print(str(e)) + + +def _gen_addr_creds(socket_type, tempdir): + if socket_type == "uds": + addr = f"unix://{tempdir}/server.sock" + server_creds = grpc.local_server_credentials(grpc.LocalConnectionType.UDS) + channel_creds = grpc.local_channel_credentials(grpc.LocalConnectionType.UDS) + elif socket_type == "local_tcp": + addr = "127.0.0.1:5432" + server_creds = grpc.local_server_credentials(grpc.LocalConnectionType.LOCAL_TCP) + channel_creds = grpc.local_channel_credentials( + grpc.LocalConnectionType.LOCAL_TCP + ) + else: + raise NotImplementedError(f"Not supported socket type ({socket_type})") + + return addr, server_creds, channel_creds + + +async def run_grpc_benchmark( + batch_size, + io_mode, + socket_type, + num_replicas, + num_trials, + tokens_per_request, + trial_runtime, +): + with TemporaryDirectory() as tempdir: + _ = EndpointActor.remote( + tokens_per_request=tokens_per_request, + socket_type=socket_type, + tempdir=tempdir, + ) + + ca = GrpcCallerActor.remote( + tempdir, + socket_type, + mode=IOMode(io_mode.upper()), + tokens_per_request=tokens_per_request, + batch_size=batch_size, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) + + # TODO make starting server a method (to make synchronization explicit) + time.sleep(5) + + mean, stddev = await ca.run_benchmark.remote() + + print( + "gRPC streaming throughput ({}) {}: {} +- {} tokens/s".format( + io_mode.upper(), + f"(num_replicas={num_replicas}, " + f"tokens_per_request={tokens_per_request}, " + f"batch_size={batch_size})", + mean, + stddev, + ) + ) + + +@click.command(help="Benchmark streaming deployment handle throughput.") +@click.option( + "--tokens-per-request", + type=int, + default=1000, + help="Number of tokens (per request) to stream from downstream deployment", +) +@click.option( + "--batch-size", + type=int, + default=10, + help="Number of requests to send to downstream deployment in each batch.", +) +@click.option( + "--num-replicas", + type=int, + default=1, + help="Number of replicas in the downstream deployment.", +) +@click.option( + "--num-trials", + type=int, + default=5, + help="Number of trials of the benchmark to run.", +) +@click.option( + "--trial-runtime", + type=int, + default=5, + help="Duration to run each trial of the benchmark for (seconds).", +) +@click.option( + "--io-mode", + type=str, + default="async", + help="Controls mode of the streaming generation (either 'sync' or 'async')", +) +@click.option( + "--socket-type", + type=str, + default="local_tcp", + help="Controls type of socket used as underlying transport (either 'uds' or " + "'local_tcp')", +) +def main( + tokens_per_request: int, + batch_size: int, + num_replicas: int, + num_trials: int, + trial_runtime: float, + io_mode: str, + socket_type: grpc.LocalConnectionType, +): + """Reference benchmark for vanilla Python (w/ C-based core) gRPC implementation""" + + asyncio.run( + run_grpc_benchmark( + batch_size, + io_mode, + socket_type, + num_replicas, + num_trials, + tokens_per_request, + trial_runtime, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_handle_throughput.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_handle_throughput.py new file mode 100644 index 0000000000000000000000000000000000000000..77ed697053b3bdb5437aa28ee7aff24bf5a1e317 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_handle_throughput.py @@ -0,0 +1,94 @@ +import click + +from ray import serve +from ray.serve._private.benchmarks.streaming.common import Caller, Endpoint, IOMode + + +@serve.deployment(ray_actor_options={"num_cpus": 0}) +class EndpointDeployment(Endpoint): + pass + + +@serve.deployment +class CallerDeployment(Caller): + async def _consume_single_stream(self): + method = self._get_remote_method().options( + stream=True, + ) + + async for r in method.remote(): + # Blackhole the response + # self.sink(str(r, 'utf-8')) + self.sink(r) + + +@click.command(help="Benchmark streaming deployment handle throughput.") +@click.option( + "--tokens-per-request", + type=int, + default=1000, + help="Number of requests to send to downstream deployment in each trial.", +) +@click.option( + "--batch-size", + type=int, + default=10, + help="Number of requests to send to downstream deployment in each trial.", +) +@click.option( + "--num-replicas", + type=int, + default=1, + help="Number of replicas in the downstream deployment.", +) +@click.option( + "--num-trials", + type=int, + default=5, + help="Number of trials of the benchmark to run.", +) +@click.option( + "--trial-runtime", + type=int, + default=1, + help="Duration to run each trial of the benchmark for (seconds).", +) +@click.option( + "--io-mode", + type=str, + default="async", + help="Controls mode of the streaming generation (either 'sync' or 'async')", +) +def main( + tokens_per_request: int, + batch_size: int, + num_replicas: int, + num_trials: int, + trial_runtime: float, + io_mode: str, +): + app = CallerDeployment.bind( + EndpointDeployment.options(num_replicas=num_replicas).bind(tokens_per_request), + mode=IOMode(io_mode.upper()), + tokens_per_request=tokens_per_request, + batch_size=batch_size, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) + h = serve.run(app) + + mean, stddev = h.run_benchmark.remote().result() + print( + "DeploymentHandle streaming throughput ({}) {}: {} +- {} tokens/s".format( + io_mode.upper(), + f"(num_replicas={num_replicas}, " + f"tokens_per_request={tokens_per_request}, " + f"batch_size={batch_size})", + mean, + stddev, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_http_throughput.py b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_http_throughput.py new file mode 100644 index 0000000000000000000000000000000000000000..b80b5e5b5dac41059362a1b13e762114efcd1717 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/benchmarks/streaming/streaming_http_throughput.py @@ -0,0 +1,140 @@ +import asyncio +import logging +from typing import Tuple + +import aiohttp +import click +from starlette.responses import StreamingResponse + +from ray import serve +from ray.serve._private.benchmarks.common import run_throughput_benchmark +from ray.serve.handle import DeploymentHandle + + +@serve.deployment(ray_actor_options={"num_cpus": 0}) +class Downstream: + def __init__(self, tokens_per_request: int): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + self._tokens_per_request = tokens_per_request + + async def stream(self): + for i in range(self._tokens_per_request): + yield "hi" + + def __call__(self, *args): + return StreamingResponse(self.stream()) + + +@serve.deployment(ray_actor_options={"num_cpus": 0}) +class Intermediate: + def __init__(self, downstream: DeploymentHandle): + logging.getLogger("ray.serve").setLevel(logging.WARNING) + + self._h = downstream.options(stream=True) + + async def stream(self): + async for token in self._h.stream.remote(): + yield token + + def __call__(self, *args): + return StreamingResponse(self.stream()) + + +async def _consume_single_stream(): + async with aiohttp.ClientSession(raise_for_status=True) as session: + async with session.get("http://localhost:8000") as r: + async for line in r.content: + pass + + +async def run_benchmark( + tokens_per_request: int, + batch_size: int, + num_trials: int, + trial_runtime: float, +) -> Tuple[float, float]: + async def _do_single_batch(): + await asyncio.gather(*[_consume_single_stream() for _ in range(batch_size)]) + + return await run_throughput_benchmark( + fn=_do_single_batch, + multiplier=batch_size * tokens_per_request, + num_trials=num_trials, + trial_runtime=trial_runtime, + ) + + +@click.command(help="Benchmark streaming HTTP throughput.") +@click.option( + "--tokens-per-request", + type=int, + default=1000, + help="Number of requests to send to downstream deployment in each trial.", +) +@click.option( + "--batch-size", + type=int, + default=10, + help="Number of requests to send to downstream deployment in each trial.", +) +@click.option( + "--num-replicas", + type=int, + default=1, + help="Number of replicas in the downstream deployment.", +) +@click.option( + "--num-trials", + type=int, + default=5, + help="Number of trials of the benchmark to run.", +) +@click.option( + "--trial-runtime", + type=int, + default=1, + help="Duration to run each trial of the benchmark for (seconds).", +) +@click.option( + "--use-intermediate-deployment", + is_flag=True, + default=False, + help="Whether to run an intermediate deployment proxying the requests.", +) +def main( + tokens_per_request: int, + batch_size: int, + num_replicas: int, + num_trials: int, + trial_runtime: float, + use_intermediate_deployment: bool, +): + app = Downstream.options(num_replicas=num_replicas).bind(tokens_per_request) + if use_intermediate_deployment: + app = Intermediate.bind(app) + + serve.run(app) + + mean, stddev = asyncio.new_event_loop().run_until_complete( + run_benchmark( + tokens_per_request, + batch_size, + num_trials, + trial_runtime, + ) + ) + print( + "HTTP streaming throughput {}: {} +- {} tokens/s".format( + f"(num_replicas={num_replicas}, " + f"tokens_per_request={tokens_per_request}, " + f"batch_size={batch_size}, " + f"use_intermediate_deployment={use_intermediate_deployment})", + mean, + stddev, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/build_app.py b/venv/lib/python3.10/site-packages/ray/serve/_private/build_app.py new file mode 100644 index 0000000000000000000000000000000000000000..b52cca21812b1330130d732cd70b8eaf7e7ca77a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/build_app.py @@ -0,0 +1,237 @@ +import logging +from copy import deepcopy +from dataclasses import dataclass +from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar, Union + +from ray.dag.py_obj_scanner import _PyObjScanner +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve.deployment import Application, Deployment +from ray.serve.handle import DeploymentHandle +from ray.serve.schema import LoggingConfig + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +K = TypeVar("K") +V = TypeVar("V") + + +class IDDict(dict, Generic[K, V]): + """Dictionary that uses id() for keys instead of hash(). + + This is necessary because Application objects aren't hashable and we want each + instance to map to a unique key. + """ + + def __getitem__(self, key: K) -> V: + if not isinstance(key, int): + key = id(key) + return super().__getitem__(key) + + def __setitem__(self, key: K, value: V): + if not isinstance(key, int): + key = id(key) + return super().__setitem__(key, value) + + def __delitem__(self, key: K): + if not isinstance(key, int): + key = id(key) + return super().__delitem__(key) + + def __contains__(self, key: object): + if not isinstance(key, int): + key = id(key) + return super().__contains__(key) + + +@dataclass(frozen=True) +class BuiltApplication: + # Name of the application. + name: str + route_prefix: Optional[str] + logging_config: Optional[LoggingConfig] + # Name of the application's 'ingress' deployment + # (the one exposed over gRPC/HTTP/handle). + ingress_deployment_name: str + # List of unique deployments comprising the app. + deployments: List[Deployment] + # Dict[name, DeploymentHandle] mapping deployment names to the handles that replaced + # them in other deployments' init args/kwargs. + deployment_handles: Dict[str, DeploymentHandle] + + +def _make_deployment_handle_default( + deployment: Deployment, app_name: str +) -> DeploymentHandle: + return DeploymentHandle( + deployment.name, + app_name=app_name, + ) + + +def build_app( + app: Application, + *, + name: str, + route_prefix: Optional[str] = None, + logging_config: Optional[Union[Dict, LoggingConfig]] = None, + default_runtime_env: Optional[Dict[str, Any]] = None, + make_deployment_handle: Optional[ + Callable[[Deployment, str], DeploymentHandle] + ] = None, +) -> BuiltApplication: + """Builds the application into a list of finalized deployments. + + The following transformations are made: + - Application objects in constructor args/kwargs are converted to + DeploymentHandles for injection at runtime. + - Name conflicts from deployments that use the same class are handled + by appending a monotonically increasing suffix (e.g., SomeClass_1). + + Returns: BuiltApplication + """ + if make_deployment_handle is None: + make_deployment_handle = _make_deployment_handle_default + + handles = IDDict() + deployment_names = IDDict() + deployments = _build_app_recursive( + app, + app_name=name, + handles=handles, + deployment_names=deployment_names, + default_runtime_env=default_runtime_env, + make_deployment_handle=make_deployment_handle, + ) + return BuiltApplication( + name=name, + route_prefix=route_prefix, + logging_config=logging_config, + ingress_deployment_name=app._bound_deployment.name, + deployments=deployments, + deployment_handles={ + deployment_names[app]: handle for app, handle in handles.items() + }, + ) + + +def _build_app_recursive( + app: Application, + *, + app_name: str, + deployment_names: IDDict[Application, str], + handles: IDDict[Application, DeploymentHandle], + default_runtime_env: Optional[Dict[str, Any]] = None, + make_deployment_handle: Callable[[Deployment, str], DeploymentHandle], +) -> List[Deployment]: + """Recursively traverses the graph of Application objects. + + Each Application will have an associated DeploymentHandle created that will replace + it in any occurrences in other Applications' args or kwargs. + + Also collects a list of the unique Applications encountered and returns them as + deployable Deployment objects. + """ + # This application has already been encountered. + # There's no need to recurse into its child args and we don't want to create + # a duplicate entry for it in the list of deployments. + if app in handles: + return [] + + deployments = [] + scanner = _PyObjScanner(source_type=Application) + try: + # Recursively traverse any Application objects bound to init args/kwargs. + child_apps = scanner.find_nodes( + (app._bound_deployment.init_args, app._bound_deployment.init_kwargs) + ) + for child_app in child_apps: + deployments.extend( + _build_app_recursive( + child_app, + app_name=app_name, + handles=handles, + deployment_names=deployment_names, + make_deployment_handle=make_deployment_handle, + default_runtime_env=default_runtime_env, + ) + ) + + # Replace Application objects with their corresponding DeploymentHandles. + new_init_args, new_init_kwargs = scanner.replace_nodes(handles) + final_deployment = app._bound_deployment.options( + name=_get_unique_deployment_name_memoized(app, deployment_names), + _init_args=new_init_args, + _init_kwargs=new_init_kwargs, + ) + final_deployment = _set_default_runtime_env( + final_deployment, default_runtime_env + ) + + # Create the DeploymentHandle that will be used to replace this application + # in the arguments of its parent(s). + handles[app] = make_deployment_handle( + final_deployment, + app_name, + ) + + return deployments + [final_deployment] + finally: + scanner.clear() + + +def _set_default_runtime_env( + d: Deployment, default_runtime_env: Optional[Dict[str, Any]] +) -> Deployment: + """Configures the deployment with the provided default runtime_env. + + If the deployment does not have a runtime_env configured, the default will be set. + + If it does have a runtime_env configured but that runtime_env does not have a + working_dir, only the working_dir field will be set. + + Else the deployment's runtime_env will be left untouched. + """ + if not default_runtime_env: + return d + + ray_actor_options = deepcopy(d.ray_actor_options or {}) + default_working_dir = default_runtime_env.get("working_dir", None) + if "runtime_env" not in ray_actor_options: + ray_actor_options["runtime_env"] = default_runtime_env + elif default_working_dir is not None: + ray_actor_options["runtime_env"].setdefault("working_dir", default_working_dir) + + return d.options(ray_actor_options=ray_actor_options) + + +def _get_unique_deployment_name_memoized( + app: Application, deployment_names: IDDict[Application, str] +) -> str: + """Generates a name for the deployment. + + This is used to handle collisions when the user does not specify a name + explicitly, so typically we'd use the class name as the default. + + In that case, we append a monotonically increasing suffix to the name, e.g., + Deployment, then Deployment_1, then Deployment_2, ... + + Names are memoized in the `deployment_names` dict, which should be passed to + subsequent calls to this function. + """ + if app in deployment_names: + return deployment_names[app] + + idx = 1 + name = app._bound_deployment.name + while name in deployment_names.values(): + name = f"{app._bound_deployment.name}_{idx}" + idx += 1 + + if idx != 1: + logger.warning( + "There are multiple deployments with the same name " + f"'{app._bound_deployment.name}'. Renaming one to '{name}'." + ) + + deployment_names[app] = name + return name diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/client.py b/venv/lib/python3.10/site-packages/ray/serve/_private/client.py new file mode 100644 index 0000000000000000000000000000000000000000..0b69def0cf2196daae0af190aebd94a346525cc3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/client.py @@ -0,0 +1,495 @@ +import logging +import random +import time +from collections.abc import Sequence +from functools import wraps +from typing import Callable, Dict, List, Optional, Tuple, Union + +import ray +from ray.actor import ActorHandle +from ray.serve._private.application_state import StatusOverview +from ray.serve._private.build_app import BuiltApplication +from ray.serve._private.common import ( + DeploymentID, + DeploymentStatus, + DeploymentStatusInfo, + RequestRoutingInfo, +) +from ray.serve._private.constants import ( + CLIENT_CHECK_CREATION_POLLING_INTERVAL_S, + CLIENT_POLLING_INTERVAL_S, + MAX_CACHED_HANDLES, + SERVE_DEFAULT_APP_NAME, + SERVE_LOGGER_NAME, +) +from ray.serve._private.controller import ServeController +from ray.serve._private.deploy_utils import get_deploy_args +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.utils import get_random_string +from ray.serve.config import HTTPOptions +from ray.serve.exceptions import RayServeException +from ray.serve.generated.serve_pb2 import ( + DeploymentArgs, + DeploymentRoute, + DeploymentStatusInfo as DeploymentStatusInfoProto, + StatusOverview as StatusOverviewProto, +) +from ray.serve.handle import DeploymentHandle +from ray.serve.schema import ( + ApplicationStatus, + LoggingConfig, + ServeApplicationSchema, + ServeDeploySchema, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +def _ensure_connected(f: Callable) -> Callable: + @wraps(f) + def check(self, *args, **kwargs): + if self._shutdown: + raise RayServeException("Client has already been shut down.") + return f(self, *args, **kwargs) + + return check + + +class ServeControllerClient: + def __init__( + self, + controller: ActorHandle, + ): + self._controller: ServeController = controller + self._shutdown = False + self._http_config: HTTPOptions = ray.get(controller.get_http_config.remote()) + self._root_url = ray.get(controller.get_root_url.remote()) + + # Each handle has the overhead of long poll client, therefore cached. + self.handle_cache = dict() + self._evicted_handle_keys = set() + + @property + def root_url(self): + return self._root_url + + @property + def http_config(self): + return self._http_config + + def __reduce__(self): + raise RayServeException(("Ray Serve client cannot be serialized.")) + + def shutdown_cached_handles(self): + """Shuts down all cached handles. + + Remove the reference to the cached handles so that they can be + garbage collected. + """ + for cache_key in list(self.handle_cache): + self.handle_cache[cache_key].shutdown() + del self.handle_cache[cache_key] + + def shutdown(self, timeout_s: float = 30.0) -> None: + """Completely shut down the connected Serve instance. + + Shuts down all processes and deletes all state associated with the + instance. + """ + self.shutdown_cached_handles() + + if ray.is_initialized() and not self._shutdown: + try: + ray.get(self._controller.graceful_shutdown.remote(), timeout=timeout_s) + except ray.exceptions.RayActorError: + # Controller has been shut down. + pass + except TimeoutError: + logger.warning( + f"Controller failed to shut down within {timeout_s}s. " + "Check controller logs for more details." + ) + self._shutdown = True + + def _wait_for_deployment_healthy(self, name: str, timeout_s: int = -1): + """Waits for the named deployment to enter "HEALTHY" status. + + Raises RuntimeError if the deployment enters the "UNHEALTHY" status + instead. + + Raises TimeoutError if this doesn't happen before timeout_s. + """ + start = time.time() + while time.time() - start < timeout_s or timeout_s < 0: + status_bytes = ray.get(self._controller.get_deployment_status.remote(name)) + + if status_bytes is None: + raise RuntimeError( + f"Waiting for deployment {name} to be HEALTHY, " + "but deployment doesn't exist." + ) + + status = DeploymentStatusInfo.from_proto( + DeploymentStatusInfoProto.FromString(status_bytes) + ) + + if status.status == DeploymentStatus.HEALTHY: + break + elif status.status == DeploymentStatus.UNHEALTHY: + raise RuntimeError( + f"Deployment {name} is UNHEALTHY: " f"{status.message}" + ) + else: + # Guard against new unhandled statuses being added. + assert status.status == DeploymentStatus.UPDATING + + logger.debug( + f"Waiting for {name} to be healthy, current status: " + f"{status.status}." + ) + time.sleep(CLIENT_POLLING_INTERVAL_S) + else: + raise TimeoutError( + f"Deployment {name} did not become HEALTHY after {timeout_s}s." + ) + + def _wait_for_deployment_deleted( + self, name: str, app_name: str, timeout_s: int = 60 + ): + """Waits for the named deployment to be shut down and deleted. + + Raises TimeoutError if this doesn't happen before timeout_s. + """ + start = time.time() + while time.time() - start < timeout_s: + curr_status_bytes = ray.get( + self._controller.get_deployment_status.remote(name) + ) + if curr_status_bytes is None: + break + curr_status = DeploymentStatusInfo.from_proto( + DeploymentStatusInfoProto.FromString(curr_status_bytes) + ) + logger.debug( + f"Waiting for {name} to be deleted, current status: {curr_status}." + ) + time.sleep(CLIENT_POLLING_INTERVAL_S) + else: + raise TimeoutError(f"Deployment {name} wasn't deleted after {timeout_s}s.") + + def _wait_for_deployment_created( + self, deployment_name: str, app_name: str, timeout_s: int = -1 + ): + """Waits for the named deployment to be created. + + A deployment being created simply means that its been registered + with the deployment state manager. The deployment state manager + will then continue to reconcile the deployment towards its + target state. + + Raises TimeoutError if this doesn't happen before timeout_s. + """ + + start = time.time() + while time.time() - start < timeout_s or timeout_s < 0: + status_bytes = ray.get( + self._controller.get_deployment_status.remote(deployment_name, app_name) + ) + + if status_bytes is not None: + break + + logger.debug( + f"Waiting for deployment '{deployment_name}' in application " + f"'{app_name}' to be created." + ) + time.sleep(CLIENT_CHECK_CREATION_POLLING_INTERVAL_S) + else: + raise TimeoutError( + f"Deployment '{deployment_name}' in application '{app_name}' " + f"did not become HEALTHY after {timeout_s}s." + ) + + def _wait_for_application_running(self, name: str, timeout_s: int = -1): + """Waits for the named application to enter "RUNNING" status. + + Raises: + RuntimeError: if the application enters the "DEPLOY_FAILED" status instead. + TimeoutError: if this doesn't happen before timeout_s. + """ + start = time.time() + while time.time() - start < timeout_s or timeout_s < 0: + status_bytes = ray.get(self._controller.get_serve_status.remote(name)) + if status_bytes is None: + raise RuntimeError( + f"Waiting for application {name} to be RUNNING, " + "but application doesn't exist." + ) + + status = StatusOverview.from_proto( + StatusOverviewProto.FromString(status_bytes) + ) + + if status.app_status.status == ApplicationStatus.RUNNING: + break + elif status.app_status.status == ApplicationStatus.DEPLOY_FAILED: + raise RuntimeError( + f"Deploying application {name} failed: {status.app_status.message}" + ) + + logger.debug( + f"Waiting for {name} to be RUNNING, current status: " + f"{status.app_status.status}." + ) + time.sleep(CLIENT_POLLING_INTERVAL_S) + else: + raise TimeoutError( + f"Application {name} did not become RUNNING after {timeout_s}s." + ) + + @_ensure_connected + def deploy_applications( + self, + built_apps: Sequence[BuiltApplication], + *, + wait_for_ingress_deployment_creation: bool = True, + wait_for_applications_running: bool = True, + ) -> List[DeploymentHandle]: + name_to_deployment_args_list = {} + for app in built_apps: + deployment_args_list = [] + for deployment in app.deployments: + if deployment.logging_config is None and app.logging_config: + deployment = deployment.options(logging_config=app.logging_config) + + is_ingress = deployment.name == app.ingress_deployment_name + deployment_args = get_deploy_args( + deployment.name, + ingress=is_ingress, + replica_config=deployment._replica_config, + deployment_config=deployment._deployment_config, + version=deployment._version or get_random_string(), + route_prefix=app.route_prefix if is_ingress else None, + docs_path=deployment._docs_path, + ) + + deployment_args_proto = DeploymentArgs() + deployment_args_proto.deployment_name = deployment_args[ + "deployment_name" + ] + deployment_args_proto.deployment_config = deployment_args[ + "deployment_config_proto_bytes" + ] + deployment_args_proto.replica_config = deployment_args[ + "replica_config_proto_bytes" + ] + deployment_args_proto.deployer_job_id = deployment_args[ + "deployer_job_id" + ] + if deployment_args["route_prefix"]: + deployment_args_proto.route_prefix = deployment_args["route_prefix"] + deployment_args_proto.ingress = deployment_args["ingress"] + if deployment_args["docs_path"]: + deployment_args_proto.docs_path = deployment_args["docs_path"] + + deployment_args_list.append(deployment_args_proto.SerializeToString()) + + name_to_deployment_args_list[app.name] = deployment_args_list + + ray.get( + self._controller.deploy_applications.remote(name_to_deployment_args_list) + ) + + handles = [] + for app in built_apps: + # The deployment state is not guaranteed to be created after + # deploy_application returns; the application state manager will + # need another reconcile iteration to create it. + if wait_for_ingress_deployment_creation: + self._wait_for_deployment_created(app.ingress_deployment_name, app.name) + + if wait_for_applications_running: + self._wait_for_application_running(app.name) + if app.route_prefix is not None: + url_part = " at " + self._root_url + app.route_prefix + else: + url_part = "" + logger.info(f"Application '{app.name}' is ready{url_part}.") + + handles.append( + self.get_handle( + app.ingress_deployment_name, app.name, check_exists=False + ) + ) + + return handles + + @_ensure_connected + def deploy_apps( + self, + config: Union[ServeApplicationSchema, ServeDeploySchema], + _blocking: bool = False, + ) -> None: + """Starts a task on the controller that deploys application(s) from a config. + + Args: + config: A single-application config (ServeApplicationSchema) or a + multi-application config (ServeDeploySchema) + _blocking: Whether to block until the application is running. + + Raises: + RayTaskError: If the deploy task on the controller fails. This can be + because a single-app config was deployed after deploying a multi-app + config, or vice versa. + """ + ray.get(self._controller.apply_config.remote(config)) + + if _blocking: + timeout_s = 60 + + start = time.time() + while time.time() - start < timeout_s: + curr_status = self.get_serve_status() + if curr_status.app_status.status == ApplicationStatus.RUNNING: + break + time.sleep(CLIENT_POLLING_INTERVAL_S) + else: + raise TimeoutError( + f"Serve application isn't running after {timeout_s}s." + ) + + @_ensure_connected + def delete_apps(self, names: List[str], blocking: bool = True): + if not names: + return + + logger.info(f"Deleting app {names}") + self._controller.delete_apps.remote(names) + if blocking: + start = time.time() + while time.time() - start < 60: + curr_statuses_bytes = ray.get( + self._controller.get_serve_statuses.remote(names) + ) + all_deleted = True + for cur_status_bytes in curr_statuses_bytes: + cur_status = StatusOverview.from_proto( + StatusOverviewProto.FromString(cur_status_bytes) + ) + if cur_status.app_status.status != ApplicationStatus.NOT_STARTED: + all_deleted = False + if all_deleted: + return + time.sleep(CLIENT_POLLING_INTERVAL_S) + else: + raise TimeoutError( + f"Some of these applications weren't deleted after 60s: {names}" + ) + + @_ensure_connected + def delete_all_apps(self, blocking: bool = True): + """Delete all applications""" + all_apps = [] + for status_bytes in ray.get(self._controller.list_serve_statuses.remote()): + proto = StatusOverviewProto.FromString(status_bytes) + status = StatusOverview.from_proto(proto) + all_apps.append(status.name) + self.delete_apps(all_apps, blocking) + + @_ensure_connected + def get_deployment_info( + self, name: str, app_name: str + ) -> Tuple[DeploymentInfo, str]: + deployment_route = DeploymentRoute.FromString( + ray.get(self._controller.get_deployment_info.remote(name, app_name)) + ) + return ( + DeploymentInfo.from_proto(deployment_route.deployment_info), + deployment_route.route if deployment_route.route != "" else None, + ) + + @_ensure_connected + def get_serve_status(self, name: str = SERVE_DEFAULT_APP_NAME) -> StatusOverview: + proto = StatusOverviewProto.FromString( + ray.get(self._controller.get_serve_status.remote(name)) + ) + return StatusOverview.from_proto(proto) + + @_ensure_connected + def get_all_deployment_statuses(self) -> List[DeploymentStatusInfo]: + statuses_bytes = ray.get(self._controller.get_all_deployment_statuses.remote()) + return [ + DeploymentStatusInfo.from_proto( + DeploymentStatusInfoProto.FromString(status_bytes) + ) + for status_bytes in statuses_bytes + ] + + @_ensure_connected + def get_serve_details(self) -> Dict: + return ray.get(self._controller.get_serve_instance_details.remote()) + + @_ensure_connected + def get_handle( + self, + deployment_name: str, + app_name: Optional[str] = SERVE_DEFAULT_APP_NAME, + check_exists: bool = True, + ) -> DeploymentHandle: + """Construct a handle for the specified deployment. + + Args: + deployment_name: Deployment name. + app_name: Application name. + check_exists: If False, then Serve won't check the deployment + is registered. True by default. + + Returns: + DeploymentHandle + """ + deployment_id = DeploymentID(name=deployment_name, app_name=app_name) + cache_key = (deployment_name, app_name, check_exists) + if cache_key in self.handle_cache: + return self.handle_cache[cache_key] + + if check_exists: + all_deployments = ray.get(self._controller.list_deployment_ids.remote()) + if deployment_id not in all_deployments: + raise KeyError(f"{deployment_id} does not exist.") + + handle = DeploymentHandle(deployment_name, app_name) + self.handle_cache[cache_key] = handle + if cache_key in self._evicted_handle_keys: + logger.warning( + "You just got a ServeHandle that was evicted from internal " + "cache. This means you are getting too many ServeHandles in " + "the same process, this will bring down Serve's performance. " + "Please post a github issue at " + "https://github.com/ray-project/ray/issues to let the Serve " + "team to find workaround for your use case." + ) + + if len(self.handle_cache) > MAX_CACHED_HANDLES: + # Perform random eviction to keep the handle cache from growing + # infinitely. We used use WeakValueDictionary but hit + # https://github.com/ray-project/ray/issues/18980. + evict_key = random.choice(list(self.handle_cache.keys())) + self._evicted_handle_keys.add(evict_key) + self.handle_cache.pop(evict_key) + + return handle + + @_ensure_connected + def record_request_routing_info(self, info: RequestRoutingInfo): + """Record replica routing information for a replica. + + Args: + info: RequestRoutingInfo including deployment name, replica tag, + multiplex model ids, and routing stats. + """ + self._controller.record_request_routing_info.remote(info) + + @_ensure_connected + def update_global_logging_config(self, logging_config: LoggingConfig): + """Reconfigure the logging config for the controller & proxies.""" + self._controller.reconfigure_global_logging_config.remote(logging_config) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/cluster_node_info_cache.py b/venv/lib/python3.10/site-packages/ray/serve/_private/cluster_node_info_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0121dd309d61d49409a6801650cd91a1f7f269 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/cluster_node_info_cache.py @@ -0,0 +1,102 @@ +from abc import ABC, abstractmethod +from typing import Dict, List, Optional, Set, Tuple, Union + +import ray +from ray._raylet import GcsClient +from ray.serve._private.constants import RAY_GCS_RPC_TIMEOUT_S + + +class ClusterNodeInfoCache(ABC): + """Provide access to cached node information in the cluster.""" + + def __init__(self, gcs_client: GcsClient): + self._gcs_client = gcs_client + self._cached_alive_nodes = None + self._cached_node_labels = dict() + self._cached_total_resources_per_node = dict() + self._cached_available_resources_per_node = dict() + + def update(self): + """Update the cache by fetching latest node information from GCS. + + This should be called once in each update cycle. + Within an update cycle, everyone will see the same + cached node info avoiding any potential issues + caused by inconsistent node info seen by different components. + """ + nodes = self._gcs_client.get_all_node_info(timeout=RAY_GCS_RPC_TIMEOUT_S) + alive_nodes = [ + (node_id.hex(), node.node_name, node.instance_id) + for (node_id, node) in nodes.items() + if node.state == ray.core.generated.gcs_pb2.GcsNodeInfo.ALIVE + ] + + # Sort on NodeID to ensure the ordering is deterministic across the cluster. + sorted(alive_nodes) + self._cached_alive_nodes = alive_nodes + self._cached_node_labels = { + node_id.hex(): dict(node.labels) for (node_id, node) in nodes.items() + } + + # Node resources + self._cached_total_resources_per_node = { + node_id.hex(): dict(node.resources_total) + for (node_id, node) in nodes.items() + } + + self._cached_available_resources_per_node = ( + ray._private.state.available_resources_per_node() + ) + + def get_alive_nodes(self) -> List[Tuple[str, str, str]]: + """Get IDs, IPs, and Instance IDs for all live nodes in the cluster. + + Returns a list of (node_id: str, node_ip: str, instance_id: str). + The node_id can be passed into the Ray SchedulingPolicy API. + """ + return self._cached_alive_nodes + + def get_total_resources_per_node(self) -> Dict[str, Dict]: + """Get total resources for alive nodes.""" + return self._cached_total_resources_per_node + + def get_alive_node_ids(self) -> Set[str]: + """Get IDs of all live nodes in the cluster.""" + return {node_id for node_id, _, _ in self.get_alive_nodes()} + + @abstractmethod + def get_draining_nodes(self) -> Dict[str, int]: + """Get draining nodes in the cluster and their deadlines.""" + raise NotImplementedError + + @abstractmethod + def get_node_az(self, node_id: str) -> Optional[str]: + """Get availability zone of a node.""" + raise NotImplementedError + + def get_active_node_ids(self) -> Set[str]: + """Get IDs of all active nodes in the cluster. + + A node is active if it's schedulable for new tasks and actors. + """ + return self.get_alive_node_ids() - set(self.get_draining_nodes()) + + def get_available_resources_per_node(self) -> Dict[str, Union[float, Dict]]: + """Get available resources per node. + + Returns a map from (node_id -> Dict of resources). + """ + + return self._cached_available_resources_per_node + + +class DefaultClusterNodeInfoCache(ClusterNodeInfoCache): + def __init__(self, gcs_client: GcsClient): + super().__init__(gcs_client) + + def get_draining_nodes(self) -> Dict[str, int]: + return dict() + + def get_node_az(self, node_id: str) -> Optional[str]: + """Get availability zone of a node.""" + return None diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/common.py b/venv/lib/python3.10/site-packages/ray/serve/_private/common.py new file mode 100644 index 0000000000000000000000000000000000000000..a533b46e9f6476dea0501f55cc5d11dbf429ad1b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/common.py @@ -0,0 +1,716 @@ +import json +from dataclasses import asdict, dataclass, field +from enum import Enum +from typing import Any, Awaitable, Callable, Dict, List, Optional + +from starlette.types import Scope + +import ray +from ray.actor import ActorHandle +from ray.serve._private.constants import SERVE_DEFAULT_APP_NAME, SERVE_NAMESPACE +from ray.serve.generated.serve_pb2 import ( + DeploymentStatus as DeploymentStatusProto, + DeploymentStatusInfo as DeploymentStatusInfoProto, + DeploymentStatusTrigger as DeploymentStatusTriggerProto, +) +from ray.serve.grpc_util import RayServegRPCContext +from ray.util.annotations import PublicAPI + +REPLICA_ID_FULL_ID_STR_PREFIX = "SERVE_REPLICA::" + + +@dataclass(frozen=True) +class DeploymentID: + name: str + app_name: str = SERVE_DEFAULT_APP_NAME + + def to_replica_actor_class_name(self): + return f"ServeReplica:{self.app_name}:{self.name}" + + def __str__(self): + return f"Deployment(name='{self.name}', app='{self.app_name}')" + + def __repr__(self): + return str(self) + + +@PublicAPI(stability="alpha") +@dataclass(frozen=True) +class ReplicaID: + """A unique identifier for a replica.""" + + unique_id: str + """A unique identifier for the replica within the deployment.""" + + deployment_id: DeploymentID + """The deployment this replica belongs to.""" + + def to_full_id_str(self) -> str: + s = f"{self.deployment_id.name}#{self.unique_id}" + if self.deployment_id.app_name: + s = f"{self.deployment_id.app_name}#{s}" + + return f"{REPLICA_ID_FULL_ID_STR_PREFIX}{s}" + + @staticmethod + def is_full_id_str(s: str) -> bool: + return s.startswith(REPLICA_ID_FULL_ID_STR_PREFIX) + + @classmethod + def from_full_id_str(cls, s: str): + assert cls.is_full_id_str(s) + + parsed = s[len(REPLICA_ID_FULL_ID_STR_PREFIX) :].split("#") + if len(parsed) == 3: + app_name, deployment_name, unique_id = parsed + elif len(parsed) == 2: + app_name = "" + deployment_name, unique_id = parsed + else: + raise ValueError( + f"Given replica ID string {s} didn't match expected pattern, " + "ensure it has either two or three fields with delimiter '#'." + ) + + return cls( + unique_id, + deployment_id=DeploymentID(name=deployment_name, app_name=app_name), + ) + + def __repr__(self) -> str: + return str(self) + + def __str__(self) -> str: + """Returns a human-readable string. + + This is used in user-facing log messages, so take care when updating it. + """ + return ( + f"Replica(" + f"id='{self.unique_id}', " + f"deployment='{self.deployment_id.name}', " + f"app='{self.deployment_id.app_name}'" + ")" + ) + + +NodeId = str +Duration = float +ApplicationName = str + + +@dataclass +class EndpointInfo: + route: str + app_is_cross_language: bool = False + + +# Keep in sync with ServeReplicaState in dashboard/client/src/type/serve.ts +class ReplicaState(str, Enum): + STARTING = "STARTING" + UPDATING = "UPDATING" + RECOVERING = "RECOVERING" + RUNNING = "RUNNING" + STOPPING = "STOPPING" + PENDING_MIGRATION = "PENDING_MIGRATION" + + +class DeploymentStatus(str, Enum): + UPDATING = "UPDATING" + HEALTHY = "HEALTHY" + UNHEALTHY = "UNHEALTHY" + DEPLOY_FAILED = "DEPLOY_FAILED" + UPSCALING = "UPSCALING" + DOWNSCALING = "DOWNSCALING" + + +class DeploymentStatusTrigger(str, Enum): + UNSPECIFIED = "UNSPECIFIED" + CONFIG_UPDATE_STARTED = "CONFIG_UPDATE_STARTED" + CONFIG_UPDATE_COMPLETED = "CONFIG_UPDATE_COMPLETED" + UPSCALE_COMPLETED = "UPSCALE_COMPLETED" + DOWNSCALE_COMPLETED = "DOWNSCALE_COMPLETED" + AUTOSCALING = "AUTOSCALING" + REPLICA_STARTUP_FAILED = "REPLICA_STARTUP_FAILED" + HEALTH_CHECK_FAILED = "HEALTH_CHECK_FAILED" + INTERNAL_ERROR = "INTERNAL_ERROR" + DELETING = "DELETING" + + +# Internal Enum used to manage deployment state machine +class DeploymentStatusInternalTrigger(str, Enum): + HEALTHY = "HEALTHY" + CONFIG_UPDATE = "CONFIG_UPDATE" + AUTOSCALE_UP = "AUTOSCALE_UP" + AUTOSCALE_DOWN = "AUTOSCALE_DOWN" + MANUALLY_INCREASE_NUM_REPLICAS = "MANUALLY_INCREASE_NUM_REPLICAS" + MANUALLY_DECREASE_NUM_REPLICAS = "MANUALLY_DECREASE_NUM_REPLICAS" + REPLICA_STARTUP_FAILED = "REPLICA_STARTUP_FAILED" + HEALTH_CHECK_FAILED = "HEALTH_CHECK_FAILED" + INTERNAL_ERROR = "INTERNAL_ERROR" + DELETE = "DELETE" + + +# List of states in ranked order. +# +# Each ranked state has the format of a tuple with either 1 or 2 items. +# If 1 item: contains a single DeploymentStatus, representing states with +# that DeploymentStatus and any DeploymentStatusTrigger. +# If 2 items: tuple contains a DeploymentStatus and a DeploymentStatusTrigger, +# representing a state with that status and status trigger. +DEPLOYMENT_STATUS_RANKING_ORDER = { + # Status ranking order is defined in a following fashion: + # 0. (Highest) State signaling a deploy failure. + (DeploymentStatus.DEPLOY_FAILED,): 0, + # 1. State signaling any non-deploy failures in the system. + (DeploymentStatus.UNHEALTHY,): 1, + # 2. States signaling the user updated the configuration. + (DeploymentStatus.UPDATING,): 2, + (DeploymentStatus.UPSCALING, DeploymentStatusTrigger.CONFIG_UPDATE_STARTED): 2, + ( + DeploymentStatus.DOWNSCALING, + DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + ): 2, + # 3. Steady state or autoscaling. + (DeploymentStatus.UPSCALING, DeploymentStatusTrigger.AUTOSCALING): 3, + (DeploymentStatus.DOWNSCALING, DeploymentStatusTrigger.AUTOSCALING): 3, + (DeploymentStatus.HEALTHY,): 3, +} + + +@dataclass(eq=True) +class DeploymentStatusInfo: + name: str + status: DeploymentStatus + status_trigger: DeploymentStatusTrigger + message: str = "" + + @property + def rank(self) -> int: + """Get priority of state based on ranking_order(). + + The ranked order indicates what the status should be of a + hierarchically "higher" resource when derived from a group of + `DeploymentStatusInfo` sub-resources. + """ + + if (self.status,) in DEPLOYMENT_STATUS_RANKING_ORDER: + return DEPLOYMENT_STATUS_RANKING_ORDER[(self.status,)] + elif (self.status, self.status_trigger) in DEPLOYMENT_STATUS_RANKING_ORDER: + return DEPLOYMENT_STATUS_RANKING_ORDER[(self.status, self.status_trigger)] + + def debug_string(self): + return json.dumps(asdict(self), indent=4) + + def _updated_copy( + self, + status: DeploymentStatus = None, + status_trigger: DeploymentStatusTrigger = None, + message: str = "", + ): + """Returns a copy of the current object with the passed in kwargs updated.""" + + return DeploymentStatusInfo( + name=self.name, + status=status if status else self.status, + status_trigger=status_trigger if status_trigger else self.status_trigger, + message=message, + ) + + def update_message(self, message: str): + return self._updated_copy(message=message) + + def handle_transition( + self, + trigger: DeploymentStatusInternalTrigger, + message: str = "", + ) -> "DeploymentStatusInfo": + """Handles a transition from the current state to the next state. + + Args: + trigger: An internal trigger that determines the state + transition. + message: The message to set in status info. + + Returns: + New instance of DeploymentStatusInfo representing the + next state to transition to. + """ + + # If there was an unexpected internal error during reconciliation, set + # status to unhealthy immediately and return + if trigger == DeploymentStatusInternalTrigger.INTERNAL_ERROR: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.INTERNAL_ERROR, + message=message, + ) + + # If deployment is being deleted, set status immediately and return + elif trigger == DeploymentStatusInternalTrigger.DELETE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.DELETING, + message=message, + ) + + # Otherwise, go through normal state machine transitions + elif self.status == DeploymentStatus.UPDATING: + # Finished updating configuration and transition to healthy + if trigger == DeploymentStatusInternalTrigger.HEALTHY: + return self._updated_copy( + status=DeploymentStatus.HEALTHY, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_COMPLETED, + message=message, + ) + + # A new configuration has been deployed before deployment + # has finished updating + elif trigger == DeploymentStatusInternalTrigger.CONFIG_UPDATE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + + # Autoscaling. + elif trigger == DeploymentStatusInternalTrigger.AUTOSCALE_UP: + return self._updated_copy( + status=DeploymentStatus.UPSCALING, + status_trigger=DeploymentStatusTrigger.AUTOSCALING, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.AUTOSCALE_DOWN: + return self._updated_copy( + status=DeploymentStatus.DOWNSCALING, + status_trigger=DeploymentStatusTrigger.AUTOSCALING, + message=message, + ) + + # Manually increasing or decreasing num replicas does not + # change the status while deployment is still updating. + elif trigger in { + DeploymentStatusInternalTrigger.MANUALLY_INCREASE_NUM_REPLICAS, + DeploymentStatusInternalTrigger.MANUALLY_DECREASE_NUM_REPLICAS, + }: + return self + + # Failures occurred while a deployment was being updated + elif trigger == DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED: + return self._updated_copy( + status=DeploymentStatus.DEPLOY_FAILED, + status_trigger=DeploymentStatusTrigger.HEALTH_CHECK_FAILED, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.REPLICA_STARTUP_FAILED: + return self._updated_copy( + status=DeploymentStatus.DEPLOY_FAILED, + status_trigger=DeploymentStatusTrigger.REPLICA_STARTUP_FAILED, + message=message, + ) + + elif self.status in {DeploymentStatus.UPSCALING, DeploymentStatus.DOWNSCALING}: + # Deployment transitions to healthy + if trigger == DeploymentStatusInternalTrigger.HEALTHY: + return self._updated_copy( + status=DeploymentStatus.HEALTHY, + status_trigger=DeploymentStatusTrigger.UPSCALE_COMPLETED + if self.status == DeploymentStatus.UPSCALING + else DeploymentStatusTrigger.DOWNSCALE_COMPLETED, + message=message, + ) + + # Configuration is updated before scaling is finished + elif trigger == DeploymentStatusInternalTrigger.CONFIG_UPDATE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + + # Upscale replicas before previous upscaling/downscaling has finished + elif ( + self.status_trigger == DeploymentStatusTrigger.AUTOSCALING + and trigger == DeploymentStatusInternalTrigger.AUTOSCALE_UP + ) or ( + self.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_STARTED + and trigger + == DeploymentStatusInternalTrigger.MANUALLY_INCREASE_NUM_REPLICAS + ): + return self._updated_copy( + status=DeploymentStatus.UPSCALING, message=message + ) + + # Downscale replicas before previous upscaling/downscaling has finished + elif ( + self.status_trigger == DeploymentStatusTrigger.AUTOSCALING + and trigger == DeploymentStatusInternalTrigger.AUTOSCALE_DOWN + ) or ( + self.status_trigger == DeploymentStatusTrigger.CONFIG_UPDATE_STARTED + and trigger + == DeploymentStatusInternalTrigger.MANUALLY_DECREASE_NUM_REPLICAS + ): + return self._updated_copy( + status=DeploymentStatus.DOWNSCALING, message=message + ) + + # Failures occurred while upscaling/downscaling + elif trigger == DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.HEALTH_CHECK_FAILED, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.REPLICA_STARTUP_FAILED: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.REPLICA_STARTUP_FAILED, + message=message, + ) + + elif self.status == DeploymentStatus.HEALTHY: + # Deployment remains healthy + if trigger == DeploymentStatusInternalTrigger.HEALTHY: + return self + + # New configuration is deployed + elif trigger == DeploymentStatusInternalTrigger.CONFIG_UPDATE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + + # Manually scaling / autoscaling num replicas + elif ( + trigger + == DeploymentStatusInternalTrigger.MANUALLY_INCREASE_NUM_REPLICAS + ): + return self._updated_copy( + status=DeploymentStatus.UPSCALING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + elif ( + trigger + == DeploymentStatusInternalTrigger.MANUALLY_DECREASE_NUM_REPLICAS + ): + return self._updated_copy( + status=DeploymentStatus.DOWNSCALING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.AUTOSCALE_UP: + return self._updated_copy( + status=DeploymentStatus.UPSCALING, + status_trigger=DeploymentStatusTrigger.AUTOSCALING, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.AUTOSCALE_DOWN: + return self._updated_copy( + status=DeploymentStatus.DOWNSCALING, + status_trigger=DeploymentStatusTrigger.AUTOSCALING, + message=message, + ) + + # Health check for one or more replicas has failed + elif trigger == DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.HEALTH_CHECK_FAILED, + message=message, + ) + + elif self.status == DeploymentStatus.UNHEALTHY: + # The deployment recovered + if trigger == DeploymentStatusInternalTrigger.HEALTHY: + return self._updated_copy( + status=DeploymentStatus.HEALTHY, + status_trigger=DeploymentStatusTrigger.UNSPECIFIED, + message=message, + ) + + # A new configuration is being deployed. + elif trigger == DeploymentStatusInternalTrigger.CONFIG_UPDATE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + + # Old failures keep getting triggered, or new failures occurred. + elif trigger == DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.HEALTH_CHECK_FAILED, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.REPLICA_STARTUP_FAILED: + return self._updated_copy( + status=DeploymentStatus.UNHEALTHY, + status_trigger=DeploymentStatusTrigger.REPLICA_STARTUP_FAILED, + message=message, + ) + + elif self.status == DeploymentStatus.DEPLOY_FAILED: + # The deployment recovered + if trigger == DeploymentStatusInternalTrigger.HEALTHY: + return self._updated_copy( + status=DeploymentStatus.HEALTHY, + status_trigger=DeploymentStatusTrigger.UNSPECIFIED, + message=message, + ) + + # A new configuration is being deployed. + elif trigger == DeploymentStatusInternalTrigger.CONFIG_UPDATE: + return self._updated_copy( + status=DeploymentStatus.UPDATING, + status_trigger=DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + message=message, + ) + + # Old failures keep getting triggered, or new failures occurred. + elif trigger == DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED: + return self._updated_copy( + status=DeploymentStatus.DEPLOY_FAILED, + status_trigger=DeploymentStatusTrigger.HEALTH_CHECK_FAILED, + message=message, + ) + elif trigger == DeploymentStatusInternalTrigger.REPLICA_STARTUP_FAILED: + return self._updated_copy( + status=DeploymentStatus.DEPLOY_FAILED, + status_trigger=DeploymentStatusTrigger.REPLICA_STARTUP_FAILED, + message=message, + ) + + # If it's any other transition, ignore it. + return self + + def to_proto(self): + return DeploymentStatusInfoProto( + name=self.name, + status=f"DEPLOYMENT_STATUS_{self.status.name}", + status_trigger=f"DEPLOYMENT_STATUS_TRIGGER_{self.status_trigger.name}", + message=self.message, + ) + + @classmethod + def from_proto(cls, proto: DeploymentStatusInfoProto): + status = DeploymentStatusProto.Name(proto.status)[len("DEPLOYMENT_STATUS_") :] + status_trigger = DeploymentStatusTriggerProto.Name(proto.status_trigger)[ + len("DEPLOYMENT_STATUS_TRIGGER_") : + ] + return cls( + name=proto.name, + status=DeploymentStatus(status), + status_trigger=DeploymentStatusTrigger(status_trigger), + message=proto.message, + ) + + +@dataclass(frozen=True) +class RunningReplicaInfo: + replica_id: ReplicaID + node_id: Optional[str] + node_ip: Optional[str] + availability_zone: Optional[str] + actor_handle: ActorHandle + max_ongoing_requests: int + is_cross_language: bool = False + multiplexed_model_ids: List[str] = field(default_factory=list) + routing_stats: Dict[str, Any] = field(default_factory=dict) + port: Optional[int] = None + + def __post_init__(self): + # Set hash value when object is constructed. + # We use _actor_id to hash the ActorHandle object + # instead of actor_handle itself to make sure + # it is consistently same actor handle between different + # object ids. + + hash_val = hash( + " ".join( + [ + self.replica_id.to_full_id_str(), + self.node_id if self.node_id else "", + str(self.actor_handle._actor_id), + str(self.max_ongoing_requests), + str(self.is_cross_language), + str(self.multiplexed_model_ids), + str(self.routing_stats), + ] + ) + ) + + # RunningReplicaInfo class set frozen=True, this is the hacky way to set + # new attribute for the class. + object.__setattr__(self, "_hash", hash_val) + + def __hash__(self): + return self._hash + + def __eq__(self, other): + return all( + [ + isinstance(other, RunningReplicaInfo), + self._hash == other._hash, + ] + ) + + +@dataclass(frozen=True) +class DeploymentTargetInfo: + is_available: bool + running_replicas: List[RunningReplicaInfo] + + +class ServeDeployMode(str, Enum): + MULTI_APP = "MULTI_APP" + + +class ServeComponentType(str, Enum): + REPLICA = "replica" + + +@dataclass +class RequestRoutingInfo: + """Information about the request routing. + + It includes deployment name (from ReplicaID), replica tag (from ReplicaID), + multiplex model ids, and routing stats. + """ + + replica_id: ReplicaID + multiplexed_model_ids: Optional[List[str]] = None + routing_stats: Optional[Dict[str, Any]] = None + + +@dataclass +class gRPCRequest: + """Sent from the GRPC proxy to replicas on both unary and streaming codepaths.""" + + user_request_proto: Any + + +class RequestProtocol(str, Enum): + UNDEFINED = "UNDEFINED" + HTTP = "HTTP" + GRPC = "gRPC" + + +class DeploymentHandleSource(str, Enum): + UNKNOWN = "UNKNOWN" + PROXY = "PROXY" + REPLICA = "REPLICA" + + +@dataclass +class RequestMetadata: + # request_id can be passed by the client and is only generated by the proxy if the + # client did not pass it in the headers. It is used for logging across different + # system. We can not guarantee the uniqueness of its value. + request_id: str + # internal_request_id is always generated by the proxy and is used for tracking + # request objects. We can assume this is always unique between requests. + internal_request_id: str + + # Method of the user callable to execute. + call_method: str = "__call__" + + # HTTP route path of the request. + route: str = "" + + # Application name. + app_name: str = "" + + # Multiplexed model ID. + multiplexed_model_id: str = "" + + # If this request expects a streaming response. + is_streaming: bool = False + + _http_method: str = "" + + # The protocol to serve this request + _request_protocol: RequestProtocol = RequestProtocol.UNDEFINED + + # Serve's gRPC context associated with this request for getting and setting metadata + grpc_context: Optional[RayServegRPCContext] = None + + _by_reference: bool = True + + @property + def is_http_request(self) -> bool: + return self._request_protocol == RequestProtocol.HTTP + + @property + def is_grpc_request(self) -> bool: + return self._request_protocol == RequestProtocol.GRPC + + +class StreamingHTTPRequest: + """Sent from the HTTP proxy to replicas on the streaming codepath.""" + + def __init__( + self, + asgi_scope: Scope, + *, + proxy_actor_name: Optional[str] = None, + receive_asgi_messages: Optional[ + Callable[[RequestMetadata], Awaitable[bytes]] + ] = None, + ): + self._asgi_scope: Scope = asgi_scope + + if proxy_actor_name is None and receive_asgi_messages is None: + raise ValueError( + "Either proxy_actor_name or receive_asgi_messages must be provided." + ) + + # If receive_asgi_messages is passed, it'll be called directly. + # If proxy_actor_name is passed, the actor will be fetched and its + # `receive_asgi_messages` method will be called. + self._proxy_actor_name: Optional[str] = proxy_actor_name + # Need to keep the actor handle cached to avoid "lost reference to actor" error. + self._cached_proxy_actor: Optional[ActorHandle] = None + self._receive_asgi_messages: Optional[ + Callable[[RequestMetadata], Awaitable[bytes]] + ] = receive_asgi_messages + + @property + def asgi_scope(self) -> Scope: + return self._asgi_scope + + @property + def receive_asgi_messages(self) -> Callable[[RequestMetadata], Awaitable[bytes]]: + if self._receive_asgi_messages is None: + self._cached_proxy_actor = ray.get_actor( + self._proxy_actor_name, namespace=SERVE_NAMESPACE + ) + self._receive_asgi_messages = ( + self._cached_proxy_actor.receive_asgi_messages.remote + ) + + return self._receive_asgi_messages + + +class TargetCapacityDirection(str, Enum): + """Determines what direction the target capacity is scaling.""" + + UP = "UP" + DOWN = "DOWN" + + +@dataclass(frozen=True) +class ReplicaQueueLengthInfo: + accepted: bool + num_ongoing_requests: int + + +@dataclass(frozen=True) +class CreatePlacementGroupRequest: + bundles: List[Dict[str, float]] + strategy: str + target_node_id: str + name: str + runtime_env: Optional[str] = None diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/config.py b/venv/lib/python3.10/site-packages/ray/serve/_private/config.py new file mode 100644 index 0000000000000000000000000000000000000000..3293f5557ee4d543a27ebec7306e2fef49c38c4d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/config.py @@ -0,0 +1,779 @@ +import inspect +import json +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union + +from google.protobuf.descriptor import FieldDescriptor +from google.protobuf.message import Message + +from ray import cloudpickle +from ray._common.pydantic_compat import ( + BaseModel, + Field, + NonNegativeFloat, + NonNegativeInt, + PositiveFloat, + PositiveInt, + validator, +) +from ray._common.utils import resources_from_ray_options +from ray._private import ray_option_utils +from ray._private.serialization import pickle_dumps +from ray.serve._private.constants import ( + DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_S, + DEFAULT_GRACEFUL_SHUTDOWN_WAIT_LOOP_S, + DEFAULT_HEALTH_CHECK_PERIOD_S, + DEFAULT_HEALTH_CHECK_TIMEOUT_S, + DEFAULT_MAX_ONGOING_REQUESTS, + MAX_REPLICAS_PER_NODE_MAX_VALUE, +) +from ray.serve._private.utils import DEFAULT, DeploymentOptionUpdateType +from ray.serve.config import AutoscalingConfig, RequestRouterConfig +from ray.serve.generated.serve_pb2 import ( + AutoscalingConfig as AutoscalingConfigProto, + DeploymentConfig as DeploymentConfigProto, + DeploymentLanguage, + EncodingType as EncodingTypeProto, + LoggingConfig as LoggingConfigProto, + ReplicaConfig as ReplicaConfigProto, + RequestRouterConfig as RequestRouterConfigProto, +) +from ray.util.placement_group import validate_placement_group + + +def _needs_pickle(deployment_language: DeploymentLanguage, is_cross_language: bool): + """From Serve client API's perspective, decide whether pickling is needed.""" + if deployment_language == DeploymentLanguage.PYTHON and not is_cross_language: + # Python client deploying Python replicas. + return True + elif deployment_language == DeploymentLanguage.JAVA and is_cross_language: + # Python client deploying Java replicas, + # using xlang serialization via cloudpickle. + return True + else: + return False + + +def _proto_to_dict(proto: Message) -> Dict: + """Recursively convert a protobuf into a Python dictionary. + + This is an alternative to protobuf's `MessageToDict`. Unlike + `MessageToDict`, this function doesn't add an extra base64 + encoding to bytes when constructing a json response. + """ + data = {} + # Fill data with non-empty fields. + for field, value in proto.ListFields(): + # Handle repeated fields + if field.label == FieldDescriptor.LABEL_REPEATED: + # if we dont do this block the repeated field will be a list of + # `google.protobuf.internal.containers.RepeatedScalarFieldContainer + # Explicitly convert to list + if field.type == FieldDescriptor.TYPE_MESSAGE: + data[field.name] = [ + _proto_to_dict(v) for v in value + ] # Convert each item + else: + data[field.name] = list(value) # Convert to list directly + # Recursively call if the field is another protobuf. + elif field.type == FieldDescriptor.TYPE_MESSAGE: + data[field.name] = _proto_to_dict(value) + else: + data[field.name] = value + + # Fill data default values. + for field in proto.DESCRIPTOR.fields: + if ( + field.name not in data # skip the fields that are already set + and field.type != FieldDescriptor.TYPE_MESSAGE # skip nested messages + and not field.containing_oneof # skip optional fields + ): + data[field.name] = field.default_value + return data + + +class DeploymentConfig(BaseModel): + """Internal datastructure wrapping config options for a deployment. + + Args: + num_replicas: The number of processes to start up that + handles requests to this deployment. Defaults to 1. + max_ongoing_requests: The maximum number of queries + that is sent to a replica of this deployment without receiving + a response. Defaults to 5. + max_queued_requests: Maximum number of requests to this deployment that will be + queued at each *caller* (proxy or DeploymentHandle). Once this limit is + reached, subsequent requests will raise a BackPressureError (for handles) or + return an HTTP 503 status code (for HTTP requests). Defaults to -1 (no + limit). + user_config: Arguments to pass to the reconfigure + method of the deployment. The reconfigure method is called if + user_config is not None. Must be JSON-serializable. + graceful_shutdown_wait_loop_s: Duration + that deployment replicas wait until there is no more work to + be done before shutting down. + graceful_shutdown_timeout_s: Controller waits for this duration + to forcefully kill the replica for shutdown. + health_check_period_s: Frequency at which the controller health + checks replicas. + health_check_timeout_s: Timeout that the controller waits for a + response from the replica's health check before marking it + unhealthy. + autoscaling_config: Autoscaling configuration. + logging_config: Configuration for deployment logs. + user_configured_option_names: The names of options manually + configured by the user. + request_router_config: Configuration for deployment request router. + """ + + num_replicas: Optional[NonNegativeInt] = Field( + default=1, update_type=DeploymentOptionUpdateType.LightWeight + ) + max_ongoing_requests: PositiveInt = Field( + default=DEFAULT_MAX_ONGOING_REQUESTS, + update_type=DeploymentOptionUpdateType.NeedsActorReconfigure, + ) + max_queued_requests: int = Field( + default=-1, + update_type=DeploymentOptionUpdateType.LightWeight, + ) + user_config: Any = Field( + default=None, update_type=DeploymentOptionUpdateType.NeedsActorReconfigure + ) + + graceful_shutdown_timeout_s: NonNegativeFloat = Field( + default=DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_S, + update_type=DeploymentOptionUpdateType.NeedsReconfigure, + ) + graceful_shutdown_wait_loop_s: NonNegativeFloat = Field( + default=DEFAULT_GRACEFUL_SHUTDOWN_WAIT_LOOP_S, + update_type=DeploymentOptionUpdateType.NeedsActorReconfigure, + ) + + health_check_period_s: PositiveFloat = Field( + default=DEFAULT_HEALTH_CHECK_PERIOD_S, + update_type=DeploymentOptionUpdateType.NeedsReconfigure, + ) + health_check_timeout_s: PositiveFloat = Field( + default=DEFAULT_HEALTH_CHECK_TIMEOUT_S, + update_type=DeploymentOptionUpdateType.NeedsReconfigure, + ) + + autoscaling_config: Optional[AutoscalingConfig] = Field( + default=None, update_type=DeploymentOptionUpdateType.NeedsActorReconfigure + ) + + request_router_config: RequestRouterConfig = Field( + default=RequestRouterConfig(), + update_type=DeploymentOptionUpdateType.NeedsActorReconfigure, + ) + + # This flag is used to let replica know they are deployed from + # a different language. + is_cross_language: bool = False + + # This flag is used to let controller know which language does + # the deployment use. + deployment_language: Any = DeploymentLanguage.PYTHON + + version: Optional[str] = Field( + default=None, + update_type=DeploymentOptionUpdateType.HeavyWeight, + ) + + logging_config: Optional[dict] = Field( + default=None, + update_type=DeploymentOptionUpdateType.NeedsActorReconfigure, + ) + + # Contains the names of deployment options manually set by the user + user_configured_option_names: Set[str] = set() + + class Config: + validate_assignment = True + arbitrary_types_allowed = True + + @validator("user_config", always=True) + def user_config_json_serializable(cls, v): + if isinstance(v, bytes): + return v + if v is not None: + try: + json.dumps(v) + except TypeError as e: + raise ValueError(f"user_config is not JSON-serializable: {str(e)}.") + + return v + + @validator("logging_config", always=True) + def logging_config_valid(cls, v): + if v is None: + return v + if not isinstance(v, dict): + raise TypeError( + f"Got invalid type '{type(v)}' for logging_config. " + "Expected a dictionary." + ) + # Handle default value + from ray.serve.schema import LoggingConfig + + v = LoggingConfig(**v).dict() + return v + + @validator("max_queued_requests", always=True) + def validate_max_queued_requests(cls, v): + if not isinstance(v, int): + raise TypeError("max_queued_requests must be an integer.") + + if v < 1 and v != -1: + raise ValueError( + "max_queued_requests must be -1 (no limit) or a positive integer." + ) + + return v + + def needs_pickle(self): + return _needs_pickle(self.deployment_language, self.is_cross_language) + + def to_proto(self): + data = self.dict() + if data.get("user_config") is not None: + if self.needs_pickle(): + data["user_config"] = cloudpickle.dumps(data["user_config"]) + if data.get("autoscaling_config"): + data["autoscaling_config"] = AutoscalingConfigProto( + **data["autoscaling_config"] + ) + if data.get("request_router_config"): + router_kwargs = data["request_router_config"].get("request_router_kwargs") + if router_kwargs is not None: + if not router_kwargs: + data["request_router_config"]["request_router_kwargs"] = b"" + elif self.needs_pickle(): + # Protobuf requires bytes, so we need to pickle + data["request_router_config"][ + "request_router_kwargs" + ] = cloudpickle.dumps(router_kwargs) + else: + raise ValueError( + "Non-empty request_router_kwargs not supported" + f"for cross-language deployments. Got: {router_kwargs}" + ) + data["request_router_config"] = RequestRouterConfigProto( + **data["request_router_config"] + ) + if data.get("logging_config"): + if "encoding" in data["logging_config"]: + data["logging_config"]["encoding"] = EncodingTypeProto.Value( + data["logging_config"]["encoding"] + ) + data["logging_config"] = LoggingConfigProto(**data["logging_config"]) + data["user_configured_option_names"] = list( + data["user_configured_option_names"] + ) + return DeploymentConfigProto(**data) + + def to_proto_bytes(self): + return self.to_proto().SerializeToString() + + @classmethod + def from_proto(cls, proto: DeploymentConfigProto): + data = _proto_to_dict(proto) + deployment_language = ( + data["deployment_language"] + if "deployment_language" in data + else DeploymentLanguage.PYTHON + ) + is_cross_language = ( + data["is_cross_language"] if "is_cross_language" in data else False + ) + needs_pickle = _needs_pickle(deployment_language, is_cross_language) + if "user_config" in data: + if data["user_config"] != b"": + if needs_pickle: + data["user_config"] = cloudpickle.loads(proto.user_config) + else: + data["user_config"] = proto.user_config + else: + data["user_config"] = None + if "request_router_config" in data: + if "request_router_kwargs" in data["request_router_config"]: + request_router_kwargs = data["request_router_config"][ + "request_router_kwargs" + ] + if request_router_kwargs != b"": + if needs_pickle: + data["request_router_config"][ + "request_router_kwargs" + ] = cloudpickle.loads( + proto.request_router_config.request_router_kwargs + ) + else: + data["request_router_config"][ + "request_router_kwargs" + ] = proto.request_router_config.request_router_kwargs + else: + data["request_router_config"]["request_router_kwargs"] = {} + + data["request_router_config"] = RequestRouterConfig( + **data["request_router_config"] + ) + if "autoscaling_config" in data: + if not data["autoscaling_config"].get("upscale_smoothing_factor"): + data["autoscaling_config"]["upscale_smoothing_factor"] = None + if not data["autoscaling_config"].get("downscale_smoothing_factor"): + data["autoscaling_config"]["downscale_smoothing_factor"] = None + if not data["autoscaling_config"].get("upscaling_factor"): + data["autoscaling_config"]["upscaling_factor"] = None + if not data["autoscaling_config"].get("downscaling_factor"): + data["autoscaling_config"]["downscaling_factor"] = None + if not data["autoscaling_config"].get("target_ongoing_requests"): + data["autoscaling_config"]["target_ongoing_requests"] = None + data["autoscaling_config"] = AutoscalingConfig(**data["autoscaling_config"]) + if "version" in data: + if data["version"] == "": + data["version"] = None + if "user_configured_option_names" in data: + data["user_configured_option_names"] = set( + data["user_configured_option_names"] + ) + if "logging_config" in data: + if "encoding" in data["logging_config"]: + data["logging_config"]["encoding"] = EncodingTypeProto.Name( + data["logging_config"]["encoding"] + ) + + return cls(**data) + + @classmethod + def from_proto_bytes(cls, proto_bytes: bytes): + proto = DeploymentConfigProto.FromString(proto_bytes) + return cls.from_proto(proto) + + @classmethod + def from_default(cls, **kwargs): + """Creates a default DeploymentConfig and overrides it with kwargs. + + Ignores any kwargs set to DEFAULT.VALUE. + + Raises: + TypeError: when a keyword that's not an argument to the class is + passed in. + """ + + config = cls() + valid_config_options = set(config.dict().keys()) + + # Friendly error if a non-DeploymentConfig kwarg was passed in + for key, val in kwargs.items(): + if key not in valid_config_options: + raise TypeError( + f'Got invalid Deployment config option "{key}" ' + f"(with value {val}) as keyword argument. All Deployment " + "config options must come from this list: " + f"{list(valid_config_options)}." + ) + + kwargs = {key: val for key, val in kwargs.items() if val != DEFAULT.VALUE} + + for key, val in kwargs.items(): + config.__setattr__(key, val) + + return config + + +def handle_num_replicas_auto( + max_ongoing_requests: Union[int, DEFAULT], + autoscaling_config: Optional[Union[Dict, AutoscalingConfig, DEFAULT]], +): + """Return modified `max_ongoing_requests` and `autoscaling_config` + for when num_replicas="auto". + + If `autoscaling_config` is unspecified, returns the modified value + AutoscalingConfig.default(). + If it is specified, the specified fields in `autoscaling_config` + override that of AutoscalingConfig.default(). + """ + + if autoscaling_config in [DEFAULT.VALUE, None]: + # If autoscaling config wasn't specified, use default + # configuration + autoscaling_config = AutoscalingConfig.default() + else: + # If autoscaling config was specified, values specified in + # autoscaling config overrides the default configuration + default_config = AutoscalingConfig.default().dict(exclude_unset=True) + autoscaling_config = ( + autoscaling_config + if isinstance(autoscaling_config, dict) + else autoscaling_config.dict(exclude_unset=True) + ) + default_config.update(autoscaling_config) + autoscaling_config = AutoscalingConfig(**default_config) + + return max_ongoing_requests, autoscaling_config + + +class ReplicaConfig: + """Internal datastructure wrapping config options for a deployment's replicas. + + Provides five main properties (see property docstrings for more info): + deployment_def: the code, or a reference to the code, that this + replica should run. + init_args: the deployment_def's init_args. + init_kwargs: the deployment_def's init_kwargs. + ray_actor_options: the Ray actor options to pass into the replica's + actor. + resource_dict: contains info on this replica's actor's resource needs. + + Offers a serialized equivalent (e.g. serialized_deployment_def) for + deployment_def, init_args, and init_kwargs. Deserializes these properties + when they're first accessed, if they were not passed in directly through + create(). + + Use the classmethod create() to make a ReplicaConfig with the deserialized + properties. + + Note: overwriting or setting any property after the ReplicaConfig has been + constructed is currently undefined behavior. The config's fields should not + be modified externally after it is created. + """ + + def __init__( + self, + deployment_def_name: str, + serialized_deployment_def: bytes, + serialized_init_args: bytes, + serialized_init_kwargs: bytes, + ray_actor_options: Dict, + placement_group_bundles: Optional[List[Dict[str, float]]] = None, + placement_group_strategy: Optional[str] = None, + max_replicas_per_node: Optional[int] = None, + needs_pickle: bool = True, + ): + """Construct a ReplicaConfig with serialized properties. + + All parameters are required. See classmethod create() for defaults. + """ + self.deployment_def_name = deployment_def_name + + # Store serialized versions of code properties. + self.serialized_deployment_def = serialized_deployment_def + self.serialized_init_args = serialized_init_args + self.serialized_init_kwargs = serialized_init_kwargs + + # Deserialize properties when first accessed. See @property methods. + self._deployment_def = None + self._init_args = None + self._init_kwargs = None + + # Configure ray_actor_options. These are the Ray options ultimately + # passed into the replica's actor when it's created. + self.ray_actor_options = ray_actor_options + + self.placement_group_bundles = placement_group_bundles + self.placement_group_strategy = placement_group_strategy + + self.max_replicas_per_node = max_replicas_per_node + + self._validate() + + # Create resource_dict. This contains info about the replica's resource + # needs. It does NOT set the replica's resource usage. That's done by + # the ray_actor_options. + self.resource_dict = resources_from_ray_options(self.ray_actor_options) + self.needs_pickle = needs_pickle + + def _validate(self): + self._validate_ray_actor_options() + self._validate_placement_group_options() + self._validate_max_replicas_per_node() + + if ( + self.max_replicas_per_node is not None + and self.placement_group_bundles is not None + ): + raise ValueError( + "Setting max_replicas_per_node is not allowed when " + "placement_group_bundles is provided." + ) + + def update( + self, + ray_actor_options: dict, + placement_group_bundles: Optional[List[Dict[str, float]]] = None, + placement_group_strategy: Optional[str] = None, + max_replicas_per_node: Optional[int] = None, + ): + self.ray_actor_options = ray_actor_options + + self.placement_group_bundles = placement_group_bundles + self.placement_group_strategy = placement_group_strategy + + self.max_replicas_per_node = max_replicas_per_node + + self._validate() + + self.resource_dict = resources_from_ray_options(self.ray_actor_options) + + @classmethod + def create( + cls, + deployment_def: Union[Callable, str], + init_args: Optional[Tuple[Any]] = None, + init_kwargs: Optional[Dict[Any, Any]] = None, + ray_actor_options: Optional[Dict] = None, + placement_group_bundles: Optional[List[Dict[str, float]]] = None, + placement_group_strategy: Optional[str] = None, + max_replicas_per_node: Optional[int] = None, + deployment_def_name: Optional[str] = None, + ): + """Create a ReplicaConfig from deserialized parameters.""" + + if not callable(deployment_def) and not isinstance(deployment_def, str): + raise TypeError("@serve.deployment must be called on a class or function.") + + if not (init_args is None or isinstance(init_args, (tuple, list))): + raise TypeError("init_args must be a tuple.") + + if not (init_kwargs is None or isinstance(init_kwargs, dict)): + raise TypeError("init_kwargs must be a dict.") + + if inspect.isfunction(deployment_def): + if init_args: + raise ValueError("init_args not supported for function deployments.") + elif init_kwargs: + raise ValueError("init_kwargs not supported for function deployments.") + + if not isinstance(deployment_def, (Callable, str)): + raise TypeError( + f'Got invalid type "{type(deployment_def)}" for ' + "deployment_def. Expected deployment_def to be a " + "class, function, or string." + ) + # Set defaults + if init_args is None: + init_args = () + if init_kwargs is None: + init_kwargs = {} + if ray_actor_options is None: + ray_actor_options = {} + if deployment_def_name is None: + if isinstance(deployment_def, str): + deployment_def_name = deployment_def + else: + deployment_def_name = deployment_def.__name__ + + config = cls( + deployment_def_name, + pickle_dumps( + deployment_def, + f"Could not serialize the deployment {repr(deployment_def)}", + ), + pickle_dumps(init_args, "Could not serialize the deployment init args"), + pickle_dumps(init_kwargs, "Could not serialize the deployment init kwargs"), + ray_actor_options, + placement_group_bundles, + placement_group_strategy, + max_replicas_per_node, + ) + + config._deployment_def = deployment_def + config._init_args = init_args + config._init_kwargs = init_kwargs + + return config + + def _validate_ray_actor_options(self): + if not isinstance(self.ray_actor_options, dict): + raise TypeError( + f'Got invalid type "{type(self.ray_actor_options)}" for ' + "ray_actor_options. Expected a dictionary." + ) + # Please keep this in sync with the docstring for the ray_actor_options + # kwarg in api.py. + allowed_ray_actor_options = { + # Resource options + "accelerator_type", + "memory", + "num_cpus", + "num_gpus", + "resources", + # Other options + "runtime_env", + } + + for option in self.ray_actor_options: + if option not in allowed_ray_actor_options: + raise ValueError( + f"Specifying '{option}' in ray_actor_options is not allowed. " + f"Allowed options: {allowed_ray_actor_options}" + ) + ray_option_utils.validate_actor_options(self.ray_actor_options, in_options=True) + + # Set Serve replica defaults + if self.ray_actor_options.get("num_cpus") is None: + self.ray_actor_options["num_cpus"] = 1 + + def _validate_max_replicas_per_node(self) -> None: + if self.max_replicas_per_node is None: + return + if not isinstance(self.max_replicas_per_node, int): + raise TypeError( + f"Get invalid type '{type(self.max_replicas_per_node)}' for " + "max_replicas_per_node. Expected None or an integer " + f"in the range of [1, {MAX_REPLICAS_PER_NODE_MAX_VALUE}]." + ) + if ( + self.max_replicas_per_node < 1 + or self.max_replicas_per_node > MAX_REPLICAS_PER_NODE_MAX_VALUE + ): + raise ValueError( + f"Invalid max_replicas_per_node {self.max_replicas_per_node}. " + "Valid values are None or an integer " + f"in the range of [1, {MAX_REPLICAS_PER_NODE_MAX_VALUE}]." + ) + + def _validate_placement_group_options(self) -> None: + if self.placement_group_strategy is not None: + if self.placement_group_bundles is None: + raise ValueError( + "If `placement_group_strategy` is provided, " + "`placement_group_bundles` must also be provided." + ) + + if self.placement_group_bundles is not None: + validate_placement_group( + bundles=self.placement_group_bundles, + strategy=self.placement_group_strategy or "PACK", + lifetime="detached", + ) + + resource_error_prefix = ( + "When using `placement_group_bundles`, the replica actor " + "will be placed in the first bundle, so the resource " + "requirements for the actor must be a subset of the first " + "bundle." + ) + + first_bundle = self.placement_group_bundles[0] + + # Validate that the replica actor fits in the first bundle. + bundle_cpu = first_bundle.get("CPU", 0) + replica_actor_num_cpus = self.ray_actor_options.get("num_cpus", 0) + if bundle_cpu < replica_actor_num_cpus: + raise ValueError( + f"{resource_error_prefix} `num_cpus` for the actor is " + f"{replica_actor_num_cpus}, but the bundle only has " + f"{bundle_cpu} `CPU` specified." + ) + + bundle_gpu = first_bundle.get("GPU", 0) + replica_actor_num_gpus = self.ray_actor_options.get("num_gpus", 0) + if bundle_gpu < replica_actor_num_gpus: + raise ValueError( + f"{resource_error_prefix} `num_gpus` for the actor is " + f"{replica_actor_num_gpus}, but the bundle only has " + f"{bundle_gpu} `GPU` specified." + ) + + replica_actor_resources = self.ray_actor_options.get("resources", {}) + for actor_resource, actor_value in replica_actor_resources.items(): + bundle_value = first_bundle.get(actor_resource, 0) + if bundle_value < actor_value: + raise ValueError( + f"{resource_error_prefix} `{actor_resource}` requirement " + f"for the actor is {actor_value}, but the bundle only " + f"has {bundle_value} `{actor_resource}` specified." + ) + + @property + def deployment_def(self) -> Union[Callable, str]: + """The code, or a reference to the code, that this replica runs. + + For Python replicas, this can be one of the following: + - Function (Callable) + - Class (Callable) + - Import path (str) + + For Java replicas, this can be one of the following: + - Class path (str) + """ + if self._deployment_def is None: + if self.needs_pickle: + self._deployment_def = cloudpickle.loads(self.serialized_deployment_def) + else: + self._deployment_def = self.serialized_deployment_def.decode( + encoding="utf-8" + ) + + return self._deployment_def + + @property + def init_args(self) -> Optional[Union[Tuple[Any], bytes]]: + """The init_args for a Python class. + + This property is only meaningful if deployment_def is a Python class. + Otherwise, it is None. + """ + if self._init_args is None: + if self.needs_pickle: + self._init_args = cloudpickle.loads(self.serialized_init_args) + else: + self._init_args = self.serialized_init_args + + return self._init_args + + @property + def init_kwargs(self) -> Optional[Tuple[Any]]: + """The init_kwargs for a Python class. + + This property is only meaningful if deployment_def is a Python class. + Otherwise, it is None. + """ + + if self._init_kwargs is None: + self._init_kwargs = cloudpickle.loads(self.serialized_init_kwargs) + + return self._init_kwargs + + @classmethod + def from_proto(cls, proto: ReplicaConfigProto, needs_pickle: bool = True): + return ReplicaConfig( + proto.deployment_def_name, + proto.deployment_def, + proto.init_args if proto.init_args != b"" else None, + proto.init_kwargs if proto.init_kwargs != b"" else None, + json.loads(proto.ray_actor_options), + json.loads(proto.placement_group_bundles) + if proto.placement_group_bundles + else None, + proto.placement_group_strategy + if proto.placement_group_strategy != "" + else None, + proto.max_replicas_per_node if proto.max_replicas_per_node else None, + needs_pickle, + ) + + @classmethod + def from_proto_bytes(cls, proto_bytes: bytes, needs_pickle: bool = True): + proto = ReplicaConfigProto.FromString(proto_bytes) + return cls.from_proto(proto, needs_pickle) + + def to_proto(self): + return ReplicaConfigProto( + deployment_def_name=self.deployment_def_name, + deployment_def=self.serialized_deployment_def, + init_args=self.serialized_init_args, + init_kwargs=self.serialized_init_kwargs, + ray_actor_options=json.dumps(self.ray_actor_options), + placement_group_bundles=json.dumps(self.placement_group_bundles) + if self.placement_group_bundles is not None + else "", + placement_group_strategy=self.placement_group_strategy, + max_replicas_per_node=self.max_replicas_per_node + if self.max_replicas_per_node is not None + else 0, + ) + + def to_proto_bytes(self): + return self.to_proto().SerializeToString() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/constants.py b/venv/lib/python3.10/site-packages/ray/serve/_private/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..8edcc38e04f34d780d17cfb8354544cdc11f9546 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/constants.py @@ -0,0 +1,472 @@ +import os +from typing import List + +#: Logger used by serve components +SERVE_LOGGER_NAME = "ray.serve" + +#: Actor name used to register controller +SERVE_CONTROLLER_NAME = "SERVE_CONTROLLER_ACTOR" + +#: Actor name used to register HTTP proxy actor +SERVE_PROXY_NAME = "SERVE_PROXY_ACTOR" + +#: Ray namespace used for all Serve actors +SERVE_NAMESPACE = "serve" + +#: HTTP Host +DEFAULT_HTTP_HOST = os.environ.get("RAY_SERVE_DEFAULT_HTTP_HOST", "127.0.0.1") + +#: HTTP Port +DEFAULT_HTTP_PORT = int(os.environ.get("RAY_SERVE_DEFAULT_HTTP_PORT", 8000)) + +#: Uvicorn timeout_keep_alive Config +DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S = 90 + +#: gRPC Port +DEFAULT_GRPC_PORT = int(os.environ.get("RAY_SERVE_DEFAULT_GRPC_PORT", 9000)) + +#: Default Serve application name +SERVE_DEFAULT_APP_NAME = "default" + +#: Max concurrency +ASYNC_CONCURRENCY = int(1e6) + +# How long to sleep between control loop cycles on the controller. +CONTROL_LOOP_INTERVAL_S = float(os.getenv("RAY_SERVE_CONTROL_LOOP_INTERVAL_S", 0.1)) +assert CONTROL_LOOP_INTERVAL_S >= 0, ( + f"Got unexpected value {CONTROL_LOOP_INTERVAL_S} for " + "RAY_SERVE_CONTROL_LOOP_INTERVAL_S environment variable. " + "RAY_SERVE_CONTROL_LOOP_INTERVAL_S cannot be negative." +) + +#: Max time to wait for HTTP proxy in `serve.start()`. +HTTP_PROXY_TIMEOUT = 60 + +#: Max retry count for allowing failures in replica constructor. +#: If no replicas at target version is running by the time we're at +#: max construtor retry count, deploy() is considered failed. +#: By default we set threshold as min(num_replicas * 3, this value) +MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT = int( + os.environ.get("MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT", "20") +) + +# Max retry on deployment constructor is +# min(num_replicas * MAX_PER_REPLICA_RETRY_COUNT, MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT) +MAX_PER_REPLICA_RETRY_COUNT = int(os.environ.get("MAX_PER_REPLICA_RETRY_COUNT", "3")) + + +# If you are wondering why we are using histogram buckets, please refer to +# https://prometheus.io/docs/practices/histograms/ +# short answer is that its cheaper to calculate percentiles on the histogram +# than to calculate them on raw data, both in terms of time and space. + +#: Default histogram buckets for latency tracker. +DEFAULT_LATENCY_BUCKET_MS = [ + 1, + 2, + 5, + 10, + 20, + 50, + 100, + 200, + 300, + 400, + 500, + 1000, + 2000, + # 5 seconds + 5000, + # 10 seconds + 10000, + # 60 seconds + 60000, + # 2min + 120000, + # 5 min + 300000, + # 10 min + 600000, +] + + +def parse_latency_buckets(bucket_str: str, default_buckets: list) -> list: + if bucket_str.strip() == "": + return default_buckets + try: + # Convert string to list of floats + buckets = [float(x.strip()) for x in bucket_str.split(",")] + if not buckets: + raise ValueError("Empty bucket list") + if any(x <= 0 for x in buckets): + raise ValueError("Bucket values must be positive") + if sorted(set(buckets)) != buckets: + raise ValueError("Bucket values must be in strictly ascending order") + return buckets + except Exception as e: + raise ValueError( + f"Invalid format for {bucket_str}. " + f"Expected comma-separated positive numbers in ascending order. Error: {str(e)}" + ) + + +# Example usage: +# RAY_SERVE_REQUEST_LATENCY_BUCKET_MS="1,2,3,4" +# RAY_SERVE_MODEL_LOAD_LATENCY_BUCKET_MS="1,2,3,4" +#: Histogram buckets for request latency. +REQUEST_LATENCY_BUCKETS_MS = parse_latency_buckets( + os.getenv("REQUEST_LATENCY_BUCKETS_MS", ""), DEFAULT_LATENCY_BUCKET_MS +) +#: Histogram buckets for model load/unload latency. +MODEL_LOAD_LATENCY_BUCKETS_MS = parse_latency_buckets( + os.getenv("MODEL_LOAD_LATENCY_BUCKETS_MS", ""), DEFAULT_LATENCY_BUCKET_MS +) + +#: Name of deployment health check method implemented by user. +HEALTH_CHECK_METHOD = "check_health" + +#: Name of deployment reconfiguration method implemented by user. +RECONFIGURE_METHOD = "reconfigure" + +SERVE_ROOT_URL_ENV_KEY = "RAY_SERVE_ROOT_URL" + +#: Limit the number of cached handles because each handle has long poll +#: overhead. See https://github.com/ray-project/ray/issues/18980 +MAX_CACHED_HANDLES = int(os.getenv("MAX_CACHED_HANDLES", 100)) +assert MAX_CACHED_HANDLES > 0, ( + f"Got unexpected value {MAX_CACHED_HANDLES} for " + "MAX_CACHED_HANDLES environment variable. " + "MAX_CACHED_HANDLES must be positive." +) + +#: Because ServeController will accept one long poll request per handle, its +#: concurrency needs to scale as O(num_handles) +CONTROLLER_MAX_CONCURRENCY = int(os.getenv("CONTROLLER_MAX_CONCURRENCY", 15_000)) +assert CONTROLLER_MAX_CONCURRENCY > 0, ( + f"Got unexpected value {CONTROLLER_MAX_CONCURRENCY} for " + "CONTROLLER_MAX_CONCURRENCY environment variable. " + "CONTROLLER_MAX_CONCURRENCY must be positive." +) + +DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_S = 20 +DEFAULT_GRACEFUL_SHUTDOWN_WAIT_LOOP_S = 2 +DEFAULT_HEALTH_CHECK_PERIOD_S = 10 +DEFAULT_HEALTH_CHECK_TIMEOUT_S = 30 +DEFAULT_MAX_ONGOING_REQUESTS = 5 +DEFAULT_TARGET_ONGOING_REQUESTS = 2 + +# HTTP Proxy health check configs +PROXY_HEALTH_CHECK_TIMEOUT_S = ( + float(os.environ.get("RAY_SERVE_PROXY_HEALTH_CHECK_TIMEOUT_S", "10")) or 10 +) +PROXY_HEALTH_CHECK_PERIOD_S = ( + float(os.environ.get("RAY_SERVE_PROXY_HEALTH_CHECK_PERIOD_S", "10")) or 10 +) +PROXY_READY_CHECK_TIMEOUT_S = ( + float(os.environ.get("RAY_SERVE_PROXY_READY_CHECK_TIMEOUT_S", "5")) or 5 +) + +# Number of times in a row that a HTTP proxy must fail the health check before +# being marked unhealthy. +PROXY_HEALTH_CHECK_UNHEALTHY_THRESHOLD = 3 + +# The minimum drain period for a HTTP proxy. +PROXY_MIN_DRAINING_PERIOD_S = ( + float(os.environ.get("RAY_SERVE_PROXY_MIN_DRAINING_PERIOD_S", "30")) or 30 +) +# The time in seconds that the http proxy state waits before +# rechecking whether the proxy actor is drained or not. +PROXY_DRAIN_CHECK_PERIOD_S = 5 + +#: Number of times in a row that a replica must fail the health check before +#: being marked unhealthy. +REPLICA_HEALTH_CHECK_UNHEALTHY_THRESHOLD = 3 + +# The time in seconds that the Serve client waits before rechecking deployment state +CLIENT_POLLING_INTERVAL_S: float = 1 + +# The time in seconds that the Serve client waits before checking if +# deployment has been created +CLIENT_CHECK_CREATION_POLLING_INTERVAL_S: float = 0.1 + +# Handle metric push interval. (This interval will affect the cold start time period) +HANDLE_METRIC_PUSH_INTERVAL_S = float( + os.environ.get("RAY_SERVE_HANDLE_METRIC_PUSH_INTERVAL_S", "10") +) + +# Timeout for GCS internal KV service +RAY_SERVE_KV_TIMEOUT_S = float(os.environ.get("RAY_SERVE_KV_TIMEOUT_S", "0")) or None + +# Timeout for GCS RPC request +RAY_GCS_RPC_TIMEOUT_S = 3.0 + +# Maximum duration to wait until broadcasting a long poll update if there are +# still replicas in the RECOVERING state. +RECOVERING_LONG_POLL_BROADCAST_TIMEOUT_S = 10.0 + +# Minimum duration to wait until broadcasting model IDs. +PUSH_MULTIPLEXED_MODEL_IDS_INTERVAL_S = 0.1 + + +# Deprecation message for V1 migrations. +MIGRATION_MESSAGE = ( + "See https://docs.ray.io/en/latest/serve/index.html for more information." +) + +# Environment variable name for to specify the encoding of the log messages +RAY_SERVE_LOG_ENCODING = os.environ.get("RAY_SERVE_LOG_ENCODING", "TEXT") + +# Jsonify the log messages. This constant is deprecated and will be removed in the +# future. Use RAY_SERVE_LOG_ENCODING or 'LoggingConfig' to enable json format. +RAY_SERVE_ENABLE_JSON_LOGGING = os.environ.get("RAY_SERVE_ENABLE_JSON_LOGGING") == "1" + +# Setting RAY_SERVE_LOG_TO_STDERR=0 will disable logging to the stdout and stderr. +# Also, redirect them to serve's log files. +RAY_SERVE_LOG_TO_STDERR = os.environ.get("RAY_SERVE_LOG_TO_STDERR", "1") == "1" + +# Logging format attributes +SERVE_LOG_REQUEST_ID = "request_id" +SERVE_LOG_ROUTE = "route" +SERVE_LOG_APPLICATION = "application" +SERVE_LOG_DEPLOYMENT = "deployment" +SERVE_LOG_REPLICA = "replica" +SERVE_LOG_COMPONENT = "component_name" +SERVE_LOG_COMPONENT_ID = "component_id" +SERVE_LOG_MESSAGE = "message" +# This is a reserved for python logging module attribute, it should not be changed. +SERVE_LOG_LEVEL_NAME = "levelname" +SERVE_LOG_TIME = "asctime" + +# Logging format with record key to format string dict +SERVE_LOG_RECORD_FORMAT = { + SERVE_LOG_REQUEST_ID: "%(request_id)s", + SERVE_LOG_APPLICATION: "%(application)s", + SERVE_LOG_MESSAGE: "-- %(message)s", + SERVE_LOG_LEVEL_NAME: "%(levelname)s", + SERVE_LOG_TIME: "%(asctime)s", +} + +# There are some attributes that we only use internally or don't provide values to the +# users. Adding to this set will remove them from structured logs. +SERVE_LOG_UNWANTED_ATTRS = { + "serve_access_log", + "task_id", + "job_id", +} + +RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S = int( + os.environ.get("RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S", 0) +) + +RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S = ( + float(os.environ.get("RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S", 0)) + or float(os.environ.get("SERVE_REQUEST_PROCESSING_TIMEOUT_S", 0)) + or None +) + +SERVE_LOG_EXTRA_FIELDS = "ray_serve_extra_fields" + +# Serve HTTP request header key for routing requests. +SERVE_MULTIPLEXED_MODEL_ID = "serve_multiplexed_model_id" + +# HTTP request ID +SERVE_HTTP_REQUEST_ID_HEADER = "x-request-id" + +# Feature flag to turn on node locality routing for proxies. On by default. +RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING = ( + os.environ.get("RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING", "1") == "1" +) + +# Feature flag to turn on AZ locality routing for proxies. On by default. +RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING = ( + os.environ.get("RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING", "1") == "1" +) + +# Serve HTTP proxy callback import path. +RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH = os.environ.get( + "RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH", None +) +# Serve controller callback import path. +RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH = os.environ.get( + "RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH", None +) + +# How often autoscaling metrics are recorded on Serve replicas. +RAY_SERVE_REPLICA_AUTOSCALING_METRIC_RECORD_PERIOD_S = 0.5 + +# How often autoscaling metrics are recorded on Serve handles. +RAY_SERVE_HANDLE_AUTOSCALING_METRIC_RECORD_PERIOD_S = 0.5 + +# Serve multiplexed matching timeout. +# This is the timeout for the matching process of multiplexed requests. To avoid +# thundering herd problem, the timeout value will be randomed between this value +# and this value * 2. The unit is second. +# If the matching process takes longer than the timeout, the request will be +# fallen to the default routing strategy. +RAY_SERVE_MULTIPLEXED_MODEL_ID_MATCHING_TIMEOUT_S = float( + os.environ.get("RAY_SERVE_MULTIPLEXED_MODEL_ID_MATCHING_TIMEOUT_S", "1") +) + +# Enable memray in all Serve actors. +RAY_SERVE_ENABLE_MEMORY_PROFILING = ( + os.environ.get("RAY_SERVE_ENABLE_MEMORY_PROFILING", "0") == "1" +) + +# Enable cProfile in all Serve actors. +RAY_SERVE_ENABLE_CPU_PROFILING = ( + os.environ.get("RAY_SERVE_ENABLE_CPU_PROFILING", "0") == "1" +) + +# Max value allowed for max_replicas_per_node option. +# TODO(jjyao) the <= 100 limitation is an artificial one +# and is due to the fact that Ray core only supports resource +# precision up to 0.0001. +# This limitation should be lifted in the long term. +MAX_REPLICAS_PER_NODE_MAX_VALUE = 100 + +# Argument name for passing in the gRPC context into a replica. +GRPC_CONTEXT_ARG_NAME = "grpc_context" + +# Whether or not to forcefully kill replicas that fail health checks. +RAY_SERVE_FORCE_STOP_UNHEALTHY_REPLICAS = ( + os.environ.get("RAY_SERVE_FORCE_STOP_UNHEALTHY_REPLICAS", "0") == "1" +) + +# Initial deadline for queue length responses in the router. +RAY_SERVE_QUEUE_LENGTH_RESPONSE_DEADLINE_S = float( + os.environ.get("RAY_SERVE_QUEUE_LENGTH_RESPONSE_DEADLINE_S", 0.1) +) + +# Maximum deadline for queue length responses in the router (in backoff). +RAY_SERVE_MAX_QUEUE_LENGTH_RESPONSE_DEADLINE_S = float( + os.environ.get("RAY_SERVE_MAX_QUEUE_LENGTH_RESPONSE_DEADLINE_S", 1.0) +) + +# Length of time to respect entries in the queue length cache when routing requests. +RAY_SERVE_QUEUE_LENGTH_CACHE_TIMEOUT_S = float( + os.environ.get("RAY_SERVE_QUEUE_LENGTH_CACHE_TIMEOUT_S", 10.0) +) + +# The default autoscaling policy to use if none is specified. +DEFAULT_AUTOSCALING_POLICY = "ray.serve.autoscaling_policy:default_autoscaling_policy" + +# Feature flag to enable collecting all queued and ongoing request +# metrics at handles instead of replicas. ON by default. +RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE = ( + os.environ.get("RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE", "1") == "1" +) + +RAY_SERVE_MIN_HANDLE_METRICS_TIMEOUT_S = float( + os.environ.get("RAY_SERVE_MIN_HANDLE_METRICS_TIMEOUT_S", 10.0) +) + +# Feature flag to always run a proxy on the head node even if it has no replicas. +RAY_SERVE_ALWAYS_RUN_PROXY_ON_HEAD_NODE = ( + os.environ.get("RAY_SERVE_ALWAYS_RUN_PROXY_ON_HEAD_NODE", "1") == "1" +) + + +# Default is 2GiB, the max for a signed int. +RAY_SERVE_GRPC_MAX_MESSAGE_SIZE = int( + os.environ.get("RAY_SERVE_GRPC_MAX_MESSAGE_SIZE", (2 * 1024 * 1024 * 1024) - 1) +) + +# Default options passed when constructing gRPC servers. +DEFAULT_GRPC_SERVER_OPTIONS = [ + ("grpc.max_send_message_length", RAY_SERVE_GRPC_MAX_MESSAGE_SIZE), + ("grpc.max_receive_message_length", RAY_SERVE_GRPC_MAX_MESSAGE_SIZE), +] + +# Timeout for gracefully shutting down metrics pusher, e.g. in routers or replicas +METRICS_PUSHER_GRACEFUL_SHUTDOWN_TIMEOUT_S = 10 + +# Feature flag to set `enable_task_events=True` on Serve-managed actors. +RAY_SERVE_ENABLE_TASK_EVENTS = ( + os.environ.get("RAY_SERVE_ENABLE_TASK_EVENTS", "0") == "1" +) + +# Use compact instead of spread scheduling strategy +RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY = ( + os.environ.get("RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY", "0") == "1" +) + + +def str_to_list(s: str) -> List[str]: + """Return a list from a comma-separated string. + + Trims whitespace and skips empty entries. + """ + return [r.strip() for r in s.split(",") if r.strip()] + + +# Comma-separated list of custom resources prioritized in scheduling. Sorted from highest to lowest priority. +# Example: "customx,customy" +RAY_SERVE_HIGH_PRIORITY_CUSTOM_RESOURCES: List[str] = str_to_list( + os.environ.get("RAY_SERVE_HIGH_PRIORITY_CUSTOM_RESOURCES", "") +) + +# Feature flag to always override local_testing_mode to True in serve.run. +# This is used for internal testing to avoid passing the flag to every invocation. +RAY_SERVE_FORCE_LOCAL_TESTING_MODE = ( + os.environ.get("RAY_SERVE_FORCE_LOCAL_TESTING_MODE", "0") == "1" +) + +# Run sync methods defined in the replica in a thread pool by default. +RAY_SERVE_RUN_SYNC_IN_THREADPOOL = ( + os.environ.get("RAY_SERVE_RUN_SYNC_IN_THREADPOOL", "0") == "1" +) + +RAY_SERVE_RUN_SYNC_IN_THREADPOOL_WARNING = ( + "Calling sync method '{method_name}' directly on the " + "asyncio loop. In a future version, sync methods will be run in a " + "threadpool by default. Ensure your sync methods are thread safe " + "or keep the existing behavior by making them `async def`. Opt " + "into the new behavior by setting " + "RAY_SERVE_RUN_SYNC_IN_THREADPOOL=1." +) + +# Feature flag to turn off GC optimizations in the proxy (in case there is a +# memory leak or negative performance impact). +RAY_SERVE_ENABLE_PROXY_GC_OPTIMIZATIONS = ( + os.environ.get("RAY_SERVE_ENABLE_PROXY_GC_OPTIMIZATIONS", "1") == "1" +) + +# Used for gc.set_threshold() when proxy GC optimizations are enabled. +RAY_SERVE_PROXY_GC_THRESHOLD = int( + os.environ.get("RAY_SERVE_PROXY_GC_THRESHOLD", "10000") +) + +# Interval at which cached metrics will be exported using the Ray metric API. +# Set to `0` to disable caching entirely. +RAY_SERVE_METRICS_EXPORT_INTERVAL_MS = int( + os.environ.get("RAY_SERVE_METRICS_EXPORT_INTERVAL_MS", "100") +) + +# The default request router class to use if none is specified. +DEFAULT_REQUEST_ROUTER_PATH = ( + "ray.serve._private.request_router:PowerOfTwoChoicesRequestRouter" +) + +# The default request routing period to use if none is specified. +DEFAULT_REQUEST_ROUTING_STATS_PERIOD_S = 10 + +# The default request routing timeout to use if none is specified. +DEFAULT_REQUEST_ROUTING_STATS_TIMEOUT_S = 30 + +# Name of deployment request routing stats method implemented by user. +REQUEST_ROUTING_STATS_METHOD = "record_routing_stats" + +# By default, we run user code in a separate event loop. +# This flag can be set to 0 to run user code in the same event loop as the +# replica's main event loop. +RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD = ( + os.environ.get("RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD", "1") == "1" +) + +# The default buffer size for request path logs. Setting to 1 will ensure +# logs are flushed to file handler immediately, otherwise it will be buffered +# and flushed to file handler when the buffer is full or when there is a log +# line with level ERROR. +RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE = int( + os.environ.get("RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE", "1") +) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/controller.py b/venv/lib/python3.10/site-packages/ray/serve/_private/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..4637e45461fef2ebb97e7b1308ff281905b69832 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/controller.py @@ -0,0 +1,1231 @@ +import asyncio +import logging +import marshal +import os +import pickle +import time +from typing import Any, Dict, Iterable, List, Optional, Tuple, Union + +import ray +from ray._common.utils import run_background_task +from ray._raylet import GcsClient +from ray.actor import ActorHandle +from ray.serve._private.application_state import ApplicationStateManager, StatusOverview +from ray.serve._private.autoscaling_state import AutoscalingStateManager +from ray.serve._private.common import ( + DeploymentHandleSource, + DeploymentID, + NodeId, + RequestProtocol, + RequestRoutingInfo, + RunningReplicaInfo, + TargetCapacityDirection, +) +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import ( + CONTROL_LOOP_INTERVAL_S, + RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH, + RECOVERING_LONG_POLL_BROADCAST_TIMEOUT_S, + SERVE_CONTROLLER_NAME, + SERVE_DEFAULT_APP_NAME, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, + SERVE_ROOT_URL_ENV_KEY, +) +from ray.serve._private.default_impl import create_cluster_node_info_cache +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.deployment_state import DeploymentStateManager +from ray.serve._private.endpoint_state import EndpointState +from ray.serve._private.grpc_util import set_proxy_default_grpc_options +from ray.serve._private.http_util import ( + configure_http_options_with_defaults, +) +from ray.serve._private.logging_utils import ( + configure_component_cpu_profiler, + configure_component_logger, + configure_component_memory_profiler, + get_component_logger_file_path, +) +from ray.serve._private.long_poll import LongPollHost, LongPollNamespace +from ray.serve._private.proxy_state import ProxyStateManager +from ray.serve._private.storage.kv_store import RayInternalKVStore +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + call_function_from_import_path, + get_all_live_placement_group_names, + get_head_node_id, + is_grpc_enabled, +) +from ray.serve.config import HTTPOptions, ProxyLocation, gRPCOptions +from ray.serve.generated.serve_pb2 import ( + ActorNameList, + DeploymentArgs, + DeploymentRoute, + EndpointInfo as EndpointInfoProto, + EndpointSet, +) +from ray.serve.schema import ( + ApplicationDetails, + DeploymentDetails, + HTTPOptionsSchema, + LoggingConfig, + ProxyDetails, + ServeActorDetails, + ServeApplicationSchema, + ServeDeploySchema, + ServeInstanceDetails, + TargetGroup, + gRPCOptionsSchema, +) +from ray.util import metrics + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +# Used for testing purposes only. If this is set, the controller will crash +# after writing each checkpoint with the specified probability. +_CRASH_AFTER_CHECKPOINT_PROBABILITY = 0 + +CONFIG_CHECKPOINT_KEY = "serve-app-config-checkpoint" +LOGGING_CONFIG_CHECKPOINT_KEY = "serve-logging-config-checkpoint" + + +class ServeController: + """Responsible for managing the state of the serving system. + + The controller implements fault tolerance by persisting its state in + a new checkpoint each time a state change is made. If the actor crashes, + the latest checkpoint is loaded and the state is recovered. Checkpoints + are written/read using a provided KV-store interface. + + All hard state in the system is maintained by this actor and persisted via + these checkpoints. Soft state required by other components is fetched by + those actors from this actor on startup and updates are pushed out from + this actor. + + All other actors started by the controller are named, detached actors + so they will not fate share with the controller if it crashes. + + The following guarantees are provided for state-changing calls to the + controller: + - If the call succeeds, the change was made and will be reflected in + the system even if the controller or other actors die unexpectedly. + - If the call fails, the change may have been made but isn't guaranteed + to have been. The client should retry in this case. Note that this + requires all implementations here to be idempotent. + """ + + async def __init__( + self, + *, + http_options: HTTPOptions, + global_logging_config: LoggingConfig, + grpc_options: Optional[gRPCOptions] = None, + ): + self._controller_node_id = ray.get_runtime_context().get_node_id() + assert ( + self._controller_node_id == get_head_node_id() + ), "Controller must be on the head node." + + self.ray_worker_namespace = ray.get_runtime_context().namespace + self.gcs_client = GcsClient(address=ray.get_runtime_context().gcs_address) + kv_store_namespace = f"ray-serve-{self.ray_worker_namespace}" + self.kv_store = RayInternalKVStore(kv_store_namespace, self.gcs_client) + + self.long_poll_host = LongPollHost() + self.done_recovering_event = asyncio.Event() + + # Try to read config from checkpoint + # logging config from checkpoint take precedence over the one passed in + # the constructor. + self.global_logging_config = None + log_config_checkpoint = self.kv_store.get(LOGGING_CONFIG_CHECKPOINT_KEY) + if log_config_checkpoint is not None: + global_logging_config = pickle.loads(log_config_checkpoint) + self.reconfigure_global_logging_config(global_logging_config) + + configure_component_memory_profiler( + component_name="controller", component_id=str(os.getpid()) + ) + self.cpu_profiler, self.cpu_profiler_log = configure_component_cpu_profiler( + component_name="controller", component_id=str(os.getpid()) + ) + if RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH: + logger.info( + "Calling user-provided callback from import path " + f"{RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH}." + ) + call_function_from_import_path(RAY_SERVE_CONTROLLER_CALLBACK_IMPORT_PATH) + + # Used to read/write checkpoints. + self.cluster_node_info_cache = create_cluster_node_info_cache(self.gcs_client) + self.cluster_node_info_cache.update() + + # Configure proxy default HTTP and gRPC options. + self.proxy_state_manager = ProxyStateManager( + http_options=configure_http_options_with_defaults(http_options), + head_node_id=self._controller_node_id, + cluster_node_info_cache=self.cluster_node_info_cache, + logging_config=self.global_logging_config, + grpc_options=set_proxy_default_grpc_options(grpc_options), + ) + # We modify the HTTP and gRPC options above, so delete them to avoid + del http_options, grpc_options + + self.endpoint_state = EndpointState(self.kv_store, self.long_poll_host) + + # Fetch all running actors in current cluster as source of current + # replica state for controller failure recovery + all_current_actors = ray.util.list_named_actors(all_namespaces=True) + all_serve_actor_names = [ + actor["name"] + for actor in all_current_actors + if actor["namespace"] == SERVE_NAMESPACE + ] + + self.autoscaling_state_manager = AutoscalingStateManager() + self.deployment_state_manager = DeploymentStateManager( + self.kv_store, + self.long_poll_host, + all_serve_actor_names, + get_all_live_placement_group_names(), + self.cluster_node_info_cache, + self.autoscaling_state_manager, + ) + + # Manage all applications' state + self.application_state_manager = ApplicationStateManager( + self.deployment_state_manager, + self.endpoint_state, + self.kv_store, + self.global_logging_config, + ) + + # Controller actor details + self._actor_details = ServeActorDetails( + node_id=ray.get_runtime_context().get_node_id(), + node_ip=ray.util.get_node_ip_address(), + node_instance_id=ray.util.get_node_instance_id(), + actor_id=ray.get_runtime_context().get_actor_id(), + actor_name=SERVE_CONTROLLER_NAME, + worker_id=ray.get_runtime_context().get_worker_id(), + log_file_path=get_component_logger_file_path(), + ) + self._shutting_down = False + self._shutdown_event = asyncio.Event() + self._shutdown_start_time = None + + self._create_control_loop_metrics() + run_background_task(self.run_control_loop()) + + # The target capacity percentage for all deployments across the cluster. + self._target_capacity: Optional[float] = None + self._target_capacity_direction: Optional[TargetCapacityDirection] = None + self._recover_state_from_checkpoint() + + # Nodes where proxy actors should run. + self._proxy_nodes = set() + self._update_proxy_nodes() + + def reconfigure_global_logging_config(self, global_logging_config: LoggingConfig): + if ( + self.global_logging_config + and self.global_logging_config == global_logging_config + ): + return + self.kv_store.put( + LOGGING_CONFIG_CHECKPOINT_KEY, pickle.dumps(global_logging_config) + ) + self.global_logging_config = global_logging_config + + self.long_poll_host.notify_changed( + {LongPollNamespace.GLOBAL_LOGGING_CONFIG: global_logging_config} + ) + configure_component_logger( + component_name="controller", + component_id=str(os.getpid()), + logging_config=global_logging_config, + ) + + logger.info( + f"Controller starting (version='{ray.__version__}').", + extra={"log_to_stderr": False}, + ) + logger.debug( + "Configure the serve controller logger " + f"with logging config: {self.global_logging_config}" + ) + + def check_alive(self) -> None: + """No-op to check if this controller is alive.""" + return + + def get_pid(self) -> int: + return os.getpid() + + def record_autoscaling_metrics( + self, replica_id: str, window_avg: Optional[float], send_timestamp: float + ): + logger.debug( + f"Received metrics from replica {replica_id}: {window_avg} running requests" + ) + self.autoscaling_state_manager.record_request_metrics_for_replica( + replica_id, window_avg, send_timestamp + ) + + def record_handle_metrics( + self, + deployment_id: str, + handle_id: str, + actor_id: Optional[str], + handle_source: DeploymentHandleSource, + queued_requests: float, + running_requests: Dict[str, float], + send_timestamp: float, + ): + logger.debug( + f"Received metrics from handle {handle_id} for deployment {deployment_id}: " + f"{queued_requests} queued requests and {running_requests} running requests" + ) + self.autoscaling_state_manager.record_request_metrics_for_handle( + deployment_id=deployment_id, + handle_id=handle_id, + actor_id=actor_id, + handle_source=handle_source, + queued_requests=queued_requests, + running_requests=running_requests, + send_timestamp=send_timestamp, + ) + + def _dump_autoscaling_metrics_for_testing(self): + return self.autoscaling_state_manager.get_metrics() + + def _dump_replica_states_for_testing(self, deployment_id: DeploymentID): + return self.deployment_state_manager._deployment_states[deployment_id]._replicas + + def _stop_one_running_replica_for_testing(self, deployment_id): + self.deployment_state_manager._deployment_states[ + deployment_id + ]._stop_one_running_replica_for_testing() + + async def listen_for_change(self, keys_to_snapshot_ids: Dict[str, int]): + """Proxy long pull client's listen request. + + Args: + keys_to_snapshot_ids (Dict[str, int]): Snapshot IDs are used to + determine whether or not the host should immediately return the + data or wait for the value to be changed. + """ + if not self.done_recovering_event.is_set(): + await self.done_recovering_event.wait() + + return await self.long_poll_host.listen_for_change(keys_to_snapshot_ids) + + async def listen_for_change_java(self, keys_to_snapshot_ids_bytes: bytes): + """Proxy long pull client's listen request. + + Args: + keys_to_snapshot_ids_bytes (Dict[str, int]): the protobuf bytes of + keys_to_snapshot_ids (Dict[str, int]). + """ + if not self.done_recovering_event.is_set(): + await self.done_recovering_event.wait() + + return await self.long_poll_host.listen_for_change_java( + keys_to_snapshot_ids_bytes + ) + + def get_all_endpoints(self) -> Dict[DeploymentID, Dict[str, Any]]: + """Returns a dictionary of deployment name to config.""" + return self.endpoint_state.get_endpoints() + + def get_all_endpoints_java(self) -> bytes: + """Returns a dictionary of deployment name to config.""" + endpoints = self.get_all_endpoints() + # NOTE(zcin): Java only supports 1.x deployments, so only return + # a dictionary of deployment name -> endpoint info + data = { + endpoint_tag.name: EndpointInfoProto(route=endpoint_dict["route"]) + for endpoint_tag, endpoint_dict in endpoints.items() + } + return EndpointSet(endpoints=data).SerializeToString() + + def get_proxies(self) -> Dict[NodeId, ActorHandle]: + """Returns a dictionary of node ID to proxy actor handles.""" + if self.proxy_state_manager is None: + return {} + return self.proxy_state_manager.get_proxy_handles() + + def get_proxy_names(self) -> bytes: + """Returns the proxy actor name list serialized by protobuf.""" + if self.proxy_state_manager is None: + return None + + actor_name_list = ActorNameList( + names=self.proxy_state_manager.get_proxy_names().values() + ) + return actor_name_list.SerializeToString() + + def _update_proxy_nodes(self): + """Update the nodes set where proxy actors should run. + + Controller decides where proxy actors should run + (head node and nodes with deployment replicas). + """ + new_proxy_nodes = self.deployment_state_manager.get_active_node_ids() + new_proxy_nodes = new_proxy_nodes - set( + self.cluster_node_info_cache.get_draining_nodes() + ) + new_proxy_nodes.add(self._controller_node_id) + self._proxy_nodes = new_proxy_nodes + + async def run_control_loop(self) -> None: + # NOTE(edoakes): we catch all exceptions here and simply log them, + # because an unhandled exception would cause the main control loop to + # halt, which should *never* happen. + recovering_timeout = RECOVERING_LONG_POLL_BROADCAST_TIMEOUT_S + num_loops = 0 + start_time = time.time() + while True: + loop_start_time = time.time() + try: + await self.run_control_loop_step( + start_time, recovering_timeout, num_loops + ) + except Exception as e: + # we never expect this to happen, but adding this to be safe + logger.exception(f"There was an exception in the control loop: {e}") + await asyncio.sleep(1) + + loop_duration = time.time() - loop_start_time + if loop_duration > 10: + logger.warning( + f"The last control loop was slow (took {loop_duration}s). " + "This is likely caused by running a large number of " + "replicas in a single Ray cluster. Consider using " + "multiple Ray clusters.", + extra={"log_to_stderr": False}, + ) + self.control_loop_duration_gauge_s.set(loop_duration) + + num_loops += 1 + self.num_control_loops_gauge.set(num_loops) + + sleep_start_time = time.time() + await asyncio.sleep(CONTROL_LOOP_INTERVAL_S) + self.sleep_duration_gauge_s.set(time.time() - sleep_start_time) + + async def run_control_loop_step( + self, start_time: float, recovering_timeout: float, num_loops: int + ): + try: + self.cluster_node_info_cache.update() + except Exception: + logger.exception("Exception updating cluster node info cache.") + + if self._shutting_down: + try: + self.shutdown() + except Exception: + logger.exception("Exception during shutdown.") + + if ( + not self.done_recovering_event.is_set() + and time.time() - start_time > recovering_timeout + ): + logger.warning( + f"Replicas still recovering after {recovering_timeout}s, " + "setting done recovering event to broadcast long poll updates." + ) + self.done_recovering_event.set() + + # initialize any_recovering to None to indicate that we don't know if + # we've recovered anything yet + any_recovering: Optional[bool] = None + try: + dsm_update_start_time = time.time() + any_recovering = self.deployment_state_manager.update() + + self.deployment_state_manager.save_checkpoint() + + self.dsm_update_duration_gauge_s.set(time.time() - dsm_update_start_time) + if not self.done_recovering_event.is_set() and not any_recovering: + self.done_recovering_event.set() + if num_loops > 0: + # Only log if we actually needed to recover anything. + logger.info( + "Finished recovering deployments after " + f"{(time.time() - start_time):.2f}s.", + extra={"log_to_stderr": False}, + ) + except Exception: + logger.exception("Exception updating deployment state.") + + try: + asm_update_start_time = time.time() + self.application_state_manager.update() + + self.application_state_manager.save_checkpoint() + # ApplicationStateManager.update() can also mutate the + # DeploymentStateManager so we need to checkpoint that as well + self.deployment_state_manager.save_checkpoint() + + self.asm_update_duration_gauge_s.set(time.time() - asm_update_start_time) + except Exception: + logger.exception("Exception updating application state.") + + # Update the proxy nodes set before updating the proxy states, + # so they are more consistent. + node_update_start_time = time.time() + self._update_proxy_nodes() + self.node_update_duration_gauge_s.set(time.time() - node_update_start_time) + + # Don't update proxy_state until after the done recovering event is set, + # otherwise we may start a new proxy but not broadcast it any + # info about available deployments & their replicas. + if self.proxy_state_manager and self.done_recovering_event.is_set(): + try: + proxy_update_start_time = time.time() + self.proxy_state_manager.update(proxy_nodes=self._proxy_nodes) + self.proxy_update_duration_gauge_s.set( + time.time() - proxy_update_start_time + ) + except Exception: + logger.exception("Exception updating proxy state.") + + # When the controller is done recovering, drop invalid handle metrics + # that may be stale for autoscaling + if any_recovering is False: + self.autoscaling_state_manager.drop_stale_handle_metrics( + self.deployment_state_manager.get_alive_replica_actor_ids() + | self.proxy_state_manager.get_alive_proxy_actor_ids() + ) + + def _create_control_loop_metrics(self): + self.node_update_duration_gauge_s = metrics.Gauge( + "serve_controller_node_update_duration_s", + description="The control loop time spent on collecting proxy node info.", + ) + self.proxy_update_duration_gauge_s = metrics.Gauge( + "serve_controller_proxy_state_update_duration_s", + description="The control loop time spent on updating proxy state.", + ) + self.dsm_update_duration_gauge_s = metrics.Gauge( + "serve_controller_deployment_state_update_duration_s", + description="The control loop time spent on updating deployment state.", + ) + self.asm_update_duration_gauge_s = metrics.Gauge( + "serve_controller_application_state_update_duration_s", + description="The control loop time spent on updating application state.", + ) + self.sleep_duration_gauge_s = metrics.Gauge( + "serve_controller_sleep_duration_s", + description="The duration of the last control loop's sleep.", + ) + self.control_loop_duration_gauge_s = metrics.Gauge( + "serve_controller_control_loop_duration_s", + description="The duration of the last control loop.", + ) + self.num_control_loops_gauge = metrics.Gauge( + "serve_controller_num_control_loops", + description=( + "The number of control loops performed by the controller. " + "Increases monotonically over the controller's lifetime." + ), + tag_keys=("actor_id",), + ) + self.num_control_loops_gauge.set_default_tags( + {"actor_id": ray.get_runtime_context().get_actor_id()} + ) + + def _recover_state_from_checkpoint(self): + ( + deployment_time, + serve_config, + target_capacity_direction, + ) = self._read_config_checkpoint() + self._target_capacity_direction = target_capacity_direction + if serve_config is not None: + logger.info( + "Recovered config from checkpoint.", extra={"log_to_stderr": False} + ) + self.apply_config(serve_config, deployment_time=deployment_time) + + def _read_config_checkpoint( + self, + ) -> Tuple[float, Optional[ServeDeploySchema], Optional[TargetCapacityDirection]]: + """Reads the current Serve config checkpoint. + + The Serve config checkpoint stores active application configs and + other metadata. + + Returns: + + If the GCS contains a checkpoint, tuple of: + 1. A deployment timestamp. + 2. A Serve config. This Serve config is reconstructed from the + active application states. It may not exactly match the + submitted config (e.g. the top-level http options may be + different). + 3. The target_capacity direction calculated after the Serve + was submitted. + + If the GCS doesn't contain a checkpoint, returns (0, None, None). + """ + + checkpoint = self.kv_store.get(CONFIG_CHECKPOINT_KEY) + if checkpoint is not None: + ( + deployment_time, + target_capacity, + target_capacity_direction, + config_checkpoints_dict, + ) = pickle.loads(checkpoint) + + return ( + deployment_time, + ServeDeploySchema( + applications=list(config_checkpoints_dict.values()), + target_capacity=target_capacity, + ), + target_capacity_direction, + ) + else: + return (0.0, None, None) + + def _all_running_replicas(self) -> Dict[DeploymentID, List[RunningReplicaInfo]]: + """Used for testing. + + Returned dictionary maps deployment names to replica infos. + """ + + return self.deployment_state_manager.get_running_replica_infos() + + def get_actor_details(self) -> ServeActorDetails: + """Returns the actor details for this controller. + + Currently used for test only. + """ + return self._actor_details + + def get_proxy_details(self, node_id: str) -> Optional[ProxyDetails]: + """Returns the proxy details for the proxy on the given node. + + Currently used for test only. Will return None if the proxy doesn't exist on + the given node. + """ + if self.proxy_state_manager is None: + return None + + return self.proxy_state_manager.get_proxy_details().get(node_id) + + def get_deployment_timestamps(self, app_name: str) -> float: + """Returns the deployment timestamp for the given app. + + Currently used for test only. + """ + for ( + _app_name, + app_status_info, + ) in self.application_state_manager.list_app_statuses().items(): + if app_name == _app_name: + return app_status_info.deployment_timestamp + + def get_deployment_details( + self, app_name: str, deployment_name: str + ) -> DeploymentDetails: + """Returns the deployment details for the app and deployment. + + Currently used for test only. + """ + return self.application_state_manager.list_deployment_details(app_name)[ + deployment_name + ] + + def get_http_config(self) -> HTTPOptions: + """Return the HTTP proxy configuration.""" + if self.proxy_state_manager is None: + return HTTPOptions() + return self.proxy_state_manager.get_config() + + def get_grpc_config(self) -> gRPCOptions: + """Return the gRPC proxy configuration.""" + if self.proxy_state_manager is None: + return gRPCOptions() + return self.proxy_state_manager.get_grpc_config() + + def get_root_url(self): + """Return the root url for the serve instance.""" + if self.proxy_state_manager is None: + return None + http_config = self.get_http_config() + if http_config.root_url == "": + if SERVE_ROOT_URL_ENV_KEY in os.environ: + return os.environ[SERVE_ROOT_URL_ENV_KEY] + else: + return ( + f"http://{http_config.host}:{http_config.port}" + f"{http_config.root_path}" + ) + return http_config.root_url + + def config_checkpoint_deleted(self) -> bool: + """Returns whether the config checkpoint has been deleted. + + Get the config checkpoint from the kv store. If it is None, then it has been + deleted. + """ + return self.kv_store.get(CONFIG_CHECKPOINT_KEY) is None + + def shutdown(self): + """Shuts down the serve instance completely. + + This method will only be triggered when `self._shutting_down` is true. It + deletes the kv store for config checkpoints, sets application state to deleting, + delete all deployments, and shuts down all proxies. Once all these + resources are released, it then kills the controller actor. + """ + if not self._shutting_down: + return + + if self._shutdown_start_time is None: + self._shutdown_start_time = time.time() + logger.info("Controller shutdown started.", extra={"log_to_stderr": False}) + + self.kv_store.delete(CONFIG_CHECKPOINT_KEY) + self.kv_store.delete(LOGGING_CONFIG_CHECKPOINT_KEY) + self.application_state_manager.shutdown() + self.deployment_state_manager.shutdown() + self.endpoint_state.shutdown() + if self.proxy_state_manager: + self.proxy_state_manager.shutdown() + + config_checkpoint_deleted = self.config_checkpoint_deleted() + application_is_shutdown = self.application_state_manager.is_ready_for_shutdown() + deployment_is_shutdown = self.deployment_state_manager.is_ready_for_shutdown() + endpoint_is_shutdown = self.endpoint_state.is_ready_for_shutdown() + proxy_state_is_shutdown = ( + self.proxy_state_manager is None + or self.proxy_state_manager.is_ready_for_shutdown() + ) + if ( + config_checkpoint_deleted + and application_is_shutdown + and deployment_is_shutdown + and endpoint_is_shutdown + and proxy_state_is_shutdown + ): + logger.warning( + "All resources have shut down, controller exiting.", + extra={"log_to_stderr": False}, + ) + _controller_actor = ray.get_runtime_context().current_actor + ray.kill(_controller_actor, no_restart=True) + elif time.time() - self._shutdown_start_time > 10: + if not config_checkpoint_deleted: + logger.warning( + f"{CONFIG_CHECKPOINT_KEY} not yet deleted", + extra={"log_to_stderr": False}, + ) + if not application_is_shutdown: + logger.warning( + "application not yet shutdown", + extra={"log_to_stderr": False}, + ) + if not deployment_is_shutdown: + logger.warning( + "deployment not yet shutdown", + extra={"log_to_stderr": False}, + ) + if not endpoint_is_shutdown: + logger.warning( + "endpoint not yet shutdown", + extra={"log_to_stderr": False}, + ) + if not proxy_state_is_shutdown: + logger.warning( + "proxy_state not yet shutdown", + extra={"log_to_stderr": False}, + ) + + def deploy_applications( + self, name_to_deployment_args_list: Dict[str, List[bytes]] + ) -> None: + """ + Takes in a list of dictionaries that contain deployment arguments. + If same app name deployed, old application will be overwritten. + + Args: + name: Application name. + deployment_args_list: List of serialized deployment information, + where each item in the list is bytes representing the serialized + protobuf `DeploymentArgs` object. `DeploymentArgs` contains all the + information for the single deployment. + """ + name_to_deployment_args = {} + for name, deployment_args_list in name_to_deployment_args_list.items(): + deployment_args_deserialized = [] + for deployment_args_bytes in deployment_args_list: + args = DeploymentArgs.FromString(deployment_args_bytes) + deployment_args_deserialized.append( + { + "deployment_name": args.deployment_name, + "deployment_config_proto_bytes": args.deployment_config, + "replica_config_proto_bytes": args.replica_config, + "deployer_job_id": args.deployer_job_id, + "ingress": args.ingress, + "route_prefix": ( + args.route_prefix if args.HasField("route_prefix") else None + ), + "docs_path": ( + args.docs_path if args.HasField("docs_path") else None + ), + } + ) + name_to_deployment_args[name] = deployment_args_deserialized + + self.application_state_manager.deploy_apps(name_to_deployment_args) + + self.application_state_manager.save_checkpoint() + + def deploy_application(self, name: str, deployment_args_list: List[bytes]) -> None: + """ + Deploy a single application + (as deploy_applications(), but it only takes a single name and deployment args). + This primarily exists as a shim to avoid + changing Java code in https://github.com/ray-project/ray/pull/49168, + and could be removed if the Java code was refactored + to use the new bulk deploy_applications API. + """ + self.deploy_applications({name: deployment_args_list}) + + def apply_config( + self, + config: ServeDeploySchema, + deployment_time: float = 0.0, + ) -> None: + """Apply the config described in `ServeDeploySchema`. + + This will upgrade the applications to the goal state specified in the + config. + + If `deployment_time` is not provided, `time.time()` is used. + """ + ServeUsageTag.API_VERSION.record("v2") + if not deployment_time: + deployment_time = time.time() + + new_config_checkpoint = {} + + _, curr_config, _ = self._read_config_checkpoint() + + self._target_capacity_direction = calculate_target_capacity_direction( + curr_config=curr_config, + new_config=config, + curr_target_capacity_direction=self._target_capacity_direction, + ) + log_target_capacity_change( + self._target_capacity, + config.target_capacity, + self._target_capacity_direction, + ) + self._target_capacity = config.target_capacity + + for app_config in config.applications: + # If the application logging config is not set, use the global logging + # config. + if app_config.logging_config is None and config.logging_config: + app_config.logging_config = config.logging_config + + app_config_dict = app_config.dict(exclude_unset=True) + new_config_checkpoint[app_config.name] = app_config_dict + + self.kv_store.put( + CONFIG_CHECKPOINT_KEY, + pickle.dumps( + ( + deployment_time, + self._target_capacity, + self._target_capacity_direction, + new_config_checkpoint, + ) + ), + ) + + # Declaratively apply the new set of applications. + # This will delete any applications no longer in the config that were + # previously deployed via the REST API. + self.application_state_manager.apply_app_configs( + config.applications, + deployment_time=deployment_time, + target_capacity=self._target_capacity, + target_capacity_direction=self._target_capacity_direction, + ) + + self.application_state_manager.save_checkpoint() + + def get_deployment_info(self, name: str, app_name: str = "") -> bytes: + """Get the current information about a deployment. + + Args: + name: the name of the deployment. + + Returns: + DeploymentRoute's protobuf serialized bytes + + Raises: + KeyError: If the deployment doesn't exist. + """ + id = DeploymentID(name=name, app_name=app_name) + deployment_info = self.deployment_state_manager.get_deployment(id) + if deployment_info is None: + app_msg = f" in application '{app_name}'" if app_name else "" + raise KeyError(f"Deployment '{name}' does not exist{app_msg}.") + + route = self.endpoint_state.get_endpoint_route(id) + + deployment_route = DeploymentRoute( + deployment_info=deployment_info.to_proto(), route=route + ) + return deployment_route.SerializeToString() + + def list_deployments_internal( + self, + ) -> Dict[DeploymentID, Tuple[DeploymentInfo, str]]: + """Gets the current information about all deployments. + + Returns: + Dict(deployment_id, (DeploymentInfo, route)) + """ + return { + id: (info, self.endpoint_state.get_endpoint_route(id)) + for id, info in self.deployment_state_manager.get_deployment_infos().items() + } + + def get_deployment_config( + self, deployment_id: DeploymentID + ) -> Optional[DeploymentConfig]: + """Get the deployment config for the given deployment id. + + Args: + deployment_id: The deployment id to get the config for. + + Returns: + A deployment config object if the deployment id exist, + None otherwise. + """ + deployment_info = self.deployment_state_manager.get_deployment_infos().get( + deployment_id + ) + return deployment_info.deployment_config if deployment_info else None + + def list_deployment_ids(self) -> List[DeploymentID]: + """Gets the current list of all deployments' identifiers.""" + return self.deployment_state_manager._deployment_states.keys() + + def get_serve_instance_details(self) -> Dict: + """Gets details on all applications on the cluster and system-level info. + + The information includes application and deployment statuses, config options, + error messages, etc. + + Returns: + Dict that follows the format of the schema ServeInstanceDetails. + """ + + http_config = self.get_http_config() + grpc_config = self.get_grpc_config() + applications = {} + + app_statuses = self.application_state_manager.list_app_statuses() + + # If there are no app statuses, there's no point getting the app configs. + # Moreover, there might be no app statuses because the GCS is down, + # in which case getting the app configs would fail anyway, + # since they're stored in the checkpoint in the GCS. + app_configs = self.get_app_configs() if app_statuses else {} + + for ( + app_name, + app_status_info, + ) in app_statuses.items(): + applications[app_name] = ApplicationDetails( + name=app_name, + route_prefix=self.application_state_manager.get_route_prefix(app_name), + docs_path=self.get_docs_path(app_name), + status=app_status_info.status, + message=app_status_info.message, + last_deployed_time_s=app_status_info.deployment_timestamp, + # This can be none if the app was deployed through + # serve.run, the app is in deleting state, + # or a checkpoint hasn't been set yet + deployed_app_config=app_configs.get(app_name), + source=self.application_state_manager.get_app_source(app_name), + deployments=self.application_state_manager.list_deployment_details( + app_name + ), + ) + + # NOTE(zcin): We use exclude_unset here because we explicitly and intentionally + # fill in all info that should be shown to users. + http_options = HTTPOptionsSchema.parse_obj(http_config.dict(exclude_unset=True)) + grpc_options = gRPCOptionsSchema.parse_obj(grpc_config.dict(exclude_unset=True)) + + return ServeInstanceDetails( + target_capacity=self._target_capacity, + controller_info=self._actor_details, + proxy_location=ProxyLocation._from_deployment_mode(http_config.location), + http_options=http_options, + grpc_options=grpc_options, + proxies=( + self.proxy_state_manager.get_proxy_details() + if self.proxy_state_manager + else None + ), + applications=applications, + target_groups=self.get_target_groups(), + )._get_user_facing_json_serializable_dict(exclude_unset=True) + + def get_target_groups(self, app_name: Optional[str] = None) -> List[TargetGroup]: + """Target groups contains information about IP + addresses and ports of all proxies in the cluster. + + This information is used to setup the load balancer. + """ + target_groups: List[TargetGroup] = [] + + if self.proxy_state_manager.get_proxy_details(): + # setting prefix route to "/" because in ray serve, proxy + # accepts requests from the client and routes them to the + # correct application. This is true for both HTTP and gRPC proxies. + target_groups.append( + TargetGroup( + protocol=RequestProtocol.HTTP, + route_prefix="/", + targets=self.proxy_state_manager.get_targets(RequestProtocol.HTTP), + ) + ) + if is_grpc_enabled(self.get_grpc_config()): + target_groups.append( + TargetGroup( + protocol=RequestProtocol.GRPC, + route_prefix="/", + targets=self.proxy_state_manager.get_targets( + RequestProtocol.GRPC + ), + ) + ) + return target_groups + + def get_serve_status(self, name: str = SERVE_DEFAULT_APP_NAME) -> bytes: + """Return application status + Args: + name: application name. If application name doesn't exist, app_status + is NOT_STARTED. + """ + + app_status = self.application_state_manager.get_app_status_info(name) + deployment_statuses = self.application_state_manager.get_deployments_statuses( + name + ) + status_info = StatusOverview( + name=name, + app_status=app_status, + deployment_statuses=deployment_statuses, + ) + return status_info.to_proto().SerializeToString() + + def get_serve_statuses(self, names: List[str]) -> List[bytes]: + statuses = [] + for name in names: + statuses.append(self.get_serve_status(name)) + return statuses + + def list_serve_statuses(self) -> List[bytes]: + statuses = [] + for name in self.application_state_manager.list_app_statuses(): + statuses.append(self.get_serve_status(name)) + return statuses + + def get_app_configs(self) -> Dict[str, ServeApplicationSchema]: + checkpoint = self.kv_store.get(CONFIG_CHECKPOINT_KEY) + if checkpoint is None: + return {} + + _, _, _, config_checkpoints_dict = pickle.loads(checkpoint) + return { + app: ServeApplicationSchema.parse_obj(config) + for app, config in config_checkpoints_dict.items() + } + + def get_all_deployment_statuses(self) -> List[bytes]: + """Gets deployment status bytes for all live deployments.""" + statuses = self.deployment_state_manager.get_deployment_statuses() + return [status.to_proto().SerializeToString() for status in statuses] + + def get_deployment_status( + self, name: str, app_name: str = "" + ) -> Union[None, bytes]: + """Get deployment status by deployment name. + + Args: + name: Deployment name. + app_name: Application name. Default is "" because 1.x + deployments go through this API. + """ + + id = DeploymentID(name=name, app_name=app_name) + status = self.deployment_state_manager.get_deployment_statuses([id]) + if not status: + return None + return status[0].to_proto().SerializeToString() + + def get_docs_path(self, name: str): + """Docs path for application. + + Currently, this is the OpenAPI docs path for FastAPI-integrated applications.""" + return self.application_state_manager.get_docs_path(name) + + def get_ingress_deployment_name(self, app_name: str) -> Optional[str]: + """Name of the ingress deployment in an application. + + Returns: + Ingress deployment name (str): if the application exists. + None: if the application does not exist. + """ + return self.application_state_manager.get_ingress_deployment_name(app_name) + + def delete_apps(self, names: Iterable[str]): + """Delete applications based on names + + During deletion, the application status is DELETING + """ + for name in names: + self.application_state_manager.delete_app(name) + + self.application_state_manager.save_checkpoint() + + def record_request_routing_info(self, info: RequestRoutingInfo): + """Record replica routing information for a replica. + + Args: + info: RequestRoutingInfo including deployment name, replica tag, + multiplex model ids, and routing stats. + """ + self.deployment_state_manager.record_request_routing_info(info) + + async def graceful_shutdown(self, wait: bool = True): + """Set the shutting down flag on controller to signal shutdown in + run_control_loop(). + + This is used to signal to the controller that it should proceed with shutdown + process, so it can shut down gracefully. It also waits until the shutdown + event is triggered if wait is true. + + Raises: + RayActorError: if wait is True, the caller waits until the controller + is killed, which raises a RayActorError. + """ + self._shutting_down = True + if not wait: + return + + # This event never gets set. The caller waits indefinitely on this event + # until the controller is killed, which raises a RayActorError. + await self._shutdown_event.wait() + + def _save_cpu_profile_data(self) -> str: + """Saves CPU profiling data, if CPU profiling is enabled. + + Logs a warning if CPU profiling is disabled. + """ + + if self.cpu_profiler is not None: + self.cpu_profiler.snapshot_stats() + with open(self.cpu_profiler_log, "wb") as f: + marshal.dump(self.cpu_profiler.stats, f) + logger.info(f'Saved CPU profile data to file "{self.cpu_profiler_log}"') + return self.cpu_profiler_log + else: + logger.error( + "Attempted to save CPU profile data, but failed because no " + "CPU profiler was running! Enable CPU profiling by enabling " + "the RAY_SERVE_ENABLE_CPU_PROFILING env var." + ) + + def _get_logging_config(self) -> Tuple: + """Get the logging configuration (for testing purposes).""" + log_file_path = None + for handler in logger.handlers: + if isinstance(handler, logging.handlers.MemoryHandler): + log_file_path = handler.target.baseFilename + return self.global_logging_config, log_file_path + + def _get_target_capacity_direction(self) -> Optional[TargetCapacityDirection]: + """Gets the controller's scale direction (for testing purposes).""" + + return self._target_capacity_direction + + +def calculate_target_capacity_direction( + curr_config: Optional[ServeDeploySchema], + new_config: ServeDeploySchema, + curr_target_capacity_direction: Optional[float], +) -> Optional[TargetCapacityDirection]: + """Compares two Serve configs to calculate the next scaling direction.""" + + curr_target_capacity = None + next_target_capacity_direction = None + + if curr_config is not None and applications_match(curr_config, new_config): + curr_target_capacity = curr_config.target_capacity + next_target_capacity = new_config.target_capacity + + if curr_target_capacity == next_target_capacity: + next_target_capacity_direction = curr_target_capacity_direction + elif curr_target_capacity is None and next_target_capacity is not None: + # target_capacity is scaling down from None to a number. + next_target_capacity_direction = TargetCapacityDirection.DOWN + elif next_target_capacity is None: + next_target_capacity_direction = None + elif curr_target_capacity < next_target_capacity: + next_target_capacity_direction = TargetCapacityDirection.UP + else: + next_target_capacity_direction = TargetCapacityDirection.DOWN + elif new_config.target_capacity is not None: + # A config with different apps has been applied, and it contains a + # target_capacity. Serve must start scaling this config up. + next_target_capacity_direction = TargetCapacityDirection.UP + else: + next_target_capacity_direction = None + + return next_target_capacity_direction + + +def applications_match(config1: ServeDeploySchema, config2: ServeDeploySchema) -> bool: + """Checks whether the applications in config1 and config2 match. + + Two applications match if they have the same name. + """ + + config1_app_names = {app.name for app in config1.applications} + config2_app_names = {app.name for app in config2.applications} + + return config1_app_names == config2_app_names + + +def log_target_capacity_change( + curr_target_capacity: Optional[float], + next_target_capacity: Optional[float], + next_target_capacity_direction: Optional[TargetCapacityDirection], +): + """Logs changes in the target_capacity.""" + + if curr_target_capacity != next_target_capacity: + if isinstance(next_target_capacity_direction, TargetCapacityDirection): + logger.info( + "Target capacity scaling " + f"{next_target_capacity_direction.value.lower()} " + f"from {curr_target_capacity} to {next_target_capacity}." + ) + else: + logger.info("Target capacity entering 100% at steady state.") diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/controller_avatar.py b/venv/lib/python3.10/site-packages/ray/serve/_private/controller_avatar.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c5764809478a050bcbf900484f985ae942536a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/controller_avatar.py @@ -0,0 +1,40 @@ +import ray +from ray.serve._private.constants import SERVE_CONTROLLER_NAME, SERVE_NAMESPACE +from ray.serve._private.default_impl import get_controller_impl +from ray.serve.config import HTTPOptions +from ray.serve.schema import LoggingConfig + + +@ray.remote(num_cpus=0) +class ServeControllerAvatar: + """A hack that proxy the creation of async actors from Java. + + To be removed after https://github.com/ray-project/ray/pull/26037 + + Java api can not support python async actor. If we use java api create + python async actor. The async init method won't be executed. The async + method will fail with pickle error. And the run_control_loop of controller + actor can't be executed too. We use this proxy actor create python async + actor to avoid the above problem. + """ + + def __init__( + self, + http_proxy_port: int = 8000, + ): + try: + self._controller = ray.get_actor( + SERVE_CONTROLLER_NAME, namespace=SERVE_NAMESPACE + ) + except ValueError: + self._controller = None + if self._controller is None: + controller_impl = get_controller_impl() + self._controller = controller_impl.remote( + http_options=HTTPOptions(port=http_proxy_port), + global_logging_config=LoggingConfig(), + ) + + def check_alive(self) -> None: + """No-op to check if this actor is alive.""" + return diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/default_impl.py b/venv/lib/python3.10/site-packages/ray/serve/_private/default_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..118d75a83a54ae3b5342a3f5d9e69fc0f81600df --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/default_impl.py @@ -0,0 +1,220 @@ +from typing import Callable, Optional, Tuple + +import ray +from ray._private.resource_spec import HEAD_NODE_RESOURCE_NAME +from ray._raylet import GcsClient +from ray.serve._private.cluster_node_info_cache import ( + ClusterNodeInfoCache, + DefaultClusterNodeInfoCache, +) +from ray.serve._private.common import ( + CreatePlacementGroupRequest, + DeploymentHandleSource, + DeploymentID, + EndpointInfo, + RequestMetadata, + RequestProtocol, +) +from ray.serve._private.constants import ( + CONTROLLER_MAX_CONCURRENCY, + RAY_SERVE_ENABLE_TASK_EVENTS, + RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING, + SERVE_CONTROLLER_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.deployment_scheduler import ( + DefaultDeploymentScheduler, + DeploymentScheduler, +) +from ray.serve._private.grpc_util import gRPCGenericServer +from ray.serve._private.handle_options import DynamicHandleOptions, InitHandleOptions +from ray.serve._private.router import Router, SingletonThreadRouter +from ray.serve._private.utils import ( + generate_request_id, + get_current_actor_id, + get_head_node_id, + inside_ray_client_context, + resolve_deployment_response, +) +from ray.util.placement_group import PlacementGroup + +# NOTE: Please read carefully before changing! +# +# These methods are common extension points, therefore these should be +# changed as a Developer API, ie methods should not be renamed, have their +# API modified w/o substantial enough justification + + +def create_cluster_node_info_cache(gcs_client: GcsClient) -> ClusterNodeInfoCache: + return DefaultClusterNodeInfoCache(gcs_client) + + +CreatePlacementGroupFn = Callable[[CreatePlacementGroupRequest], PlacementGroup] + + +def _default_create_placement_group( + request: CreatePlacementGroupRequest, +) -> PlacementGroup: + return ray.util.placement_group( + request.bundles, + request.strategy, + _soft_target_node_id=request.target_node_id, + name=request.name, + lifetime="detached", + ) + + +def create_deployment_scheduler( + cluster_node_info_cache: ClusterNodeInfoCache, + head_node_id_override: Optional[str] = None, + create_placement_group_fn_override: Optional[CreatePlacementGroupFn] = None, +) -> DeploymentScheduler: + head_node_id = head_node_id_override or get_head_node_id() + return DefaultDeploymentScheduler( + cluster_node_info_cache, + head_node_id, + create_placement_group_fn=create_placement_group_fn_override + or _default_create_placement_group, + ) + + +def create_replica_impl(**kwargs): + from ray.serve._private.replica import Replica + + return Replica(**kwargs) + + +def create_replica_metrics_manager(**kwargs): + from ray.serve._private.replica import ReplicaMetricsManager + + return ReplicaMetricsManager(**kwargs) + + +def create_dynamic_handle_options(**kwargs): + return DynamicHandleOptions(**kwargs) + + +def create_init_handle_options(**kwargs): + return InitHandleOptions.create(**kwargs) + + +def get_request_metadata(init_options, handle_options): + _request_context = ray.serve.context._get_serve_request_context() + + request_protocol = RequestProtocol.UNDEFINED + if init_options and init_options._source == DeploymentHandleSource.PROXY: + if _request_context.is_http_request: + request_protocol = RequestProtocol.HTTP + elif _request_context.grpc_context: + request_protocol = RequestProtocol.GRPC + + return RequestMetadata( + request_id=_request_context.request_id + if _request_context.request_id + else generate_request_id(), + internal_request_id=_request_context._internal_request_id + if _request_context._internal_request_id + else generate_request_id(), + call_method=handle_options.method_name, + route=_request_context.route, + app_name=_request_context.app_name, + multiplexed_model_id=handle_options.multiplexed_model_id, + is_streaming=handle_options.stream, + _request_protocol=request_protocol, + grpc_context=_request_context.grpc_context, + _by_reference=True, + ) + + +def _get_node_id_and_az() -> Tuple[str, Optional[str]]: + node_id = ray.get_runtime_context().get_node_id() + try: + cluster_node_info_cache = create_cluster_node_info_cache( + GcsClient(address=ray.get_runtime_context().gcs_address) + ) + cluster_node_info_cache.update() + az = cluster_node_info_cache.get_node_az(node_id) + except Exception: + az = None + + return node_id, az + + +# Interface definition for create_router. +CreateRouterCallable = Callable[[str, DeploymentID, InitHandleOptions], Router] + + +def create_router( + handle_id: str, + deployment_id: DeploymentID, + handle_options: InitHandleOptions, + request_router_class: Optional[Callable] = None, +) -> Router: + # NOTE(edoakes): this is lazy due to a nasty circular import that should be fixed. + from ray.serve.context import _get_global_client + + actor_id = get_current_actor_id() + node_id, availability_zone = _get_node_id_and_az() + controller_handle = _get_global_client()._controller + is_inside_ray_client_context = inside_ray_client_context() + + return SingletonThreadRouter( + controller_handle=controller_handle, + deployment_id=deployment_id, + handle_id=handle_id, + self_actor_id=actor_id, + handle_source=handle_options._source, + request_router_class=request_router_class, + # Streaming ObjectRefGenerators are not supported in Ray Client + enable_strict_max_ongoing_requests=not is_inside_ray_client_context, + resolve_request_arg_func=resolve_deployment_response, + node_id=node_id, + availability_zone=availability_zone, + prefer_local_node_routing=handle_options._prefer_local_routing, + ) + + +def add_grpc_address(grpc_server: gRPCGenericServer, server_address: str): + """Helper function to add an address to a gRPC server.""" + grpc_server.add_insecure_port(server_address) + + +def get_proxy_handle(endpoint: DeploymentID, info: EndpointInfo): + # NOTE(zcin): needs to be lazy import due to a circular dependency. + # We should not be importing from application_state in context. + from ray.serve.context import _get_global_client + + client = _get_global_client() + handle = client.get_handle(endpoint.name, endpoint.app_name, check_exists=True) + + # NOTE(zcin): It's possible that a handle is already initialized + # if a deployment with the same name and application name was + # deleted, then redeployed later. However this is not an issue since + # we initialize all handles with the same init options. + if not handle.is_initialized: + # NOTE(zcin): since the router is eagerly initialized here, the + # proxy will receive the replica set from the controller early. + handle._init( + _prefer_local_routing=RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING, + _source=DeploymentHandleSource.PROXY, + ) + + return handle.options(stream=not info.app_is_cross_language) + + +def get_controller_impl(): + from ray.serve._private.controller import ServeController + + controller_impl = ray.remote( + name=SERVE_CONTROLLER_NAME, + namespace=SERVE_NAMESPACE, + num_cpus=0, + lifetime="detached", + max_restarts=-1, + max_task_retries=-1, + resources={HEAD_NODE_RESOURCE_NAME: 0.001}, + max_concurrency=CONTROLLER_MAX_CONCURRENCY, + enable_task_events=RAY_SERVE_ENABLE_TASK_EVENTS, + )(ServeController) + + return controller_impl diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/deploy_utils.py b/venv/lib/python3.10/site-packages/ray/serve/_private/deploy_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..75a95a6b5ef125e8ec5994c192483a0937028422 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/deploy_utils.py @@ -0,0 +1,113 @@ +import hashlib +import json +import logging +import time +from typing import Any, Dict, Optional, Union + +import ray +import ray.util.serialization_addons +from ray.serve._private.common import DeploymentID +from ray.serve._private.config import DeploymentConfig, ReplicaConfig +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve.schema import ServeApplicationSchema + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +def get_deploy_args( + name: str, + replica_config: ReplicaConfig, + ingress: bool = False, + deployment_config: Optional[Union[DeploymentConfig, Dict[str, Any]]] = None, + version: Optional[str] = None, + route_prefix: Optional[str] = None, + docs_path: Optional[str] = None, +) -> Dict: + """ + Takes a deployment's configuration, and returns the arguments needed + for the controller to deploy it. + """ + if deployment_config is None: + deployment_config = {} + + if isinstance(deployment_config, dict): + deployment_config = DeploymentConfig.parse_obj(deployment_config) + elif not isinstance(deployment_config, DeploymentConfig): + raise TypeError("config must be a DeploymentConfig or a dictionary.") + + deployment_config.version = version + + controller_deploy_args = { + "deployment_name": name, + "deployment_config_proto_bytes": deployment_config.to_proto_bytes(), + "replica_config_proto_bytes": replica_config.to_proto_bytes(), + "route_prefix": route_prefix, + "deployer_job_id": ray.get_runtime_context().get_job_id(), + "docs_path": docs_path, + "ingress": ingress, + } + + return controller_deploy_args + + +def deploy_args_to_deployment_info( + deployment_name: str, + deployment_config_proto_bytes: bytes, + replica_config_proto_bytes: bytes, + deployer_job_id: Union[str, bytes], + docs_path: Optional[str], + app_name: Optional[str] = None, + ingress: bool = False, + route_prefix: Optional[str] = None, + **kwargs, +) -> DeploymentInfo: + """Takes deployment args passed to the controller after building an application and + constructs a DeploymentInfo object. + """ + + deployment_config = DeploymentConfig.from_proto_bytes(deployment_config_proto_bytes) + version = deployment_config.version + replica_config = ReplicaConfig.from_proto_bytes( + replica_config_proto_bytes, deployment_config.needs_pickle() + ) + + # Java API passes in JobID as bytes + if isinstance(deployer_job_id, bytes): + deployer_job_id = ray.JobID.from_int( + int.from_bytes(deployer_job_id, "little") + ).hex() + + return DeploymentInfo( + actor_name=DeploymentID( + name=deployment_name, app_name=app_name + ).to_replica_actor_class_name(), + version=version, + deployment_config=deployment_config, + replica_config=replica_config, + deployer_job_id=deployer_job_id, + start_time_ms=int(time.time() * 1000), + route_prefix=route_prefix, + docs_path=docs_path, + ingress=ingress, + ) + + +def get_app_code_version(app_config: ServeApplicationSchema) -> str: + """Returns the code version of an application. + + Args: + app_config: The application config. + + Returns: a hash of the import path and (application level) runtime env representing + the code version of the application. + """ + encoded = json.dumps( + { + "import_path": app_config.import_path, + "runtime_env": app_config.runtime_env, + "args": app_config.args, + }, + sort_keys=True, + ).encode("utf-8") + return hashlib.sha1(encoded).hexdigest() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_info.py b/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_info.py new file mode 100644 index 0000000000000000000000000000000000000000..07b6a90948787a8079acb14ffea58d4dd7e011ea --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_info.py @@ -0,0 +1,172 @@ +from typing import Any, Dict, Optional + +import ray +from ray.serve._private.common import TargetCapacityDirection +from ray.serve._private.config import DeploymentConfig, ReplicaConfig +from ray.serve.generated.serve_pb2 import ( + DeploymentInfo as DeploymentInfoProto, + TargetCapacityDirection as TargetCapacityDirectionProto, +) + + +class DeploymentInfo: + def __init__( + self, + deployment_config: DeploymentConfig, + replica_config: ReplicaConfig, + start_time_ms: int, + deployer_job_id: str, + actor_name: Optional[str] = None, + version: Optional[str] = None, + end_time_ms: Optional[int] = None, + route_prefix: str = None, + docs_path: str = None, + ingress: bool = False, + target_capacity: Optional[float] = None, + target_capacity_direction: Optional[TargetCapacityDirection] = None, + ): + self.deployment_config = deployment_config + self.replica_config = replica_config + # The time when .deploy() was first called for this deployment. + self.start_time_ms = start_time_ms + self.actor_name = actor_name + self.version = version + self.deployer_job_id = deployer_job_id + # The time when this deployment was deleted. + self.end_time_ms = end_time_ms + + # ephermal state + self._cached_actor_def = None + + self.route_prefix = route_prefix + self.docs_path = docs_path + self.ingress = ingress + + self.target_capacity = target_capacity + self.target_capacity_direction = target_capacity_direction + + def __getstate__(self) -> Dict[Any, Any]: + clean_dict = self.__dict__.copy() + del clean_dict["_cached_actor_def"] + return clean_dict + + def __setstate__(self, d: Dict[Any, Any]) -> None: + self.__dict__ = d + self._cached_actor_def = None + + def update( + self, + deployment_config: DeploymentConfig = None, + replica_config: ReplicaConfig = None, + version: str = None, + route_prefix: str = None, + ) -> "DeploymentInfo": + return DeploymentInfo( + deployment_config=deployment_config or self.deployment_config, + replica_config=replica_config or self.replica_config, + start_time_ms=self.start_time_ms, + deployer_job_id=self.deployer_job_id, + actor_name=self.actor_name, + version=version or self.version, + end_time_ms=self.end_time_ms, + route_prefix=route_prefix or self.route_prefix, + docs_path=self.docs_path, + ingress=self.ingress, + target_capacity=self.target_capacity, + target_capacity_direction=self.target_capacity_direction, + ) + + def set_target_capacity( + self, + new_target_capacity: Optional[float], + new_target_capacity_direction: Optional[TargetCapacityDirection], + ): + self.target_capacity = new_target_capacity + self.target_capacity_direction = new_target_capacity_direction + + def config_changed(self, other) -> bool: + return ( + self.deployment_config != other.deployment_config + or self.replica_config.ray_actor_options + != other.replica_config.ray_actor_options + or other.version is None + or self.version != other.version + ) + + @property + def actor_def(self): + if self._cached_actor_def is None: + assert self.actor_name is not None + + # Break circular import :(. + from ray.serve._private.replica import ReplicaActor + + # Dynamically create a new class with custom name here so Ray picks it up + # correctly in actor metadata table and observability stack. + self._cached_actor_def = ray.remote( + type( + self.actor_name, + (ReplicaActor,), + dict(ReplicaActor.__dict__), + ) + ) + + return self._cached_actor_def + + @classmethod + def from_proto(cls, proto: DeploymentInfoProto): + deployment_config = ( + DeploymentConfig.from_proto(proto.deployment_config) + if proto.deployment_config + else None + ) + + target_capacity = proto.target_capacity if proto.target_capacity != -1 else None + + target_capacity_direction = TargetCapacityDirectionProto.Name( + proto.target_capacity_direction + ) + if target_capacity_direction == "UNSET": + target_capacity_direction = None + else: + target_capacity_direction = TargetCapacityDirection( + target_capacity_direction + ) + + data = { + "deployment_config": deployment_config, + "replica_config": ReplicaConfig.from_proto( + proto.replica_config, + deployment_config.needs_pickle() if deployment_config else True, + ), + "start_time_ms": proto.start_time_ms, + "actor_name": proto.actor_name if proto.actor_name != "" else None, + "version": proto.version if proto.version != "" else None, + "end_time_ms": proto.end_time_ms if proto.end_time_ms != 0 else None, + "deployer_job_id": ray.get_runtime_context().get_job_id(), + "target_capacity": target_capacity, + "target_capacity_direction": target_capacity_direction, + } + + return cls(**data) + + def to_proto(self): + data = { + "start_time_ms": self.start_time_ms, + "actor_name": self.actor_name, + "version": self.version, + "end_time_ms": self.end_time_ms, + } + if self.deployment_config: + data["deployment_config"] = self.deployment_config.to_proto() + if self.replica_config: + data["replica_config"] = self.replica_config.to_proto() + if self.target_capacity is None: + data["target_capacity"] = -1 + else: + data["target_capacity"] = self.target_capacity + if self.target_capacity_direction is None: + data["target_capacity_direction"] = TargetCapacityDirectionProto.UNSET + else: + data["target_capacity_direction"] = self.target_capacity_direction.name + return DeploymentInfoProto(**data) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_node.py b/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_node.py new file mode 100644 index 0000000000000000000000000000000000000000..375c49e830c4788d973c555e0ede3d5f1c883730 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_node.py @@ -0,0 +1,56 @@ +from typing import Any, Dict, List, Optional, Tuple + +from ray.dag import DAGNode +from ray.dag.format_utils import get_dag_node_str +from ray.serve.deployment import Deployment +from ray.serve.handle import DeploymentHandle + + +class DeploymentNode(DAGNode): + """Represents a deployment node in a DAG authored Ray DAG API.""" + + def __init__( + self, + # For serve structured deployment, deployment body can be import path + # to the class or function instead. + deployment: Deployment, + app_name: str, + deployment_init_args: Tuple[Any], + deployment_init_kwargs: Dict[str, Any], + ray_actor_options: Dict[str, Any], + other_args_to_resolve: Optional[Dict[str, Any]] = None, + ): + # Assign instance variables in base class constructor. + super().__init__( + deployment_init_args, + deployment_init_kwargs, + ray_actor_options, + other_args_to_resolve=other_args_to_resolve, + ) + self._app_name = app_name + self._deployment = deployment + self._deployment_handle = DeploymentHandle( + self._deployment.name, self._app_name + ) + + def _copy_impl( + self, + new_args: List[Any], + new_kwargs: Dict[str, Any], + new_options: Dict[str, Any], + new_other_args_to_resolve: Dict[str, Any], + ): + return DeploymentNode( + self._deployment, + self._app_name, + new_args, + new_kwargs, + new_options, + other_args_to_resolve=new_other_args_to_resolve, + ) + + def __str__(self) -> str: + return get_dag_node_str(self, str(self._deployment)) + + def get_deployment_name(self): + return self._deployment.name diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_scheduler.py b/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..473044a657d74886fb3a2dc184e3d7ae2e234517 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_scheduler.py @@ -0,0 +1,813 @@ +import copy +import logging +import sys +from abc import ABC, abstractmethod +from collections import defaultdict +from dataclasses import dataclass +from enum import Enum +from functools import total_ordering +from typing import Any, Callable, Dict, List, Optional, Set, Tuple + +import ray +from ray.serve._private.cluster_node_info_cache import ClusterNodeInfoCache +from ray.serve._private.common import ( + CreatePlacementGroupRequest, + DeploymentID, + ReplicaID, +) +from ray.serve._private.config import ReplicaConfig +from ray.serve._private.constants import ( + RAY_SERVE_HIGH_PRIORITY_CUSTOM_RESOURCES, + RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY, + SERVE_LOGGER_NAME, +) +from ray.util.scheduling_strategies import ( + LabelMatchExpressionsT, + NodeAffinitySchedulingStrategy, + NodeLabelSchedulingStrategy, + PlacementGroupSchedulingStrategy, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class SpreadDeploymentSchedulingPolicy: + """A scheduling policy that spreads replicas with best effort.""" + + pass + + +@total_ordering +class Resources(dict): + # Custom resource priority from environment variable + CUSTOM_PRIORITY: List[str] = RAY_SERVE_HIGH_PRIORITY_CUSTOM_RESOURCES + EPSILON = 1e-9 + + def get(self, key: str): + val = super().get(key) + if val is not None: + return val + + # Implicit resources by default have 1 total + if key.startswith(ray._raylet.IMPLICIT_RESOURCE_PREFIX): + return 1 + + # Otherwise by default there is 0 of this resource + return 0 + + def can_fit(self, other): + keys = set(self.keys()) | set(other.keys()) + # We add a small epsilon to avoid floating point precision issues. + return all(self.get(k) + self.EPSILON >= other.get(k) for k in keys) + + def __eq__(self, other): + keys = set(self.keys()) | set(other.keys()) + return all([self.get(k) == other.get(k) for k in keys]) + + def __add__(self, other): + keys = set(self.keys()) | set(other.keys()) + + kwargs = dict() + for key in keys: + if key.startswith(ray._raylet.IMPLICIT_RESOURCE_PREFIX): + kwargs[key] = min(1.0, self.get(key) + other.get(key)) + else: + kwargs[key] = self.get(key) + other.get(key) + + return Resources(kwargs) + + def __sub__(self, other): + keys = set(self.keys()) | set(other.keys()) + kwargs = {key: self.get(key) - other.get(key) for key in keys} + return Resources(kwargs) + + def __lt__(self, other): + """Determines priority when sorting a list of SoftResources. + 1. Custom resources defined in RAY_SERVE_HIGH_PRIORITY_CUSTOM_RESOURCES (sorted by priority) + 2. GPU + 3. CPU + 4. memory + 5. Other custom resources + This means a resource with a larger number of high-priority resources is always + sorted higher than one with fewer, regardless of other types. + """ + + keys = set(self.keys()) | set(other.keys()) + custom_keys = keys - {"GPU", "CPU", "memory"} + + for key in self.CUSTOM_PRIORITY: + if self.get(key) < other.get(key): + return True + elif self.get(key) > other.get(key): + return False + + if self.get("GPU") < other.get("GPU"): + return True + elif self.get("GPU") > other.get("GPU"): + return False + + if self.get("CPU") < other.get("CPU"): + return True + elif self.get("CPU") > other.get("CPU"): + return False + + if self.get("memory") < other.get("memory"): + return True + elif self.get("memory") > other.get("memory"): + return False + + for key in custom_keys - set(self.CUSTOM_PRIORITY): + if self.get(key) < other.get(key): + return True + elif self.get(key) > other.get(key): + return False + + return False + + +class ReplicaSchedulingRequestStatus(str, Enum): + """The status of a replica scheduling request.""" + + IN_PROGRESS = "IN_PROGRESS" + SUCCEEDED = "SUCCEEDED" + ACTOR_CREATION_FAILED = "ACTOR_CREATION_FAILED" + PLACEMENT_GROUP_CREATION_FAILED = "PLACEMENT_GROUP_CREATION_FAILED" + + +@dataclass +class ReplicaSchedulingRequest: + """Request to schedule a single replica. + + The scheduler is responsible for scheduling + based on the deployment scheduling policy. + """ + + replica_id: ReplicaID + actor_def: ray.actor.ActorClass + actor_resources: Dict + actor_options: Dict + actor_init_args: Tuple + on_scheduled: Callable + status: ReplicaSchedulingRequestStatus = ReplicaSchedulingRequestStatus.IN_PROGRESS + # Placement group bundles and strategy *for this replica*. + # These are optional: by default replicas do not have a placement group. + placement_group_bundles: Optional[List[Dict[str, float]]] = None + placement_group_strategy: Optional[str] = None + max_replicas_per_node: Optional[int] = None + + @property + def required_resources(self) -> Resources: + """The resources required to schedule this replica on a node. + + If this replica uses a strict pack placement group, the + required resources is the sum of the placement group bundles. + Otherwise, required resources is simply the actor resources. + """ + + if ( + self.placement_group_bundles is not None + and self.placement_group_strategy == "STRICT_PACK" + ): + return sum( + [Resources(bundle) for bundle in self.placement_group_bundles], + Resources(), + ) + else: + required = Resources(self.actor_resources) + + # Using implicit resource (resources that every node + # implicitly has and total is 1) + # to limit the number of replicas on a single node. + if self.max_replicas_per_node is not None: + deployment_id = self.replica_id.deployment_id + implicit_resource = ( + f"{ray._raylet.IMPLICIT_RESOURCE_PREFIX}" + f"{deployment_id.app_name}:{deployment_id.name}" + ) + required[implicit_resource] = 1.0 / self.max_replicas_per_node + + return required + + +@dataclass +class DeploymentDownscaleRequest: + """Request to stop a certain number of replicas. + + The scheduler is responsible for + choosing the replicas to stop. + """ + + deployment_id: DeploymentID + num_to_stop: int + + +@dataclass +class DeploymentSchedulingInfo: + deployment_id: DeploymentID + scheduling_policy: Any + actor_resources: Optional[Resources] = None + placement_group_bundles: Optional[List[Resources]] = None + placement_group_strategy: Optional[str] = None + max_replicas_per_node: Optional[int] = None + + @property + def required_resources(self) -> Resources: + """The resources required to schedule a replica of this deployment on a node. + + If this replicas uses a strict pack placement group, the + required resources is the sum of the placement group bundles. + Otherwise, required resources is simply the actor resources. + """ + + if ( + self.placement_group_bundles is not None + and self.placement_group_strategy == "STRICT_PACK" + ): + return sum(self.placement_group_bundles, Resources()) + else: + required = self.actor_resources + + # Using implicit resource (resources that every node + # implicitly has and total is 1) + # to limit the number of replicas on a single node. + if self.max_replicas_per_node: + implicit_resource = ( + f"{ray._raylet.IMPLICIT_RESOURCE_PREFIX}" + f"{self.deployment_id.app_name}:{self.deployment_id.name}" + ) + required[implicit_resource] = 1.0 / self.max_replicas_per_node + + return required + + def is_non_strict_pack_pg(self) -> bool: + return ( + self.placement_group_bundles is not None + and self.placement_group_strategy != "STRICT_PACK" + ) + + +@dataclass +class LaunchingReplicaInfo: + """Describes a replica for which a schedule request has been sent to + core but has not been scheduled (placed on a node) yet. + + Args: + target_node_id: The exact node that's been requested for this + replica. This is best effort and may not be fulfilled. + target_labels: The node labels that have been requested for this + replica. This is best effort and may not be fulfilled. + """ + + target_node_id: Optional[str] = None + target_labels: Optional[Dict[str, Any]] = None + + +def _flatten( + deployment_to_replicas: Dict[DeploymentID, Dict[ReplicaID, Any]] +) -> Dict[ReplicaID, Any]: + """Flattens a dict of {deployment_id: {replica_id: val}} to {replica_id: val}.""" + + return { + replica_id: val + for replicas in deployment_to_replicas.values() + for replica_id, val in replicas.items() + } + + +class DeploymentScheduler(ABC): + """A centralized scheduler for all Serve deployments. + + It makes a batch of scheduling decisions in each update cycle. + """ + + def __init__( + self, + cluster_node_info_cache: ClusterNodeInfoCache, + head_node_id: str, + create_placement_group_fn: Callable, + ): + # {deployment_id: scheduling_policy} + self._deployments: Dict[DeploymentID, DeploymentSchedulingInfo] = {} + # Replicas that are waiting to be scheduled. + # {deployment_id: {replica_id: deployment_upscale_request}} + self._pending_replicas: Dict[ + DeploymentID, Dict[str, ReplicaSchedulingRequest] + ] = defaultdict(dict) + # Replicas that are being scheduled. + # The underlying actors have been submitted. + # {deployment_id: {replica_id: target_node_id}} + self._launching_replicas: Dict[ + DeploymentID, Dict[str, LaunchingReplicaInfo] + ] = defaultdict(dict) + # Replicas that are recovering. + # We don't know where those replicas are running. + # {deployment_id: {replica_id}} + self._recovering_replicas = defaultdict(set) + # Replicas that are running. + # We know where those replicas are running. + # {deployment_id: {replica_id: running_node_id}} + self._running_replicas = defaultdict(dict) + + self._cluster_node_info_cache = cluster_node_info_cache + self._head_node_id = head_node_id + self._create_placement_group_fn = create_placement_group_fn + + def on_deployment_created( + self, + deployment_id: DeploymentID, + scheduling_policy: SpreadDeploymentSchedulingPolicy, + ) -> None: + """Called whenever a new deployment is created.""" + assert deployment_id not in self._pending_replicas + assert deployment_id not in self._launching_replicas + assert deployment_id not in self._recovering_replicas + assert deployment_id not in self._running_replicas + self._deployments[deployment_id] = DeploymentSchedulingInfo( + deployment_id=deployment_id, scheduling_policy=scheduling_policy + ) + + def on_deployment_deployed( + self, + deployment_id: DeploymentID, + replica_config: ReplicaConfig, + ) -> None: + assert deployment_id in self._deployments + + info = self._deployments[deployment_id] + info.actor_resources = Resources(replica_config.resource_dict) + info.max_replicas_per_node = replica_config.max_replicas_per_node + if replica_config.placement_group_bundles: + info.placement_group_bundles = [ + Resources(bundle) for bundle in replica_config.placement_group_bundles + ] + if replica_config.placement_group_strategy: + info.placement_group_strategy = replica_config.placement_group_strategy + + def on_deployment_deleted(self, deployment_id: DeploymentID) -> None: + """Called whenever a deployment is deleted.""" + assert not self._pending_replicas[deployment_id] + self._pending_replicas.pop(deployment_id, None) + + assert not self._launching_replicas[deployment_id] + self._launching_replicas.pop(deployment_id, None) + + assert not self._recovering_replicas[deployment_id] + self._recovering_replicas.pop(deployment_id, None) + + assert not self._running_replicas[deployment_id] + self._running_replicas.pop(deployment_id, None) + + del self._deployments[deployment_id] + + def on_replica_stopping(self, replica_id: ReplicaID) -> None: + """Called whenever a deployment replica is being stopped.""" + deployment_id = replica_id.deployment_id + self._pending_replicas[deployment_id].pop(replica_id, None) + self._launching_replicas[deployment_id].pop(replica_id, None) + self._recovering_replicas[deployment_id].discard(replica_id) + self._running_replicas[deployment_id].pop(replica_id, None) + + def on_replica_running(self, replica_id: ReplicaID, node_id: str) -> None: + """Called whenever a deployment replica is running with a known node id.""" + deployment_id = replica_id.deployment_id + assert replica_id not in self._pending_replicas[deployment_id] + + self._launching_replicas[deployment_id].pop(replica_id, None) + self._recovering_replicas[deployment_id].discard(replica_id) + + self._running_replicas[deployment_id][replica_id] = node_id + + def on_replica_recovering(self, replica_id: ReplicaID) -> None: + """Called whenever a deployment replica is recovering.""" + deployment_id = replica_id.deployment_id + assert replica_id not in self._pending_replicas[deployment_id] + assert replica_id not in self._launching_replicas[deployment_id] + assert replica_id not in self._running_replicas[deployment_id] + assert replica_id not in self._recovering_replicas[deployment_id] + + self._recovering_replicas[deployment_id].add(replica_id) + + def _on_replica_launching( + self, + replica_id: ReplicaID, + target_node_id: Optional[str] = None, + target_labels: Optional[Dict[str, Any]] = None, + ): + deployment_id = replica_id.deployment_id + self._launching_replicas[deployment_id][replica_id] = LaunchingReplicaInfo( + target_node_id=target_node_id, target_labels=target_labels + ) + + def _get_node_to_running_replicas( + self, deployment_id: Optional[DeploymentID] = None + ) -> Dict[str, Set[ReplicaID]]: + res = defaultdict(set) + if deployment_id: + for replica_id, node_id in self._running_replicas[deployment_id].items(): + res[node_id].add(replica_id) + else: + for _, replicas in self._running_replicas.items(): + for replica_id, node_id in replicas.items(): + res[node_id].add(replica_id) + + return res + + def _get_available_resources_per_node(self) -> Dict[str, Resources]: + """Gets current available resources per node. + + This returns a conservative view of the available resources + currently in the cluster. It returns the minimum of: + + 1. The available resources per node fetched and cached from the + GCS every control loop. + 2. The remaining resources left over on each node after + subtracting the resources taken up by running (already + scheduled by core) and launching (to-be-scheduled and soft + targeting that node) replicas. + + Note that (1) may not be accurate because it uses cached info + and there is a delay from fetching data from GCS, and (2) may + not be accurate because there can be other actors (not replicas) + running in the cluster, and launching replicas may not end up on + the node we're targeting. So the information returned from this + method is only best effort. + """ + + available_resources = ( + self._cluster_node_info_cache.get_available_resources_per_node() + ) + total_resources = self._cluster_node_info_cache.get_total_resources_per_node() + + gcs_info = {node_id: Resources(r) for node_id, r in available_resources.items()} + + # Manually calculate available resources per node by subtracting + # launching and running replicas from total resources + total_minus_replicas = { + node_id: Resources(resources) + for node_id, resources in total_resources.items() + } + for deployment_id, replicas in self._launching_replicas.items(): + deployment = self._deployments[deployment_id] + for info in replicas.values(): + target_node_id = info.target_node_id + if not target_node_id or target_node_id not in total_minus_replicas: + continue + + total_minus_replicas[target_node_id] -= deployment.required_resources + + for deployment_id, replicas in self._running_replicas.items(): + deployment = self._deployments[deployment_id] + for node_id in replicas.values(): + if node_id not in total_minus_replicas: + continue + + total_minus_replicas[node_id] -= deployment.required_resources + + def custom_min(a: Resources, b: Resources): + keys = set(a.keys()) | set(b.keys()) + res = Resources() + for key in keys: + res[key] = min(a.get(key), b.get(key)) + return res + + # Filter by active node ids (alive but not draining) + return { + node_id: custom_min( + gcs_info.get(node_id, Resources()), + total_minus_replicas.get(node_id, Resources()), + ) + for node_id in self._cluster_node_info_cache.get_active_node_ids() + } + + def _best_fit_node( + self, required_resources: Resources, available_resources: Dict[str, Resources] + ) -> Optional[str]: + """Chooses a node using best fit strategy. + + This strategy picks the node where, if the required resources + were to be scheduled on that node, it will leave the smallest + remaining space. This minimizes fragmentation of resources. + """ + + min_remaining_space = None + chosen_node = None + + for node_id in available_resources: + if not available_resources[node_id].can_fit(required_resources): + continue + + # TODO(zcin): We can make this better by only considering + # custom resources that required_resources has. + remaining_space = available_resources[node_id] - required_resources + if min_remaining_space is None or remaining_space < min_remaining_space: + min_remaining_space = remaining_space + chosen_node = node_id + + return chosen_node + + @abstractmethod + def schedule( + self, + upscales: Dict[DeploymentID, List[ReplicaSchedulingRequest]], + downscales: Dict[DeploymentID, DeploymentDownscaleRequest], + ) -> Dict[DeploymentID, Set[ReplicaID]]: + """Called for each update cycle to do batch scheduling. + + Args: + upscales: a dict of deployment name to a list of replicas to schedule. + downscales: a dict of deployment name to a downscale request. + + Returns: + The name of replicas to stop for each deployment. + """ + raise NotImplementedError + + def _schedule_replica( + self, + scheduling_request: ReplicaSchedulingRequest, + default_scheduling_strategy: str, + target_node_id: Optional[str] = None, + target_labels: Optional[LabelMatchExpressionsT] = None, + ): + """Schedule a replica from a scheduling request. + + The following special scheduling strategies will be used, in + order of highest to lowest priority. + 1. If a replica requires placement groups, we will choose to use + a `PlacementGroupSchedulingStrategy`. This can also take a + target node into consideration (soft target), if provided. + However it cannot take into account target labels. + 2. If a `target_node_id` is provided, we will choose to use a + `NodeAffinitySchedulingStrategy`. + 3. If `target_labels` is provided, we will choose to use a + `NodeLabelSchedulingStrategy`. + + Args: + scheduling_request: A request to schedule a replica. + default_scheduling_strategy: The scheduling strategy to fall + back to if no special scheduling strategy is necessary. + target_node_id: Attempt to schedule this replica onto this + target node. + target_labels: Attempt to schedule this replica onto nodes + with these target labels. + """ + + replica_id = scheduling_request.replica_id + deployment_id = replica_id.deployment_id + placement_group = None + + scheduling_strategy = default_scheduling_strategy + if scheduling_request.placement_group_bundles is not None: + placement_group_strategy = ( + scheduling_request.placement_group_strategy + if scheduling_request.placement_group_strategy + else "PACK" + ) + try: + pg = self._create_placement_group_fn( + CreatePlacementGroupRequest( + bundles=scheduling_request.placement_group_bundles, + strategy=placement_group_strategy, + target_node_id=target_node_id, + name=scheduling_request.actor_options["name"], + ) + ) + except Exception: + # We add a defensive exception here, so the controller can + # make progress even if the placement group isn't created. + # See https://github.com/ray-project/ray/issues/43888. + logger.exception( + f"Failed to create a placement group for {replica_id}." + ) + scheduling_request.status = ( + ReplicaSchedulingRequestStatus.PLACEMENT_GROUP_CREATION_FAILED + ) + return + scheduling_strategy = PlacementGroupSchedulingStrategy( + placement_group=pg, + placement_group_capture_child_tasks=True, + ) + target_labels = None + elif target_node_id is not None: + scheduling_strategy = NodeAffinitySchedulingStrategy( + node_id=target_node_id, soft=True, _spill_on_unavailable=True + ) + target_labels = None + elif target_labels is not None: + scheduling_strategy = NodeLabelSchedulingStrategy( + hard={}, soft=target_labels + ) + target_node_id = None + + actor_options = copy.copy(scheduling_request.actor_options) + if scheduling_request.max_replicas_per_node is not None: + if "resources" not in actor_options: + actor_options["resources"] = {} + # Using implicit resource (resources that every node + # implicitly has and total is 1) + # to limit the number of replicas on a single node. + actor_options["resources"][ + f"{ray._raylet.IMPLICIT_RESOURCE_PREFIX}" + f"{deployment_id.app_name}:{deployment_id.name}" + ] = (1.0 / scheduling_request.max_replicas_per_node) + + try: + actor_handle = scheduling_request.actor_def.options( + scheduling_strategy=scheduling_strategy, + **actor_options, + ).remote(*scheduling_request.actor_init_args) + except Exception: + # We add a defensive exception here, so the controller can + # make progress even if the actor options are misconfigured. + logger.exception(f"Failed to create an actor for {replica_id}.") + scheduling_request.status = ( + ReplicaSchedulingRequestStatus.ACTOR_CREATION_FAILED + ) + return + + del self._pending_replicas[deployment_id][replica_id] + self._on_replica_launching( + replica_id, target_node_id=target_node_id, target_labels=target_labels + ) + + if isinstance(scheduling_strategy, PlacementGroupSchedulingStrategy): + placement_group = scheduling_strategy.placement_group + + scheduling_request.status = ReplicaSchedulingRequestStatus.SUCCEEDED + scheduling_request.on_scheduled(actor_handle, placement_group=placement_group) + + @abstractmethod + def get_node_to_compact( + self, allow_new_compaction: bool + ) -> Optional[Tuple[str, float]]: + """Returns a node ID to be compacted and a compaction deadlne.""" + raise NotImplementedError + + +class DefaultDeploymentScheduler(DeploymentScheduler): + def schedule( + self, + upscales: Dict[DeploymentID, List[ReplicaSchedulingRequest]], + downscales: Dict[DeploymentID, DeploymentDownscaleRequest], + ) -> Dict[DeploymentID, Set[ReplicaID]]: + """Called for each update cycle to do batch scheduling. + + Args: + upscales: a dict of deployment name to a list of replicas to schedule. + downscales: a dict of deployment name to a downscale request. + + Returns: + The IDs of replicas to stop for each deployment. + """ + for upscale in upscales.values(): + for scheduling_request in upscale: + replica_id = scheduling_request.replica_id + deployment_id = replica_id.deployment_id + self._pending_replicas[deployment_id][replica_id] = scheduling_request + + non_strict_pack_pgs_exist = any( + d.is_non_strict_pack_pg() for d in self._deployments.values() + ) + # Schedule replicas using compact strategy. + if RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY and not non_strict_pack_pgs_exist: + # Flatten dict of deployment replicas into all replicas, + # then sort by decreasing resource size + all_scheduling_requests = sorted( + _flatten(self._pending_replicas).values(), + key=lambda r: r.required_resources, + reverse=True, + ) + + # Schedule each replica + for scheduling_request in all_scheduling_requests: + target_node = self._find_best_available_node( + scheduling_request.required_resources, + self._get_available_resources_per_node(), + ) + + self._schedule_replica( + scheduling_request, + default_scheduling_strategy="DEFAULT", + target_node_id=target_node, + ) + + else: + for pending_replicas in self._pending_replicas.values(): + if not pending_replicas: + continue + + for scheduling_request in list(pending_replicas.values()): + self._schedule_replica( + scheduling_request=scheduling_request, + default_scheduling_strategy="SPREAD", + ) + + deployment_to_replicas_to_stop = {} + for downscale in downscales.values(): + deployment_to_replicas_to_stop[ + downscale.deployment_id + ] = self._get_replicas_to_stop( + downscale.deployment_id, downscale.num_to_stop + ) + + return deployment_to_replicas_to_stop + + def _get_replicas_to_stop( + self, deployment_id: DeploymentID, max_num_to_stop: int + ) -> Set[ReplicaID]: + """Prioritize replicas running on a node with fewest replicas of + all deployments. + + This algorithm helps to scale down more intelligently because it can + relinquish nodes faster. Note that this algorithm doesn't consider + other non-serve actors on the same node. See more at + https://github.com/ray-project/ray/issues/20599. + """ + replicas_to_stop = set() + + # Replicas not in running state don't have node id. + # We will prioritize those first. + pending_launching_recovering_replicas = set().union( + self._pending_replicas[deployment_id].keys(), + self._launching_replicas[deployment_id].keys(), + self._recovering_replicas[deployment_id], + ) + for ( + pending_launching_recovering_replica + ) in pending_launching_recovering_replicas: + if len(replicas_to_stop) == max_num_to_stop: + return replicas_to_stop + else: + replicas_to_stop.add(pending_launching_recovering_replica) + + node_to_running_replicas_of_target_deployment = ( + self._get_node_to_running_replicas(deployment_id) + ) + node_to_running_replicas_of_all_deployments = ( + self._get_node_to_running_replicas() + ) + + # Replicas on the head node has the lowest priority for downscaling + # since we cannot relinquish the head node. + def key(node_and_num_running_replicas_of_all_deployments): + return ( + len(node_and_num_running_replicas_of_all_deployments[1]) + if node_and_num_running_replicas_of_all_deployments[0] + != self._head_node_id + else sys.maxsize + ) + + for node_id, _ in sorted( + node_to_running_replicas_of_all_deployments.items(), key=key + ): + if node_id not in node_to_running_replicas_of_target_deployment: + continue + for running_replica in node_to_running_replicas_of_target_deployment[ + node_id + ]: + if len(replicas_to_stop) == max_num_to_stop: + return replicas_to_stop + else: + replicas_to_stop.add(running_replica) + + return replicas_to_stop + + def _find_best_available_node( + self, + required_resources: Resources, + available_resources_per_node: Dict[str, Resources], + ) -> Optional[str]: + """Chooses best available node to schedule the required resources. + + If there are available nodes, returns the node ID of the best + available node, minimizing fragmentation. Prefers non-idle nodes + over idle nodes. + """ + + node_to_running_replicas = self._get_node_to_running_replicas() + + non_idle_nodes = { + node_id: res + for node_id, res in available_resources_per_node.items() + if len(node_to_running_replicas.get(node_id, set())) > 0 + } + idle_nodes = { + node_id: res + for node_id, res in available_resources_per_node.items() + if len(node_to_running_replicas.get(node_id, set())) == 0 + } + + # 1. Prefer non-idle nodes + chosen_node = self._best_fit_node(required_resources, non_idle_nodes) + if chosen_node: + return chosen_node + + # 2. Consider idle nodes last + chosen_node = self._best_fit_node(required_resources, idle_nodes) + if chosen_node: + return chosen_node + + def get_node_to_compact( + self, allow_new_compaction: bool + ) -> Optional[Tuple[str, float]]: + return None diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_state.py b/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_state.py new file mode 100644 index 0000000000000000000000000000000000000000..a700bee51e08a9d24b99b93e555fac46ed189506 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/deployment_state.py @@ -0,0 +1,3004 @@ +import json +import logging +import math +import os +import random +import time +import traceback +from collections import defaultdict +from copy import copy +from dataclasses import dataclass +from enum import Enum +from typing import Any, Callable, Dict, List, Optional, Set, Tuple + +import ray +from ray import ObjectRef, cloudpickle +from ray._private import ray_constants +from ray.actor import ActorHandle +from ray.exceptions import RayActorError, RayError, RayTaskError, RuntimeEnvSetupError +from ray.serve import metrics +from ray.serve._private import default_impl +from ray.serve._private.autoscaling_state import AutoscalingStateManager +from ray.serve._private.cluster_node_info_cache import ClusterNodeInfoCache +from ray.serve._private.common import ( + DeploymentID, + DeploymentStatus, + DeploymentStatusInfo, + DeploymentStatusInternalTrigger, + DeploymentStatusTrigger, + DeploymentTargetInfo, + Duration, + ReplicaID, + ReplicaState, + RequestRoutingInfo, + RunningReplicaInfo, +) +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import ( + MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT, + MAX_PER_REPLICA_RETRY_COUNT, + RAY_SERVE_ENABLE_TASK_EVENTS, + RAY_SERVE_FORCE_STOP_UNHEALTHY_REPLICAS, + RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY, + REPLICA_HEALTH_CHECK_UNHEALTHY_THRESHOLD, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.deployment_scheduler import ( + DeploymentDownscaleRequest, + DeploymentScheduler, + ReplicaSchedulingRequest, + ReplicaSchedulingRequestStatus, + SpreadDeploymentSchedulingPolicy, +) +from ray.serve._private.long_poll import LongPollHost, LongPollNamespace +from ray.serve._private.storage.kv_store import KVStoreBase +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + JavaActorHandleProxy, + check_obj_ref_ready_nowait, + get_capacity_adjusted_num_replicas, + get_random_string, + msgpack_deserialize, + msgpack_serialize, +) +from ray.serve._private.version import DeploymentVersion +from ray.serve.generated.serve_pb2 import DeploymentLanguage +from ray.serve.schema import ( + DeploymentDetails, + ReplicaDetails, + _deployment_info_to_schema, +) +from ray.util.placement_group import PlacementGroup + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class ReplicaStartupStatus(Enum): + PENDING_ALLOCATION = 1 + PENDING_INITIALIZATION = 2 + SUCCEEDED = 3 + FAILED = 4 + + +class ReplicaHealthCheckResponse(Enum): + NONE = 1 + SUCCEEDED = 2 + APP_FAILURE = 3 + ACTOR_CRASHED = 4 + + +@dataclass +class DeploymentTargetState: + """The current goal state for a deployment. + + info: contains the information needed to initialize a replica. + target_num_replicas: the number of replicas to run. This should already + be adjusted by the target_capacity. + version: the goal version of the deployment. + deleting: whether the deployment is being deleted. + """ + + info: Optional[DeploymentInfo] + target_num_replicas: int + version: Optional[DeploymentVersion] + deleting: bool + + @classmethod + def default(cls) -> "DeploymentTargetState": + return cls(None, -1, None, False) + + @classmethod + def create( + cls, + info: DeploymentInfo, + target_num_replicas: int, + *, + deleting: bool = False, + ) -> "DeploymentTargetState": + if deleting: + if target_num_replicas != 0: + raise ValueError( + "target_num_replicas must be 0 when setting target state " + f"to deleting. Got {target_num_replicas} instead." + ) + + version = DeploymentVersion( + info.version, + deployment_config=info.deployment_config, + ray_actor_options=info.replica_config.ray_actor_options, + placement_group_bundles=info.replica_config.placement_group_bundles, + placement_group_strategy=info.replica_config.placement_group_strategy, + max_replicas_per_node=info.replica_config.max_replicas_per_node, + ) + + return cls(info, target_num_replicas, version, deleting) + + def is_scaled_copy_of(self, other_target_state: "DeploymentTargetState") -> bool: + """Checks if this target state is a scaled copy of another target state. + + A target state is a scaled copy of another target state if all + configurable info is identical, other than target_num_replicas. + + Returns: True if this target state contains a non-None DeploymentInfo + and is a scaled copy of the other target state. + """ + + if other_target_state.info is None: + return False + + return all( + [ + self.info.replica_config.ray_actor_options + == other_target_state.info.replica_config.ray_actor_options, + self.info.replica_config.placement_group_bundles + == other_target_state.info.replica_config.placement_group_bundles, + self.info.replica_config.placement_group_strategy + == other_target_state.info.replica_config.placement_group_strategy, + self.info.replica_config.max_replicas_per_node + == other_target_state.info.replica_config.max_replicas_per_node, + self.info.deployment_config.dict(exclude={"num_replicas"}) + == other_target_state.info.deployment_config.dict( + exclude={"num_replicas"} + ), + # TODO(zcin): version can be None, this is from an outdated codepath. + # We should remove outdated code, so version can never be None. + self.version, + self.version == other_target_state.version, + ] + ) + + +@dataclass +class DeploymentStateUpdateResult: + deleted: bool + any_replicas_recovering: bool + upscale: List[ReplicaSchedulingRequest] + downscale: Optional[DeploymentDownscaleRequest] + + +CHECKPOINT_KEY = "serve-deployment-state-checkpoint" +SLOW_STARTUP_WARNING_S = int(os.environ.get("SERVE_SLOW_STARTUP_WARNING_S", 30)) +SLOW_STARTUP_WARNING_PERIOD_S = int( + os.environ.get("SERVE_SLOW_STARTUP_WARNING_PERIOD_S", 30) +) + +ALL_REPLICA_STATES = list(ReplicaState) +_SCALING_LOG_ENABLED = os.environ.get("SERVE_ENABLE_SCALING_LOG", "0") != "0" +# Feature flag to disable forcibly shutting down replicas. +RAY_SERVE_DISABLE_SHUTTING_DOWN_INGRESS_REPLICAS_FORCEFULLY = ( + os.environ.get("RAY_SERVE_DISABLE_SHUTTING_DOWN_INGRESS_REPLICAS_FORCEFULLY", "0") + == "1" +) + + +def print_verbose_scaling_log(): + assert _SCALING_LOG_ENABLED + + log_path = "/tmp/ray/session_latest/logs/monitor.log" + last_n_lines = 50 + autoscaler_log_last_n_lines = [] + if os.path.exists(log_path): + with open(log_path) as f: + autoscaler_log_last_n_lines = f.readlines()[-last_n_lines:] + + debug_info = { + "nodes": ray.nodes(), + "available_resources": ray.available_resources(), + "total_resources": ray.cluster_resources(), + "autoscaler_logs": autoscaler_log_last_n_lines, + } + logger.error(f"Scaling information\n{json.dumps(debug_info, indent=2)}") + + +class ActorReplicaWrapper: + """Wraps a Ray actor for a deployment replica. + + This is primarily defined so that we can mock out actual Ray operations + for unit testing. + + *All Ray API calls should be made here, not in DeploymentState.* + """ + + def __init__( + self, + replica_id: ReplicaID, + version: DeploymentVersion, + ): + self._replica_id = replica_id + self._deployment_id = replica_id.deployment_id + self._actor_name = replica_id.to_full_id_str() + + # Populated in either self.start() or self.recover() + self._allocated_obj_ref: ObjectRef = None + self._ready_obj_ref: ObjectRef = None + + self._actor_resources: Dict[str, float] = None + # If the replica is being started, this will be the true version + # If the replica is being recovered, this will be the target + # version, which may be inconsistent with the actual replica + # version. If so, the actual version will be updated later after + # recover() and check_ready() + self._version: DeploymentVersion = version + self._healthy: bool = True + self._health_check_ref: Optional[ObjectRef] = None + self._last_health_check_time: float = 0.0 + self._consecutive_health_check_failures = 0 + self._initialization_latency_s: Optional[float] = None + self._port: Optional[int] = None + self._docs_path: Optional[str] = None + # Populated in `on_scheduled` or `recover`. + self._actor_handle: ActorHandle = None + self._placement_group: PlacementGroup = None + + # Populated after replica is allocated. + self._pid: int = None + self._actor_id: str = None + self._worker_id: str = None + self._node_id: str = None + self._node_ip: str = None + self._node_instance_id: str = None + self._log_file_path: str = None + + # Populated in self.stop(). + self._graceful_shutdown_ref: ObjectRef = None + + # todo: will be confused with deployment_config.is_cross_language + self._is_cross_language = False + self._deployment_is_cross_language = False + self._routing_stats: Dict[str, Any] = {} + self._record_routing_stats_ref: Optional[ObjectRef] = None + self._last_record_routing_stats_time: float = 0.0 + self._ingress: bool = False + + @property + def replica_id(self) -> str: + return self._replica_id + + @property + def deployment_name(self) -> str: + return self._deployment_id.name + + @property + def app_name(self) -> str: + return self._deployment_id.app_name + + @property + def is_cross_language(self) -> bool: + return self._is_cross_language + + @property + def actor_handle(self) -> Optional[ActorHandle]: + if not self._actor_handle: + try: + self._actor_handle = ray.get_actor( + self._actor_name, namespace=SERVE_NAMESPACE + ) + except ValueError: + self._actor_handle = None + + if self._is_cross_language: + assert isinstance(self._actor_handle, JavaActorHandleProxy) + return self._actor_handle.handle + + return self._actor_handle + + @property + def placement_group_bundles(self) -> Optional[List[Dict[str, float]]]: + if not self._placement_group: + return None + + return self._placement_group.bundle_specs + + @property + def version(self) -> DeploymentVersion: + """Replica version. This can be incorrect during state recovery. + + If the controller crashes and the deployment state is being + recovered, this will temporarily be the deployment-wide target + version, which may be inconsistent with the actual version + running on the replica actor. If so, the actual version will be + updated when the replica transitions from RECOVERING -> RUNNING + """ + return self._version + + @property + def deployment_config(self) -> DeploymentConfig: + """Deployment config. This can return an incorrect config during state recovery. + + If the controller hasn't yet recovered the up-to-date version + from the running replica actor, this property will return the + current target config for the deployment. + """ + return self._version.deployment_config + + @property + def docs_path(self) -> Optional[str]: + return self._docs_path + + @property + def max_ongoing_requests(self) -> int: + return self.deployment_config.max_ongoing_requests + + @property + def max_queued_requests(self) -> int: + return self.deployment_config.max_queued_requests + + @property + def graceful_shutdown_timeout_s(self) -> float: + return self.deployment_config.graceful_shutdown_timeout_s + + @property + def health_check_period_s(self) -> float: + return self.deployment_config.health_check_period_s + + @property + def health_check_timeout_s(self) -> float: + return self.deployment_config.health_check_timeout_s + + @property + def request_routing_stats_period_s(self) -> float: + return ( + self.deployment_config.request_router_config.request_routing_stats_period_s + ) + + @property + def request_routing_stats_timeout_s(self) -> float: + return ( + self.deployment_config.request_router_config.request_routing_stats_timeout_s + ) + + @property + def pid(self) -> Optional[int]: + """Returns the pid of the actor, None if not started.""" + return self._pid + + @property + def actor_id(self) -> Optional[str]: + """Returns the actor id, None if not started.""" + return self._actor_id + + @property + def worker_id(self) -> Optional[str]: + """Returns the worker id, None if not started.""" + return self._worker_id + + @property + def node_id(self) -> Optional[str]: + """Returns the node id of the actor, None if not placed.""" + return self._node_id + + @property + def node_ip(self) -> Optional[str]: + """Returns the node ip of the actor, None if not placed.""" + return self._node_ip + + @property + def node_instance_id(self) -> Optional[str]: + """Returns the node instance id of the actor, None if not placed.""" + return self._node_instance_id + + @property + def log_file_path(self) -> Optional[str]: + """Returns the relative log file path of the actor, None if not placed.""" + return self._log_file_path + + @property + def initialization_latency_s(self) -> Optional[float]: + """Returns the initialization latency for the replica actor. + + Returns None if the replica hasn't started yet. + + Note: this value isn't checkpointed, so if the controller restarts, + this value goes back to None. + """ + + return self._initialization_latency_s + + def start(self, deployment_info: DeploymentInfo) -> ReplicaSchedulingRequest: + """Start the current DeploymentReplica instance. + + The replica will be in the STARTING and PENDING_ALLOCATION states + until the deployment scheduler schedules the underlying actor. + """ + self._actor_resources = deployment_info.replica_config.resource_dict + self._ingress = deployment_info.ingress + # it is currently not possible to create a placement group + # with no resources (https://github.com/ray-project/ray/issues/20401) + self._deployment_is_cross_language = ( + deployment_info.deployment_config.is_cross_language + ) + + logger.info( + f"Starting {self.replica_id}.", + extra={"log_to_stderr": False}, + ) + + actor_def = deployment_info.actor_def + if ( + deployment_info.deployment_config.deployment_language + == DeploymentLanguage.PYTHON + ): + if deployment_info.replica_config.serialized_init_args is None: + serialized_init_args = cloudpickle.dumps(()) + else: + serialized_init_args = ( + cloudpickle.dumps( + msgpack_deserialize( + deployment_info.replica_config.serialized_init_args + ) + ) + if self._deployment_is_cross_language + else deployment_info.replica_config.serialized_init_args + ) + init_args = ( + self.replica_id, + cloudpickle.dumps(deployment_info.replica_config.deployment_def) + if self._deployment_is_cross_language + else deployment_info.replica_config.serialized_deployment_def, + serialized_init_args, + deployment_info.replica_config.serialized_init_kwargs + if deployment_info.replica_config.serialized_init_kwargs + else cloudpickle.dumps({}), + deployment_info.deployment_config.to_proto_bytes(), + self._version, + deployment_info.ingress, + deployment_info.route_prefix, + ) + # TODO(simon): unify the constructor arguments across language + elif ( + deployment_info.deployment_config.deployment_language + == DeploymentLanguage.JAVA + ): + self._is_cross_language = True + actor_def = ray.cross_language.java_actor_class( + "io.ray.serve.replica.RayServeWrappedReplica" + ) + init_args = ( + # String deploymentName, + self.deployment_name, + # String replicaID, + self.replica_id.to_full_id_str(), + # String deploymentDef + deployment_info.replica_config.deployment_def_name, + # byte[] initArgsbytes + msgpack_serialize( + cloudpickle.loads( + deployment_info.replica_config.serialized_init_args + ) + ) + if self._deployment_is_cross_language + else deployment_info.replica_config.serialized_init_args, + # byte[] deploymentConfigBytes, + deployment_info.deployment_config.to_proto_bytes(), + # byte[] deploymentVersionBytes, + self._version.to_proto().SerializeToString(), + # String controllerName + # String appName + self.app_name, + ) + + actor_options = { + "name": self._actor_name, + "namespace": SERVE_NAMESPACE, + "lifetime": "detached", + "enable_task_events": RAY_SERVE_ENABLE_TASK_EVENTS, + } + actor_options.update(deployment_info.replica_config.ray_actor_options) + + # A replica's default `max_concurrency` value can prevent it from + # respecting the configured `max_ongoing_requests`. To avoid this + # unintentional behavior, use `max_ongoing_requests` to override + # the Actor's `max_concurrency` if it is larger. + if ( + deployment_info.deployment_config.max_ongoing_requests + > ray_constants.DEFAULT_MAX_CONCURRENCY_ASYNC + ): + actor_options[ + "max_concurrency" + ] = deployment_info.deployment_config.max_ongoing_requests + + return ReplicaSchedulingRequest( + replica_id=self.replica_id, + actor_def=actor_def, + actor_resources=self._actor_resources, + actor_options=actor_options, + actor_init_args=init_args, + placement_group_bundles=( + deployment_info.replica_config.placement_group_bundles + ), + placement_group_strategy=( + deployment_info.replica_config.placement_group_strategy + ), + max_replicas_per_node=( + deployment_info.replica_config.max_replicas_per_node + ), + on_scheduled=self.on_scheduled, + ) + + def on_scheduled( + self, + actor_handle: ActorHandle, + placement_group: Optional[PlacementGroup] = None, + ): + self._actor_handle = actor_handle + self._placement_group = placement_group + + # Perform auto method name translation for java handles. + # See https://github.com/ray-project/ray/issues/21474 + deployment_config = copy(self._version.deployment_config) + deployment_config.user_config = self._format_user_config( + deployment_config.user_config + ) + if self._is_cross_language: + self._actor_handle = JavaActorHandleProxy(self._actor_handle) + self._allocated_obj_ref = self._actor_handle.is_allocated.remote() + self._ready_obj_ref = self._actor_handle.is_initialized.remote( + deployment_config.to_proto_bytes() + ) + else: + self._allocated_obj_ref = self._actor_handle.is_allocated.remote() + replica_ready_check_func = self._actor_handle.initialize_and_get_metadata + self._ready_obj_ref = replica_ready_check_func.remote( + deployment_config, + # Ensure that `is_allocated` will execute + # before `initialize_and_get_metadata`, + # because `initialize_and_get_metadata` runs + # user code that could block the replica + # asyncio loop. If that happens before `is_allocated` is executed, + # the `is_allocated` call won't be able to run. + self._allocated_obj_ref, + ) + + def _format_user_config(self, user_config: Any): + temp = copy(user_config) + if user_config is not None and self._deployment_is_cross_language: + if self._is_cross_language: + temp = msgpack_serialize(temp) + else: + temp = msgpack_deserialize(temp) + return temp + + def reconfigure(self, version: DeploymentVersion) -> bool: + """ + Update replica version. Also, updates the deployment config on the actor + behind this DeploymentReplica instance if necessary. + + Returns: whether the actor is being updated. + """ + updating = False + if self._version.requires_actor_reconfigure(version): + # Call into replica actor reconfigure() with updated user config and + # graceful_shutdown_wait_loop_s + updating = True + deployment_config = copy(version.deployment_config) + deployment_config.user_config = self._format_user_config( + deployment_config.user_config + ) + self._ready_obj_ref = self._actor_handle.reconfigure.remote( + deployment_config + ) + + self._version = version + return updating + + def recover(self) -> bool: + """Recover replica version from a live replica actor. + + When controller dies, the deployment state loses the info on the version that's + running on each individual replica actor, so as part of the recovery process, we + need to recover the version that is running on the replica actor. + + Also confirm that actor is allocated and initialized before marking as running. + + Returns: False if the replica actor is no longer alive; the + actor could have been killed in the time between when the + controller fetching all Serve actors in the cluster and when + the controller tries to recover it. Otherwise, return True. + """ + logger.info(f"Recovering {self.replica_id}.") + try: + self._actor_handle = ray.get_actor( + self._actor_name, namespace=SERVE_NAMESPACE + ) + except ValueError: + logger.warning( + f"Failed to get handle to replica {self._actor_name} " + "during controller recovery. Marking as dead." + ) + return False + + try: + self._placement_group = ray.util.get_placement_group( + self._actor_name, + ) + except ValueError: + # ValueError is raised if the placement group does not exist. + self._placement_group = None + + # Re-fetch initialization proof + self._allocated_obj_ref = self._actor_handle.is_allocated.remote() + + # Running actor handle already has all info needed, thus successful + # starting simply means retrieving replica version hash from actor + if self._is_cross_language: + self._ready_obj_ref = self._actor_handle.check_health.remote() + else: + self._ready_obj_ref = ( + self._actor_handle.initialize_and_get_metadata.remote() + ) + + return True + + def check_ready(self) -> Tuple[ReplicaStartupStatus, Optional[str]]: + """ + Check if current replica has started by making ray API calls on + relevant actor / object ref. + + Replica initialization calls __init__(), reconfigure(), and check_health(). + + Returns: + state (ReplicaStartupStatus): + PENDING_ALLOCATION: replica is waiting for a worker to start + PENDING_INITIALIZATION: replica initialization hasn't finished. + FAILED: replica initialization failed. + SUCCEEDED: replica initialization succeeded. + error_msg: + None: for PENDING_ALLOCATION, PENDING_INITIALIZATION or SUCCEEDED states + str: for FAILED state + """ + + # Check whether the replica has been allocated. + if self._allocated_obj_ref is None or not check_obj_ref_ready_nowait( + self._allocated_obj_ref + ): + return ReplicaStartupStatus.PENDING_ALLOCATION, None + + if not self._is_cross_language: + try: + ( + self._pid, + self._actor_id, + self._worker_id, + self._node_id, + self._node_ip, + self._node_instance_id, + self._log_file_path, + ) = ray.get(self._allocated_obj_ref) + except RayTaskError as e: + logger.exception( + f"Exception in {self._replica_id}, the replica will be stopped." + ) + return ReplicaStartupStatus.FAILED, str(e.as_instanceof_cause()) + except RuntimeEnvSetupError as e: + msg = f"Exception when allocating {self._replica_id}: {str(e)}" + logger.exception(msg) + return ReplicaStartupStatus.FAILED, msg + except Exception: + msg = ( + f"Exception when allocating {self._replica_id}:\n" + + traceback.format_exc() + ) + logger.exception(msg) + return ReplicaStartupStatus.FAILED, msg + + # Check whether replica initialization has completed. + replica_ready = check_obj_ref_ready_nowait(self._ready_obj_ref) + # In case of deployment constructor failure, ray.get will help to + # surface exception to each update() cycle. + if not replica_ready: + return ReplicaStartupStatus.PENDING_INITIALIZATION, None + else: + try: + # TODO(simon): fully implement reconfigure for Java replicas. + if self._is_cross_language: + return ReplicaStartupStatus.SUCCEEDED, None + + # todo: The replica's userconfig whitch java client created + # is different from the controller's userconfig + if not self._deployment_is_cross_language: + # This should only update version if the replica is being recovered. + # If this is checking on a replica that is newly started, this + # should return a version that is identical to what's already stored + ( + _, + self._version, + self._initialization_latency_s, + self._port, + self._docs_path, + ) = ray.get(self._ready_obj_ref) + except RayTaskError as e: + logger.exception( + f"Exception in {self._replica_id}, the replica will be stopped." + ) + # NOTE(zcin): we should use str(e) instead of traceback.format_exc() + # here because the full details of the error is not displayed properly + # with traceback.format_exc(). + return ReplicaStartupStatus.FAILED, str(e.as_instanceof_cause()) + except Exception as e: + logger.exception( + f"Exception in {self._replica_id}, the replica will be stopped." + ) + return ReplicaStartupStatus.FAILED, repr(e) + + return ReplicaStartupStatus.SUCCEEDED, None + + @property + def actor_resources(self) -> Optional[Dict[str, float]]: + return self._actor_resources + + @property + def available_resources(self) -> Dict[str, float]: + return ray.available_resources() + + def graceful_stop(self) -> Duration: + """Request the actor to exit gracefully. + + Returns the timeout after which to kill the actor. + """ + try: + handle = ray.get_actor(self._actor_name, namespace=SERVE_NAMESPACE) + if self._is_cross_language: + handle = JavaActorHandleProxy(handle) + self._graceful_shutdown_ref = handle.perform_graceful_shutdown.remote() + except ValueError: + # ValueError thrown from ray.get_actor means actor has already been deleted. + pass + + return self.graceful_shutdown_timeout_s + + def check_stopped(self) -> bool: + """Check if the actor has exited.""" + try: + handle = ray.get_actor(self._actor_name, namespace=SERVE_NAMESPACE) + stopped = check_obj_ref_ready_nowait(self._graceful_shutdown_ref) + if stopped: + try: + ray.get(self._graceful_shutdown_ref) + except Exception: + logger.exception( + "Exception when trying to gracefully shutdown replica:\n" + + traceback.format_exc() + ) + + ray.kill(handle, no_restart=True) + except ValueError: + # ValueError thrown from ray.get_actor means actor has already been deleted. + stopped = True + finally: + # Remove the placement group both if the actor has already been deleted or + # it was just killed above. + if stopped and self._placement_group is not None: + ray.util.remove_placement_group(self._placement_group) + + return stopped + + def _check_active_health_check(self) -> ReplicaHealthCheckResponse: + """Check the active health check (if any). + + self._health_check_ref will be reset to `None` when the active health + check is deemed to have succeeded or failed. This method *does not* + start a new health check, that's up to the caller. + + Returns: + - NONE if there's no active health check, or it hasn't returned + yet and the timeout is not up. + - SUCCEEDED if the active health check succeeded. + - APP_FAILURE if the active health check failed (or didn't return + before the timeout). + - ACTOR_CRASHED if the underlying actor crashed. + """ + if self._health_check_ref is None: + # There is no outstanding health check. + response = ReplicaHealthCheckResponse.NONE + elif check_obj_ref_ready_nowait(self._health_check_ref): + # Object ref is ready, ray.get it to check for exceptions. + try: + ray.get(self._health_check_ref) + # Health check succeeded without exception. + response = ReplicaHealthCheckResponse.SUCCEEDED + except RayActorError: + # Health check failed due to actor crashing. + response = ReplicaHealthCheckResponse.ACTOR_CRASHED + except RayError as e: + # Health check failed due to application-level exception. + logger.warning(f"Health check for {self._replica_id} failed: {e}") + response = ReplicaHealthCheckResponse.APP_FAILURE + elif time.time() - self._last_health_check_time > self.health_check_timeout_s: + # Health check hasn't returned and the timeout is up, consider it failed. + logger.warning( + "Didn't receive health check response for replica " + f"{self._replica_id} after " + f"{self.health_check_timeout_s}s, marking it unhealthy." + ) + response = ReplicaHealthCheckResponse.APP_FAILURE + else: + # Health check hasn't returned and the timeout isn't up yet. + response = ReplicaHealthCheckResponse.NONE + + if response is not ReplicaHealthCheckResponse.NONE: + self._health_check_ref = None + + return response + + def _should_start_new_health_check(self) -> bool: + """Determines if a new health check should be kicked off. + + A health check will be started if: + 1) There is not already an active health check. + 2) It has been more than health_check_period_s since the + previous health check was *started*. + + This assumes that self._health_check_ref is reset to `None` when an + active health check succeeds or fails (due to returning or timeout). + """ + if self._health_check_ref is not None: + # There's already an active health check. + return False + + # If there's no active health check, kick off another and reset + # the timer if it's been long enough since the last health + # check. Add some randomness to avoid synchronizing across all + # replicas. + time_since_last = time.time() - self._last_health_check_time + randomized_period = self.health_check_period_s * random.uniform(0.9, 1.1) + return time_since_last > randomized_period + + def _should_record_routing_stats(self) -> bool: + """Determines if a new record routing stats should be kicked off. + + A record routing stats will be started if: + 1) There is not already an active record routing stats. + 2) It has been more than request_routing_stats_period_s since + the previous record routing stats was *started*. + + This assumes that self._record_routing_stats_ref is reset to `None` + when an active record routing stats succeeds or fails (due to + returning or timeout). + """ + if self._record_routing_stats_ref is not None: + # There's already an active record routing stats. + return False + + # If there's no active record routing stats, kick off another and + # reset the timer if it's been long enough since the last record + # routing stats. Add some randomness to avoid synchronizing across + # all replicas. + time_since_last = time.time() - self._last_record_routing_stats_time + randomized_period = self.request_routing_stats_period_s * random.uniform( + 0.9, 1.1 + ) + return time_since_last > randomized_period + + def check_health(self) -> bool: + """Check if the actor is healthy. + + self._healthy should *only* be modified in this method. + + This is responsible for: + 1) Checking the outstanding health check (if any). + 2) Determining the replica health based on the health check results. + 3) Kicking off a new health check if needed. + """ + response: ReplicaHealthCheckResponse = self._check_active_health_check() + if response is ReplicaHealthCheckResponse.NONE: + # No info; don't update replica health. + pass + elif response is ReplicaHealthCheckResponse.SUCCEEDED: + # Health check succeeded. Reset the consecutive failure counter + # and mark the replica healthy. + if self._consecutive_health_check_failures > 0: + logger.info( + f"{self._replica_id} passed the health check after " + f"{self._consecutive_health_check_failures} consecutive failures." + ) + self._consecutive_health_check_failures = 0 + self._healthy = True + elif response is ReplicaHealthCheckResponse.APP_FAILURE: + # Health check failed. If it has failed more than N times in a row, + # mark the replica unhealthy. + self._consecutive_health_check_failures += 1 + if ( + self._consecutive_health_check_failures + >= REPLICA_HEALTH_CHECK_UNHEALTHY_THRESHOLD + ): + logger.warning( + f"Replica {self._replica_id} failed the health " + f"check {self._consecutive_health_check_failures} " + "times in a row, marking it unhealthy." + ) + self._healthy = False + elif response is ReplicaHealthCheckResponse.ACTOR_CRASHED: + # Actor crashed, mark the replica unhealthy immediately. + logger.warning( + f"Actor for {self._replica_id} crashed, marking " + "it unhealthy immediately." + ) + self._healthy = False + else: + assert False, f"Unknown response type: {response}." + + if self._should_start_new_health_check(): + self._last_health_check_time = time.time() + self._health_check_ref = self._actor_handle.check_health.remote() + + return self._healthy + + def get_routing_stats(self) -> Dict[str, Any]: + """Get the routing stats for the replica.""" + if self._record_routing_stats_ref is None: + # There's no active record routing stats. + pass + elif check_obj_ref_ready_nowait(self._record_routing_stats_ref): + # Object ref is ready, ray.get it to check for exceptions. + try: + self._routing_stats = ray.get(self._record_routing_stats_ref) + except Exception: + logger.exception( + "Exception when trying to get routing stats:\n" + + traceback.format_exc() + ) + self._record_routing_stats_ref = None + elif ( + time.time() - self._last_record_routing_stats_time + > self.request_routing_stats_timeout_s + ): + # Record routing stats hasn't returned and the timeout is up, retrying. + logger.warning( + "Didn't receive routing stats response for replica " + f"{self._replica_id} after " + f"{self.request_routing_stats_timeout_s}s, retrying." + ) + self._record_routing_stats_ref = None + + if self._should_record_routing_stats(): + self._last_record_routing_stats_time = time.time() + self._record_routing_stats_ref = ( + self._actor_handle.record_routing_stats.remote() + ) + + return self._routing_stats + + def force_stop(self): + """Force the actor to exit without shutting down gracefully.""" + if ( + self._ingress + and RAY_SERVE_DISABLE_SHUTTING_DOWN_INGRESS_REPLICAS_FORCEFULLY + ): + logger.info( + f"{self.replica_id} did not shut down because it had not finished draining requests. " + "Going to wait until the draining is complete. You can force-stop the replica by " + "setting RAY_SERVE_DISABLE_SHUTTING_DOWN_INGRESS_REPLICAS_FORCEFULLY to 0." + ) + return + + try: + ray.kill(ray.get_actor(self._actor_name, namespace=SERVE_NAMESPACE)) + except ValueError: + pass + + +class DeploymentReplica: + """Manages state transitions for deployment replicas. + + This is basically a checkpointable lightweight state machine. + """ + + def __init__( + self, + replica_id: ReplicaID, + version: DeploymentVersion, + ): + self._replica_id = replica_id + self._actor = ActorReplicaWrapper(replica_id, version) + self._start_time = None + self._actor_details = ReplicaDetails( + actor_name=replica_id.to_full_id_str(), + replica_id=self._replica_id.unique_id, + state=ReplicaState.STARTING, + start_time_s=0, + ) + self._multiplexed_model_ids: List[str] = [] + self._routing_stats: Dict[str, Any] = {} + + def get_running_replica_info( + self, cluster_node_info_cache: ClusterNodeInfoCache + ) -> RunningReplicaInfo: + return RunningReplicaInfo( + replica_id=self._replica_id, + node_id=self.actor_node_id, + node_ip=self._actor.node_ip, + availability_zone=cluster_node_info_cache.get_node_az(self.actor_node_id), + actor_handle=self._actor.actor_handle, + max_ongoing_requests=self._actor.max_ongoing_requests, + is_cross_language=self._actor.is_cross_language, + multiplexed_model_ids=self.multiplexed_model_ids, + routing_stats=self.routing_stats, + port=self._actor._port, + ) + + def record_multiplexed_model_ids(self, multiplexed_model_ids: List[str]): + """Record the multiplexed model ids for this replica.""" + self._multiplexed_model_ids = multiplexed_model_ids + + def record_routing_stats(self, routing_stats: Optional[Dict[str, Any]]): + """Record the routing stats for this replica. + + Recording routing_stats as an empty dictionary is valid. But skip + update if the routing_stats is None. + """ + if routing_stats is not None: + self._routing_stats = routing_stats + + @property + def multiplexed_model_ids(self) -> List[str]: + return self._multiplexed_model_ids + + @property + def routing_stats(self) -> Dict[str, Any]: + return self._routing_stats + + @property + def actor_details(self) -> ReplicaDetails: + return self._actor_details + + @property + def replica_id(self) -> ReplicaID: + return self._replica_id + + @property + def deployment_name(self) -> str: + return self._replica_id.deployment_id.name + + @property + def app_name(self) -> str: + return self._replica_id.deployment_id.app_name + + @property + def version(self): + return self._actor.version + + @property + def docs_path(self) -> Optional[str]: + return self._actor.docs_path + + @property + def actor_id(self) -> str: + return self._actor.actor_id + + @property + def actor_handle(self) -> ActorHandle: + return self._actor.actor_handle + + @property + def actor_node_id(self) -> Optional[str]: + """Returns the node id of the actor, None if not placed.""" + return self._actor.node_id + + @property + def actor_pid(self) -> Optional[int]: + """Returns the node id of the actor, None if not placed.""" + return self._actor.pid + + @property + def initialization_latency_s(self) -> Optional[float]: + """Returns how long the replica took to initialize.""" + + return self._actor.initialization_latency_s + + def start(self, deployment_info: DeploymentInfo) -> ReplicaSchedulingRequest: + """ + Start a new actor for current DeploymentReplica instance. + """ + replica_scheduling_request = self._actor.start(deployment_info) + self._start_time = time.time() + self.update_actor_details(start_time_s=self._start_time) + return replica_scheduling_request + + def reconfigure(self, version: DeploymentVersion) -> bool: + """ + Update replica version. Also, updates the deployment config on the actor + behind this DeploymentReplica instance if necessary. + + Returns: whether the actor is being updated. + """ + return self._actor.reconfigure(version) + + def recover(self) -> bool: + """ + Recover states in DeploymentReplica instance by fetching running actor + status + + Returns: False if the replica is no longer alive at the time + when this method is called. + """ + # If replica is no longer alive + if not self._actor.recover(): + return False + + self._start_time = time.time() + self.update_actor_details(start_time_s=self._start_time) + return True + + def check_started( + self, + ) -> Tuple[ReplicaStartupStatus, Optional[str], Optional[float]]: + """Check if the replica has started. If so, transition to RUNNING. + + Should handle the case where the replica has already stopped. + + Returns: + status: Most recent state of replica by + querying actor obj ref + """ + is_ready = self._actor.check_ready() + self.update_actor_details( + pid=self._actor.pid, + node_id=self._actor.node_id, + node_ip=self._actor.node_ip, + node_instance_id=self._actor.node_instance_id, + actor_id=self._actor.actor_id, + worker_id=self._actor.worker_id, + log_file_path=self._actor.log_file_path, + ) + + return is_ready + + def stop(self, graceful: bool = True) -> None: + """Stop the replica. + + Should handle the case where the replica is already stopped. + """ + state = self._actor_details.state + logger.info( + f"Stopping {self.replica_id} (currently {state}).", + extra={"log_to_stderr": False}, + ) + timeout_s = self._actor.graceful_stop() + if not graceful: + timeout_s = 0 + self._shutdown_deadline = time.time() + timeout_s + + def check_stopped(self) -> bool: + """Check if the replica has finished stopping.""" + if self._actor.check_stopped(): + return True + + timeout_passed = time.time() >= self._shutdown_deadline + if timeout_passed: + # Graceful period passed, kill it forcefully. + # This will be called repeatedly until the replica shuts down. + logger.info( + f"{self.replica_id} did not shut down after grace " + "period, force-killing it. " + ) + + self._actor.force_stop() + return False + + def check_health(self) -> bool: + """Check if the replica is healthy. + + Returns `True` if the replica is healthy, else `False`. + """ + return self._actor.check_health() + + def pull_routing_stats(self) -> Optional[Dict[str, Any]]: + """Get the latest response from the routing stats on the replica. + + Returns None if the replica is still calculating the stats. + """ + return self._actor.get_routing_stats() + + def update_state(self, state: ReplicaState) -> None: + """Updates state in actor details.""" + self.update_actor_details(state=state) + + def update_actor_details(self, **kwargs) -> None: + details_kwargs = self._actor_details.dict() + details_kwargs.update(kwargs) + self._actor_details = ReplicaDetails(**details_kwargs) + + def resource_requirements(self) -> Tuple[str, str]: + """Returns required and currently available resources. + + Only resources with nonzero requirements will be included in the + required dict and only resources in the required dict will be + included in the available dict (filtered for relevance). + """ + if self._actor.actor_resources is None: + return "UNKNOWN", "UNKNOWN" + + if self._actor.placement_group_bundles is not None: + required = self._actor.placement_group_bundles + else: + required = { + k: v + for k, v in self._actor.actor_resources.items() + if v is not None and v > 0 + } + + available = { + k: v for k, v in self._actor.available_resources.items() if k in required + } + + # Use json.dumps() instead of str() here to avoid double-quoting keys + # when dumping these objects. See + # https://github.com/ray-project/ray/issues/26210 for the issue. + return json.dumps(required), json.dumps(available) + + +class ReplicaStateContainer: + """Container for mapping ReplicaStates to lists of DeploymentReplicas.""" + + def __init__(self): + self._replicas: Dict[ReplicaState, List[DeploymentReplica]] = defaultdict(list) + + def add(self, state: ReplicaState, replica: DeploymentReplica): + """Add the provided replica under the provided state. + + Args: + state: state to add the replica under. + replica: replica to add. + """ + assert isinstance(state, ReplicaState), f"Type: {type(state)}" + replica.update_state(state) + self._replicas[state].append(replica) + + def get( + self, states: Optional[List[ReplicaState]] = None + ) -> List[DeploymentReplica]: + """Get all replicas of the given states. + + This does not remove them from the container. Replicas are returned + in order of state as passed in. + + Args: + states: states to consider. If not specified, all replicas + are considered. + """ + if states is None: + states = ALL_REPLICA_STATES + + assert isinstance(states, list) + + return sum((self._replicas[state] for state in states), []) + + def pop( + self, + exclude_version: Optional[DeploymentVersion] = None, + states: Optional[List[ReplicaState]] = None, + max_replicas: Optional[int] = math.inf, + ) -> List[DeploymentReplica]: + """Get and remove all replicas of the given states. + + This removes the replicas from the container. Replicas are returned + in order of state as passed in. + + Args: + exclude_version: if specified, replicas of the + provided version will *not* be removed. + states: states to consider. If not specified, all replicas + are considered. + max_replicas: max number of replicas to return. If not + specified, will pop all replicas matching the criteria. + """ + if states is None: + states = ALL_REPLICA_STATES + + assert exclude_version is None or isinstance(exclude_version, DeploymentVersion) + assert isinstance(states, list) + + replicas = [] + for state in states: + popped = [] + remaining = [] + + for replica in self._replicas[state]: + if len(replicas) + len(popped) == max_replicas: + remaining.append(replica) + elif exclude_version is not None and replica.version == exclude_version: + remaining.append(replica) + else: + popped.append(replica) + + self._replicas[state] = remaining + replicas.extend(popped) + + return replicas + + def count( + self, + exclude_version: Optional[DeploymentVersion] = None, + version: Optional[DeploymentVersion] = None, + states: Optional[List[ReplicaState]] = None, + ): + """Get the total count of replicas of the given states. + + Args: + exclude_version: version to exclude. If not + specified, all versions are considered. + version: version to filter to. If not specified, + all versions are considered. + states: states to consider. If not specified, all replicas + are considered. + """ + if states is None: + states = ALL_REPLICA_STATES + assert isinstance(states, list) + assert exclude_version is None or isinstance(exclude_version, DeploymentVersion) + assert version is None or isinstance(version, DeploymentVersion) + if exclude_version is None and version is None: + return sum(len(self._replicas[state]) for state in states) + elif exclude_version is None and version is not None: + return sum( + len(list(filter(lambda r: r.version == version, self._replicas[state]))) + for state in states + ) + elif exclude_version is not None and version is None: + return sum( + len( + list( + filter( + lambda r: r.version != exclude_version, + self._replicas[state], + ) + ) + ) + for state in states + ) + else: + raise ValueError( + "Only one of `version` or `exclude_version` may be provided." + ) + + def __str__(self): + return str(self._replicas) + + def __repr__(self): + return repr(self._replicas) + + +class DeploymentState: + """Manages the target state and replicas for a single deployment.""" + + FORCE_STOP_UNHEALTHY_REPLICAS = RAY_SERVE_FORCE_STOP_UNHEALTHY_REPLICAS + + def __init__( + self, + id: DeploymentID, + long_poll_host: LongPollHost, + deployment_scheduler: DeploymentScheduler, + cluster_node_info_cache: ClusterNodeInfoCache, + autoscaling_state_manager: AutoscalingStateManager, + ): + self._id = id + self._long_poll_host: LongPollHost = long_poll_host + self._deployment_scheduler = deployment_scheduler + self._cluster_node_info_cache = cluster_node_info_cache + self._autoscaling_state_manager = autoscaling_state_manager + + # Each time we set a new deployment goal, we're trying to save new + # DeploymentInfo and bring current deployment to meet new status. + self._target_state: DeploymentTargetState = DeploymentTargetState.default() + + self._prev_startup_warning: float = time.time() + self._replica_constructor_error_msg: Optional[str] = None + # Counter for how many times replicas failed to start. This is reset to 0 when: + # (1) The deployment is deployed / re-deployed. + # (2) The deployment reaches the HEALTHY state. + self._replica_constructor_retry_counter: int = 0 + # Flag for whether any replicas of the target version has successfully started. + # This is reset to False when the deployment is re-deployed. + self._replica_has_started: bool = False + + self._replicas: ReplicaStateContainer = ReplicaStateContainer() + self._curr_status_info: DeploymentStatusInfo = DeploymentStatusInfo( + self._id.name, + DeploymentStatus.UPDATING, + DeploymentStatusTrigger.CONFIG_UPDATE_STARTED, + ) + + self.replica_average_ongoing_requests: Dict[str, float] = {} + + self.health_check_gauge = metrics.Gauge( + "serve_deployment_replica_healthy", + description=( + "Tracks whether this deployment replica is healthy. 1 means " + "healthy, 0 means unhealthy." + ), + tag_keys=("deployment", "replica", "application"), + ) + + # Whether the request routing info have been updated since the last + # time we checked. + self._request_routing_info_updated = False + + self._last_broadcasted_running_replica_infos: List[RunningReplicaInfo] = [] + self._last_broadcasted_availability: bool = True + self._last_broadcasted_deployment_config = None + + self._docs_path: Optional[str] = None + + def should_autoscale(self) -> bool: + """ + Check if the deployment is under autoscaling + """ + return self._id in self._autoscaling_state_manager._autoscaling_states + + def get_checkpoint_data(self) -> DeploymentTargetState: + """ + Return deployment's target state submitted by user's deployment call. + Should be persisted and outlive current ray cluster. + """ + return self._target_state + + def recover_target_state_from_checkpoint( + self, target_state_checkpoint: DeploymentTargetState + ): + logger.info(f"Recovering target state for {self._id} from checkpoint.") + self._target_state = target_state_checkpoint + self._deployment_scheduler.on_deployment_deployed( + self._id, self._target_state.info.replica_config + ) + if self._target_state.info.deployment_config.autoscaling_config: + self._autoscaling_state_manager.register_deployment( + self._id, + self._target_state.info, + self._target_state.target_num_replicas, + ) + + def recover_current_state_from_replica_actor_names( + self, replica_actor_names: List[str] + ): + """Recover deployment state from live replica actors found in the cluster.""" + + assert self._target_state is not None, ( + "Target state should be recovered successfully first before " + "recovering current state from replica actor names." + ) + logger.info( + f"Recovering current state for {self._id} " + f"from {len(replica_actor_names)} live actors." + ) + # All current states use default value, only attach running replicas. + for replica_actor_name in replica_actor_names: + replica_id = ReplicaID.from_full_id_str(replica_actor_name) + new_deployment_replica = DeploymentReplica( + replica_id, + self._target_state.version, + ) + # If replica is no longer alive, simply don't add it to the + # deployment state manager to track. + if not new_deployment_replica.recover(): + logger.warning(f"{replica_id} died before controller could recover it.") + continue + + self._replicas.add(ReplicaState.RECOVERING, new_deployment_replica) + self._deployment_scheduler.on_replica_recovering(replica_id) + logger.debug(f"RECOVERING {replica_id}.") + + # TODO(jiaodong): this currently halts all traffic in the cluster + # briefly because we will broadcast a replica update with everything in + # RECOVERING. We should have a grace period where we recover the state + # of the replicas before doing this update. + + @property + def target_info(self) -> DeploymentInfo: + return self._target_state.info + + @property + def target_version(self) -> DeploymentVersion: + return self._target_state.version + + @property + def target_num_replicas(self) -> int: + return self._target_state.target_num_replicas + + @property + def curr_status_info(self) -> DeploymentStatusInfo: + return self._curr_status_info + + @property + def deployment_name(self) -> str: + return self._id.name + + @property + def app_name(self) -> str: + return self._id.app_name + + @property + def docs_path(self) -> Optional[str]: + return self._docs_path + + @property + def _failed_to_start_threshold(self) -> int: + return min( + MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT, + self._target_state.target_num_replicas * MAX_PER_REPLICA_RETRY_COUNT, + ) + + def _replica_startup_failing(self) -> bool: + """Check whether replicas are currently failing and the number of + failures has exceeded a threshold. + """ + return ( + self._target_state.target_num_replicas > 0 + and self._replica_constructor_retry_counter + >= self._failed_to_start_threshold + ) + + def _terminally_failed(self) -> bool: + """Check whether the current version is terminally errored. + + The version is considered terminally errored if the number of + replica failures has exceeded a threshold, and there hasn't been + any replicas of the target version that has successfully started. + """ + return not self._replica_has_started and self._replica_startup_failing() + + def get_alive_replica_actor_ids(self) -> Set[str]: + return {replica.actor_id for replica in self._replicas.get()} + + def get_running_replica_ids(self) -> List[ReplicaID]: + return [ + replica.replica_id + for replica in self._replicas.get( + [ReplicaState.RUNNING, ReplicaState.PENDING_MIGRATION] + ) + ] + + def get_running_replica_infos(self) -> List[RunningReplicaInfo]: + return [ + replica.get_running_replica_info(self._cluster_node_info_cache) + for replica in self._replicas.get( + [ReplicaState.RUNNING, ReplicaState.PENDING_MIGRATION] + ) + ] + + def get_num_running_replicas(self, version: DeploymentVersion = None) -> int: + return self._replicas.count(states=[ReplicaState.RUNNING], version=version) + + def get_active_node_ids(self) -> Set[str]: + """Get the node ids of all running replicas in this deployment. + + This is used to determine which node has replicas. Only nodes with replicas and + head node should have active proxies. + """ + active_states = [ + ReplicaState.STARTING, + ReplicaState.UPDATING, + ReplicaState.RECOVERING, + ReplicaState.RUNNING, + # NOTE(zcin): We still want a proxy to run on a draining + # node before all the replicas are migrated. + ReplicaState.PENDING_MIGRATION, + ] + return { + replica.actor_node_id + for replica in self._replicas.get(active_states) + if replica.actor_node_id is not None + } + + def list_replica_details(self) -> List[ReplicaDetails]: + return [replica.actor_details for replica in self._replicas.get()] + + def broadcast_running_replicas_if_changed(self) -> None: + """Broadcasts the set of running replicas over long poll if it has changed. + + Keeps an in-memory record of the last set of running replicas that was broadcast + to determine if it has changed. + + The set will also be broadcast if any replicas have an updated set of + multiplexed model IDs. + """ + running_replica_infos = self.get_running_replica_infos() + is_available = not self._terminally_failed() + + running_replicas_changed = ( + set(self._last_broadcasted_running_replica_infos) + != set(running_replica_infos) + or self._request_routing_info_updated + ) + availability_changed = is_available != self._last_broadcasted_availability + if not running_replicas_changed and not availability_changed: + return + + deployment_metadata = DeploymentTargetInfo( + is_available=is_available, + running_replicas=running_replica_infos, + ) + self._long_poll_host.notify_changed( + { + ( + LongPollNamespace.DEPLOYMENT_TARGETS, + self._id, + ): deployment_metadata, + # NOTE(zcin): notify changed for Java routers. Since Java only + # supports 1.x API, there is no concept of applications in Java, + # so the key should remain a string describing the deployment + # name. If there are no Java routers, this is a no-op. + ( + LongPollNamespace.DEPLOYMENT_TARGETS, + self._id.name, + ): deployment_metadata, + } + ) + self._last_broadcasted_running_replica_infos = running_replica_infos + self._last_broadcasted_availability = is_available + self._request_routing_info_updated = False + + def broadcast_deployment_config_if_changed(self) -> None: + """Broadcasts the deployment config over long poll if it has changed. + + Keeps an in-memory record of the last config that was broadcast to determine + if it has changed. + """ + current_deployment_config = self._target_state.info.deployment_config + if self._last_broadcasted_deployment_config == current_deployment_config: + return + + self._long_poll_host.notify_changed( + {(LongPollNamespace.DEPLOYMENT_CONFIG, self._id): current_deployment_config} + ) + + self._last_broadcasted_deployment_config = current_deployment_config + + def _set_target_state_deleting(self) -> None: + """Set the target state for the deployment to be deleted.""" + target_state = DeploymentTargetState.create( + info=self._target_state.info, + target_num_replicas=0, + deleting=True, + ) + + self._target_state = target_state + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.DELETE + ) + logger.info( + f"Deleting {self._id}", + extra={"log_to_stderr": False}, + ) + + def _set_target_state( + self, + target_info: DeploymentInfo, + target_num_replicas: int, + ) -> None: + """Set the target state for the deployment to the provided info. + + Args: + target_info: The info with which to set the target state. + target_num_replicas: The number of replicas that this deployment + should attempt to run. + status_trigger: The driver that triggered this change of state. + """ + new_target_state = DeploymentTargetState.create( + target_info, target_num_replicas, deleting=False + ) + + if self._target_state.version == new_target_state.version: + # Record either num replica or autoscaling config lightweight update + if ( + self._target_state.version.deployment_config.autoscaling_config + != new_target_state.version.deployment_config.autoscaling_config + ): + ServeUsageTag.AUTOSCALING_CONFIG_LIGHTWEIGHT_UPDATED.record("True") + elif ( + self._target_state.version.deployment_config.num_replicas + != new_target_state.version.deployment_config.num_replicas + ): + ServeUsageTag.NUM_REPLICAS_LIGHTWEIGHT_UPDATED.record("True") + + self._target_state = new_target_state + + def deploy(self, deployment_info: DeploymentInfo) -> bool: + """Deploy the deployment. + + If the deployment already exists with the same version, config, + target_capacity, and target_capacity_direction, + this method returns False. + + Returns: + bool: Whether or not the deployment is being updated. + """ + + curr_deployment_info = self._target_state.info + if curr_deployment_info is not None: + # Redeploying should not reset the deployment's start time. + if not self._target_state.deleting: + deployment_info.start_time_ms = curr_deployment_info.start_time_ms + + deployment_settings_changed = ( + self._target_state.deleting + or curr_deployment_info.deployment_config + != deployment_info.deployment_config + or curr_deployment_info.replica_config.ray_actor_options + != deployment_info.replica_config.ray_actor_options + or deployment_info.version is None + or curr_deployment_info.version != deployment_info.version + ) + target_capacity_changed = ( + curr_deployment_info.target_capacity != deployment_info.target_capacity + or curr_deployment_info.target_capacity_direction + != deployment_info.target_capacity_direction + ) + else: + deployment_settings_changed = True + target_capacity_changed = True + + # Exit early if the deployment info hasn't changed. Ensures this method + # is idempotent. + if not deployment_settings_changed and not target_capacity_changed: + return False + + if deployment_info.deployment_config.autoscaling_config: + target_num_replicas = self._autoscaling_state_manager.register_deployment( + self._id, deployment_info, self._target_state.target_num_replicas + ) + else: + self._autoscaling_state_manager.deregister_deployment(self._id) + target_num_replicas = get_capacity_adjusted_num_replicas( + deployment_info.deployment_config.num_replicas, + deployment_info.target_capacity, + ) + + old_target_state = self._target_state + self._set_target_state(deployment_info, target_num_replicas=target_num_replicas) + self._deployment_scheduler.on_deployment_deployed( + self._id, deployment_info.replica_config + ) + + # Determine if the updated target state simply scales the current state. + if self._target_state.is_scaled_copy_of(old_target_state): + old_num = old_target_state.target_num_replicas + new_num = self._target_state.target_num_replicas + + if new_num > old_num: + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.MANUALLY_INCREASE_NUM_REPLICAS, # noqa: E501 + message=f"Upscaling from {old_num} to {new_num} replicas.", + ) + elif new_num < old_num: + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.MANUALLY_DECREASE_NUM_REPLICAS, # noqa: E501 + message=f"Downscaling from {old_num} to {new_num} replicas.", + ) + else: + # Otherwise, the deployment configuration has actually been updated. + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.CONFIG_UPDATE + ) + + logger.info( + f"Deploying new version of {self._id} " + f"(initial target replicas: {target_num_replicas})." + ) + self._replica_constructor_retry_counter = 0 + self._replica_has_started = False + return True + + def autoscale(self) -> int: + """Autoscale the deployment based on metrics.""" + + if self._target_state.deleting: + return + + decision_num_replicas = self._autoscaling_state_manager.get_target_num_replicas( + deployment_id=self._id, + curr_target_num_replicas=self._target_state.target_num_replicas, + ) + + if ( + decision_num_replicas is None + or decision_num_replicas == self._target_state.target_num_replicas + ): + return + + new_info = copy(self._target_state.info) + new_info.version = self._target_state.version.code_version + + old_num = self._target_state.target_num_replicas + self._set_target_state(new_info, decision_num_replicas) + + # The deployment should only transition to UPSCALING/DOWNSCALING + # if it's within the autoscaling bounds + if not self._autoscaling_state_manager.is_within_bounds( + self._id, + self._replicas.count( + states=[ReplicaState.RUNNING], version=self._target_state.version + ), + ): + return + + curr_stats_str = ( + f"Current ongoing requests: " + f"{self._autoscaling_state_manager.get_total_num_requests(self._id):.2f}, " + f"current running replicas: " + f"{self._replicas.count(states=[ReplicaState.RUNNING])}." + ) + new_num = self._target_state.target_num_replicas + if new_num > old_num: + logger.info( + f"Upscaling {self._id} from {old_num} to {new_num} replicas. " + f"{curr_stats_str}" + ) + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.AUTOSCALE_UP, + message=f"Upscaling from {old_num} to {new_num} replicas.", + ) + elif new_num < old_num: + logger.info( + f"Downscaling {self._id} from {old_num} to {new_num} replicas. " + f"{curr_stats_str}" + ) + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.AUTOSCALE_DOWN, + message=f"Downscaling from {old_num} to {new_num} replicas.", + ) + + def delete(self) -> None: + if not self._target_state.deleting: + self._set_target_state_deleting() + + def _stop_or_update_outdated_version_replicas(self, max_to_stop=math.inf) -> bool: + """Stop or update replicas with outdated versions. + + Stop replicas with versions that require the actor to be restarted, and + reconfigure replicas that require refreshing deployment config values. + + Args: + max_to_stop: max number of replicas to stop, by default, + it stops all replicas with an outdated version. + """ + replicas_to_update = self._replicas.pop( + exclude_version=self._target_state.version, + states=[ + ReplicaState.STARTING, + ReplicaState.PENDING_MIGRATION, + ReplicaState.RUNNING, + ], + ) + replicas_changed = False + code_version_changes = 0 + reconfigure_changes = 0 + for replica in replicas_to_update: + if (code_version_changes + reconfigure_changes) >= max_to_stop: + self._replicas.add(replica.actor_details.state, replica) + # If the new version requires the actors to be restarted, stop the replica. + # A new one with the correct version will be started later as part of the + # normal scale-up process. + elif replica.version.requires_actor_restart(self._target_state.version): + code_version_changes += 1 + # If the replica is still `STARTING`, we don't need to go through the + # graceful stop period. + graceful_stop = replica.actor_details.state == ReplicaState.RUNNING + self._stop_replica(replica, graceful_stop=graceful_stop) + replicas_changed = True + # Otherwise, only lightweight options in deployment config is a mismatch, so + # we update it dynamically without restarting the replica. + elif replica.actor_details.state == ReplicaState.RUNNING: + reconfigure_changes += 1 + if replica.version.requires_long_poll_broadcast( + self._target_state.version + ): + replicas_changed = True + actor_updating = replica.reconfigure(self._target_state.version) + if actor_updating: + self._replicas.add(ReplicaState.UPDATING, replica) + else: + self._replicas.add(ReplicaState.RUNNING, replica) + # We don't allow going from STARTING, PENDING_MIGRATION to UPDATING. + else: + self._replicas.add(replica.actor_details.state, replica) + + if code_version_changes > 0: + logger.info( + f"Stopping {code_version_changes} replicas of {self._id} " + "with outdated versions." + ) + + if reconfigure_changes > 0: + logger.info( + f"Updating {reconfigure_changes} replicas of {self._id} " + "with outdated deployment configs." + ) + # Record user config lightweight update + ServeUsageTag.USER_CONFIG_LIGHTWEIGHT_UPDATED.record("True") + + return replicas_changed + + def _check_and_stop_outdated_version_replicas(self) -> bool: + """Stops replicas with outdated versions to implement rolling updates. + + This includes both explicit code version updates and changes to the + user_config. + + Returns whether any replicas were stopped. + """ + # Short circuit if target replicas is 0 (the deployment is being + # deleted) because this will be handled in the main loop. + if self._target_state.target_num_replicas == 0: + return False + + # We include STARTING and UPDATING replicas here + # because if there are replicas still pending startup, we may as well + # terminate them and start new version replicas instead. + old_running_replicas = self._replicas.count( + exclude_version=self._target_state.version, + states=[ + ReplicaState.STARTING, + ReplicaState.UPDATING, + ReplicaState.RUNNING, + ], + ) + old_stopping_replicas = self._replicas.count( + exclude_version=self._target_state.version, states=[ReplicaState.STOPPING] + ) + new_running_replicas = self._replicas.count( + version=self._target_state.version, states=[ReplicaState.RUNNING] + ) + + # If the deployment is currently scaling down, let the scale down + # complete before doing a rolling update. + if ( + self._target_state.target_num_replicas + < old_running_replicas + old_stopping_replicas + ): + return False + + # The number of replicas that are currently in transition between + # an old version and the new version. Note that we cannot directly + # count the number of stopping replicas because once replicas finish + # stopping, they are removed from the data structure. + pending_replicas = ( + self._target_state.target_num_replicas + - new_running_replicas + - old_running_replicas + ) + + # Maximum number of replicas that can be updating at any given time. + # There should never be more than rollout_size old replicas stopping + # or rollout_size new replicas starting. + rollout_size = max(int(0.2 * self._target_state.target_num_replicas), 1) + max_to_stop = max(rollout_size - pending_replicas, 0) + + return self._stop_or_update_outdated_version_replicas(max_to_stop) + + def scale_deployment_replicas( + self, + ) -> Tuple[List[ReplicaSchedulingRequest], DeploymentDownscaleRequest]: + """Scale the given deployment to the number of replicas.""" + + assert ( + self._target_state.target_num_replicas >= 0 + ), "Target number of replicas must be greater than or equal to 0." + + upscale = [] + downscale = None + + self._check_and_stop_outdated_version_replicas() + + current_replicas = self._replicas.count( + states=[ReplicaState.STARTING, ReplicaState.UPDATING, ReplicaState.RUNNING] + ) + recovering_replicas = self._replicas.count(states=[ReplicaState.RECOVERING]) + + delta_replicas = ( + self._target_state.target_num_replicas + - current_replicas + - recovering_replicas + ) + if delta_replicas == 0: + return (upscale, downscale) + + elif delta_replicas > 0: + to_add = delta_replicas + if to_add > 0 and not self._terminally_failed(): + logger.info(f"Adding {to_add} replica{'s' * (to_add>1)} to {self._id}.") + for _ in range(to_add): + replica_id = ReplicaID(get_random_string(), deployment_id=self._id) + new_deployment_replica = DeploymentReplica( + replica_id, + self._target_state.version, + ) + upscale.append( + new_deployment_replica.start(self._target_state.info) + ) + + self._replicas.add(ReplicaState.STARTING, new_deployment_replica) + + elif delta_replicas < 0: + to_remove = -delta_replicas + removed_replicas = f"{to_remove} replica{'s' if to_remove > 1 else ''}" + logger.info(f"Removing {removed_replicas} from {self._id}.") + downscale = DeploymentDownscaleRequest( + deployment_id=self._id, num_to_stop=to_remove + ) + + return upscale, downscale + + def check_curr_status(self) -> Tuple[bool, bool]: + """Check the current deployment status. + + Checks the difference between the target vs. running replica count for + the target version. + + This will update the current deployment status depending on the state + of the replicas. + + Returns (deleted, any_replicas_recovering). + """ + # TODO(edoakes): we could make this more efficient in steady-state by + # having a "healthy" flag that gets flipped if an update or replica + # failure happens. + + target_version = self._target_state.version + + any_replicas_recovering = ( + self._replicas.count(states=[ReplicaState.RECOVERING]) > 0 + ) + all_running_replica_cnt = self._replicas.count(states=[ReplicaState.RUNNING]) + running_at_target_version_replica_cnt = self._replicas.count( + states=[ReplicaState.RUNNING], version=target_version + ) + + # Got to make a call to complete current deploy() goal after + # start failure threshold reached, while we might still have + # pending replicas in current goal. + if running_at_target_version_replica_cnt > 0: + # At least one RUNNING replica at target state, partial + # success; We can stop tracking constructor failures and + # leave it to the controller to fully scale to target + # number of replicas and only return as completed once + # reached target replica count + self._replica_has_started = True + elif self._replica_startup_failing(): + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.REPLICA_STARTUP_FAILED, + message=( + "The deployment failed to start " + f"{self._replica_constructor_retry_counter} times " + "in a row. This may be due to a problem with its " + "constructor or initial health check failing. See " + "controller logs for details. Error:\n" + f"{self._replica_constructor_error_msg}" + ), + ) + return False, any_replicas_recovering + + # If we have pending ops, the current goal is *not* ready. + if ( + self._replicas.count( + states=[ + ReplicaState.STARTING, + ReplicaState.UPDATING, + ReplicaState.RECOVERING, + ReplicaState.STOPPING, + ] + ) + == 0 + ): + # Check for deleting and a non-zero number of deployments. + if self._target_state.deleting and all_running_replica_cnt == 0: + return True, any_replicas_recovering + + if ( + self._target_state.target_num_replicas + == running_at_target_version_replica_cnt + and running_at_target_version_replica_cnt == all_running_replica_cnt + ): + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.HEALTHY + ) + self._replica_constructor_retry_counter = 0 + return False, any_replicas_recovering + + return False, any_replicas_recovering + + def _check_startup_replicas( + self, original_state: ReplicaState, stop_on_slow=False + ) -> List[Tuple[DeploymentReplica, ReplicaStartupStatus]]: + """ + Common helper function for startup actions tracking and status + transition: STARTING, UPDATING and RECOVERING. + + Args: + stop_on_slow: If we consider a replica failed upon observing it's + slow to reach running state. + """ + slow_replicas = [] + for replica in self._replicas.pop(states=[original_state]): + start_status, error_msg = replica.check_started() + if start_status == ReplicaStartupStatus.SUCCEEDED: + # This replica should be now be added to handle's replica + # set. + self._replicas.add(ReplicaState.RUNNING, replica) + self._deployment_scheduler.on_replica_running( + replica.replica_id, replica.actor_node_id + ) + + # if replica version is the same as the target version, + # we update the docs path + if replica.version == self._target_state.version: + self._docs_path = replica.docs_path + + # Log the startup latency. + e2e_replica_start_latency = time.time() - replica._start_time + replica_startup_message = ( + f"{replica.replica_id} started successfully " + f"on node '{replica.actor_node_id}' after " + f"{e2e_replica_start_latency:.1f}s (PID: {replica.actor_pid})." + ) + if replica.initialization_latency_s is not None: + # This condition should always be True. The initialization + # latency is only None before the replica has initialized. + replica_startup_message += ( + " Replica constructor, " + "reconfigure method, and initial health check took " + f"{replica.initialization_latency_s:.1f}s." + ) + logger.info(replica_startup_message, extra={"log_to_stderr": False}) + + elif start_status == ReplicaStartupStatus.FAILED: + # Replica reconfigure (deploy / upgrade) failed + self.record_replica_startup_failure(error_msg) + self._stop_replica(replica) + elif start_status in [ + ReplicaStartupStatus.PENDING_ALLOCATION, + ReplicaStartupStatus.PENDING_INITIALIZATION, + ]: + is_slow = time.time() - replica._start_time > SLOW_STARTUP_WARNING_S + if is_slow: + slow_replicas.append((replica, start_status)) + + # Does it make sense to stop replicas in PENDING_ALLOCATION + # state? + if is_slow and stop_on_slow: + self._stop_replica(replica, graceful_stop=False) + else: + self._replicas.add(original_state, replica) + + return slow_replicas + + def record_replica_startup_failure(self, error_msg: str): + """Record that a replica failed to start.""" + + # There is no need to record replica failures if the target is 0. + if self._target_state.target_num_replicas == 0: + return + + # Increase startup failure counter + self._replica_constructor_retry_counter += 1 + self._replica_constructor_error_msg = error_msg + + # Update the deployment message only if replicas are failing during + # the very first time the controller is trying to start replicas of + # this version. + retrying_msg = "" + if not self._replica_has_started: + remaining_retries = max( + self._failed_to_start_threshold + - self._replica_constructor_retry_counter, + 0, + ) + retrying_msg = f" {remaining_retries} more time(s)" + + message = ( + f"A replica failed to start with exception. Retrying{retrying_msg}. " + f"Error:\n{error_msg}" + ) + self._curr_status_info = self._curr_status_info.update_message(message) + + def stop_replicas(self, replicas_to_stop) -> None: + for replica in self._replicas.pop(): + if replica.replica_id in replicas_to_stop: + self._stop_replica(replica) + else: + self._replicas.add(replica.actor_details.state, replica) + + def _stop_replica(self, replica: DeploymentReplica, graceful_stop=True): + """Stop replica + 1. Stop the replica. + 2. Change the replica into stopping state. + 3. Set the health replica stats to 0. + """ + logger.debug(f"Adding STOPPING to replica: {replica.replica_id}.") + replica.stop(graceful=graceful_stop) + self._replicas.add(ReplicaState.STOPPING, replica) + self._deployment_scheduler.on_replica_stopping(replica.replica_id) + self.health_check_gauge.set( + 0, + tags={ + "deployment": self.deployment_name, + "replica": replica.replica_id.unique_id, + "application": self.app_name, + }, + ) + + def check_and_update_replicas(self): + """ + Check current state of all DeploymentReplica being tracked, and compare + with state container from previous update() cycle to see if any state + transition happened. + """ + + for replica in self._replicas.pop( + states=[ReplicaState.RUNNING, ReplicaState.PENDING_MIGRATION] + ): + if replica.check_health(): + self._replicas.add(replica.actor_details.state, replica) + self.health_check_gauge.set( + 1, + tags={ + "deployment": self.deployment_name, + "replica": replica.replica_id.unique_id, + "application": self.app_name, + }, + ) + routing_stats = replica.pull_routing_stats() + replica.record_routing_stats(routing_stats) + else: + logger.warning( + f"Replica {replica.replica_id} failed health check, stopping it." + ) + self.health_check_gauge.set( + 0, + tags={ + "deployment": self.deployment_name, + "replica": replica.replica_id.unique_id, + "application": self.app_name, + }, + ) + self._stop_replica( + replica, graceful_stop=not self.FORCE_STOP_UNHEALTHY_REPLICAS + ) + # If this is a replica of the target version, the deployment + # enters the "UNHEALTHY" status until the replica is + # recovered or a new deploy happens. + if replica.version == self._target_state.version: + self._curr_status_info = self._curr_status_info.handle_transition( + trigger=DeploymentStatusInternalTrigger.HEALTH_CHECK_FAILED, + message="A replica's health check failed. This " + "deployment will be UNHEALTHY until the replica " + "recovers or a new deploy happens.", + ) + + slow_start_replicas = [] + slow_start = self._check_startup_replicas(ReplicaState.STARTING) + slow_update = self._check_startup_replicas(ReplicaState.UPDATING) + slow_recover = self._check_startup_replicas( + ReplicaState.RECOVERING, stop_on_slow=True + ) + + slow_start_replicas = slow_start + slow_update + slow_recover + + if ( + len(slow_start_replicas) + and time.time() - self._prev_startup_warning > SLOW_STARTUP_WARNING_PERIOD_S + ): + pending_allocation = [] + pending_initialization = [] + + for replica, startup_status in slow_start_replicas: + if startup_status == ReplicaStartupStatus.PENDING_ALLOCATION: + pending_allocation.append(replica) + if startup_status == ReplicaStartupStatus.PENDING_INITIALIZATION: + pending_initialization.append(replica) + + if len(pending_allocation) > 0: + required, available = pending_allocation[0].resource_requirements() + message = ( + f"Deployment '{self.deployment_name}' in application " + f"'{self.app_name}' has {len(pending_allocation)} replicas that " + f"have taken more than {SLOW_STARTUP_WARNING_S}s to be scheduled. " + "This may be due to waiting for the cluster to auto-scale or for a " + "runtime environment to be installed. " + f"Resources required for each replica: {required}, " + f"total resources available: {available}. " + "Use `ray status` for more details." + ) + logger.warning(message) + if _SCALING_LOG_ENABLED: + print_verbose_scaling_log() + # If status is UNHEALTHY, leave the status and message as is. + # The issue that caused the deployment to be unhealthy should be + # prioritized over this resource availability issue. + if self._curr_status_info.status not in [ + DeploymentStatus.UNHEALTHY, + DeploymentStatus.DEPLOY_FAILED, + ]: + self._curr_status_info = self._curr_status_info.update_message( + message + ) + + if len(pending_initialization) > 0: + message = ( + f"Deployment '{self.deployment_name}' in application " + f"'{self.app_name}' has {len(pending_initialization)} replicas " + f"that have taken more than {SLOW_STARTUP_WARNING_S}s to " + "initialize.\n" + "This may be caused by a slow __init__ or reconfigure method." + ) + logger.warning(message) + # If status is UNHEALTHY, leave the status and message as is. + # The issue that caused the deployment to be unhealthy should be + # prioritized over this resource availability issue. + if self._curr_status_info.status not in [ + DeploymentStatus.UNHEALTHY, + DeploymentStatus.DEPLOY_FAILED, + ]: + self._curr_status_info = self._curr_status_info.update_message( + message + ) + + self._prev_startup_warning = time.time() + + for replica in self._replicas.pop(states=[ReplicaState.STOPPING]): + stopped = replica.check_stopped() + if not stopped: + self._replicas.add(ReplicaState.STOPPING, replica) + else: + logger.info(f"{replica.replica_id} is stopped.") + self._autoscaling_state_manager.on_replica_stopped(replica.replica_id) + + def _choose_pending_migration_replicas_to_stop( + self, + replicas: List[DeploymentReplica], + deadlines: Dict[str, int], + min_replicas_to_stop: int, + ) -> Tuple[List[DeploymentReplica], List[DeploymentReplica]]: + """Returns a partition of replicas to stop and to keep. + + Args: + replicas: The current list of replicas pending migration. + deadlines: The current draining node deadlines. + min_replicas_to_stop: The minimum number of replicas to stop. + """ + to_stop = [] + remaining = [] + + # Stop replicas whose deadline is up + for replica in replicas: + assert replica.actor_node_id in deadlines + + curr_timestamp_ms = time.time() * 1000 + timeout_ms = replica._actor.graceful_shutdown_timeout_s * 1000 + if curr_timestamp_ms >= deadlines[replica.actor_node_id] - timeout_ms: + to_stop.append(replica) + else: + remaining.append(replica) + + # Stop excess PENDING_MIGRATION replicas when new "replacement" + # replicas have transitioned to RUNNING. The replicas with the + # earliest deadlines should be chosen greedily. + remaining.sort(key=lambda r: deadlines[r.actor_node_id]) + num_excess = min_replicas_to_stop - len(to_stop) + + if num_excess > 0: + to_stop.extend(remaining[:num_excess]) + remaining = remaining[num_excess:] + + return to_stop, remaining + + def migrate_replicas_on_draining_nodes(self, draining_nodes: Dict[str, int]): + # Move replicas back to running if they are no longer on a draining node. + # If this causes the number of replicas to exceed the target state, + # they will be scaled down because `scale_deployment_replicas` is called on + # each deployment after this + for replica in self._replicas.pop(states=[ReplicaState.PENDING_MIGRATION]): + if replica.actor_node_id not in draining_nodes: + self._replicas.add(ReplicaState.RUNNING, replica) + else: + self._replicas.add(ReplicaState.PENDING_MIGRATION, replica) + + # Migrate replicas on draining nodes + for replica in self._replicas.pop( + states=[ReplicaState.UPDATING, ReplicaState.RUNNING, ReplicaState.STARTING] + ): + if replica.actor_node_id in draining_nodes: + # For RUNNING replicas, migrate them safely by starting + # a replacement replica first. + if replica.actor_details.state == ReplicaState.RUNNING: + logger.info( + f"Migrating {replica.replica_id} from draining node " + f"'{replica.actor_node_id}'. A new replica will be created on " + "another node." + ) + self._replicas.add(ReplicaState.PENDING_MIGRATION, replica) + # For replicas that are STARTING or UPDATING, might as + # well terminate them immediately to allow replacement + # replicas to start. Otherwise we need to wait for them + # to transition to RUNNING before starting migration. + else: + self._stop_replica(replica, graceful_stop=True) + else: + self._replicas.add(replica.actor_details.state, replica) + + num_running = self._replicas.count(states=[ReplicaState.RUNNING]) + num_draining = self._replicas.count(states=[ReplicaState.PENDING_MIGRATION]) + num_pending_migration_replicas_to_stop = ( + num_running + num_draining - self._target_state.target_num_replicas + ) + + ( + replicas_to_stop, + replicas_to_keep, + ) = self._choose_pending_migration_replicas_to_stop( + self._replicas.pop(states=[ReplicaState.PENDING_MIGRATION]), + draining_nodes, + num_pending_migration_replicas_to_stop, + ) + for replica in replicas_to_stop: + logger.info( + f"Stopping {replica.replica_id} " + f"on draining node {replica.actor_node_id}." + ) + self._stop_replica(replica, graceful_stop=True) + + for replica in replicas_to_keep: + self._replicas.add(ReplicaState.PENDING_MIGRATION, replica) + + def record_request_routing_info(self, info: RequestRoutingInfo) -> None: + """Records the multiplexed model IDs of a replica. + + Args: + info: RequestRoutingInfo including deployment name, replica tag, + multiplex model ids, and routing stats. + """ + # Find the replica + for replica in self._replicas.get(): + if replica.replica_id == info.replica_id: + if info.multiplexed_model_ids is not None: + replica.record_multiplexed_model_ids(info.multiplexed_model_ids) + if info.routing_stats is not None: + replica.record_routing_stats(info.routing_stats) + self._request_routing_info_updated = True + return + + logger.warning(f"{info.replica_id} not found.") + + def _stop_one_running_replica_for_testing(self): + running_replicas = self._replicas.pop(states=[ReplicaState.RUNNING]) + replica_to_stop = running_replicas.pop() + replica_to_stop.stop(graceful=False) + self._replicas.add(ReplicaState.STOPPING, replica_to_stop) + for replica in running_replicas: + self._replicas.add(ReplicaState.RUNNING, replica) + + +class DeploymentStateManager: + """Manages all state for deployments in the system. + + This class is *not* thread safe, so any state-modifying methods should be + called with a lock held. + """ + + def __init__( + self, + kv_store: KVStoreBase, + long_poll_host: LongPollHost, + all_current_actor_names: List[str], + all_current_placement_group_names: List[str], + cluster_node_info_cache: ClusterNodeInfoCache, + autoscaling_state_manager: AutoscalingStateManager, + head_node_id_override: Optional[str] = None, + create_placement_group_fn_override: Optional[Callable] = None, + ): + self._kv_store = kv_store + self._long_poll_host = long_poll_host + self._cluster_node_info_cache = cluster_node_info_cache + self._deployment_scheduler = default_impl.create_deployment_scheduler( + cluster_node_info_cache, + head_node_id_override, + create_placement_group_fn_override, + ) + self._autoscaling_state_manager = autoscaling_state_manager + + self._shutting_down = False + + self._deployment_states: Dict[DeploymentID, DeploymentState] = {} + self._app_deployment_mapping: Dict[str, Set[str]] = defaultdict(set) + + self._recover_from_checkpoint( + all_current_actor_names, all_current_placement_group_names + ) + + def _create_deployment_state(self, deployment_id): + self._deployment_scheduler.on_deployment_created( + deployment_id, SpreadDeploymentSchedulingPolicy() + ) + + return DeploymentState( + deployment_id, + self._long_poll_host, + self._deployment_scheduler, + self._cluster_node_info_cache, + self._autoscaling_state_manager, + ) + + def _map_actor_names_to_deployment( + self, all_current_actor_names: List[str] + ) -> Dict[str, List[str]]: + """ + Given a list of all actor names queried from current ray cluster, + map them to corresponding deployments. + + Example: + Args: + [A#zxc123, B#xcv234, A#qwe234] + Returns: + { + A: [A#zxc123, A#qwe234] + B: [B#xcv234] + } + """ + all_replica_names = [ + actor_name + for actor_name in all_current_actor_names + if ReplicaID.is_full_id_str(actor_name) + ] + deployment_to_current_replicas = defaultdict(list) + if len(all_replica_names) > 0: + for replica_name in all_replica_names: + replica_id = ReplicaID.from_full_id_str(replica_name) + deployment_to_current_replicas[replica_id.deployment_id].append( + replica_name + ) + + return deployment_to_current_replicas + + def _detect_and_remove_leaked_placement_groups( + self, + all_current_actor_names: List[str], + all_current_placement_group_names: List[str], + ): + """Detect and remove any placement groups not associated with a replica. + + This can happen under certain rare circumstances: + - The controller creates a placement group then crashes before creating + the associated replica actor. + - While the controller is down, a replica actor crashes but its placement + group still exists. + + In both of these (or any other unknown cases), we simply need to remove the + leaked placement groups. + """ + leaked_pg_names = [] + for pg_name in all_current_placement_group_names: + if ( + ReplicaID.is_full_id_str(pg_name) + and pg_name not in all_current_actor_names + ): + leaked_pg_names.append(pg_name) + + if len(leaked_pg_names) > 0: + logger.warning( + f"Detected leaked placement groups: {leaked_pg_names}. " + "The placement groups will be removed. This can happen in rare " + "circumstances when the controller crashes and should not cause any " + "issues. If this happens repeatedly, please file an issue on GitHub." + ) + + for leaked_pg_name in leaked_pg_names: + try: + pg = ray.util.get_placement_group(leaked_pg_name) + ray.util.remove_placement_group(pg) + except Exception: + logger.exception( + f"Failed to remove leaked placement group {leaked_pg_name}." + ) + + def _recover_from_checkpoint( + self, + all_current_actor_names: List[str], + all_current_placement_group_names: List[str], + ): + """ + Recover from checkpoint upon controller failure with all actor names + found in current cluster. + + Each deployment resumes target state from checkpoint if available. + + For current state it will prioritize reconstructing from current + actor names found that matches deployment tag if applicable. + """ + self._detect_and_remove_leaked_placement_groups( + all_current_actor_names, + all_current_placement_group_names, + ) + + deployment_to_current_replicas = self._map_actor_names_to_deployment( + all_current_actor_names + ) + checkpoint = self._kv_store.get(CHECKPOINT_KEY) + if checkpoint is not None: + deployment_state_info = cloudpickle.loads(checkpoint) + + for deployment_id, checkpoint_data in deployment_state_info.items(): + deployment_state = self._create_deployment_state(deployment_id) + deployment_state.recover_target_state_from_checkpoint(checkpoint_data) + if len(deployment_to_current_replicas[deployment_id]) > 0: + deployment_state.recover_current_state_from_replica_actor_names( # noqa: E501 + deployment_to_current_replicas[deployment_id] + ) + self._deployment_states[deployment_id] = deployment_state + self._app_deployment_mapping[deployment_id.app_name].add( + deployment_id.name + ) + + def shutdown(self): + """ + Shutdown all running replicas by notifying the controller, and leave + it to the controller event loop to take actions afterwards. + + Once shutdown signal is received, it will also prevent any new + deployments or replicas from being created. + + One can send multiple shutdown signals but won't effectively make any + difference compare to calling it once. + """ + self._shutting_down = True + + for deployment_state in self._deployment_states.values(): + deployment_state.delete() + + # TODO(jiaodong): This might not be 100% safe since we deleted + # everything without ensuring all shutdown goals are completed + # yet. Need to address in follow-up PRs. + self._kv_store.delete(CHECKPOINT_KEY) + + # TODO(jiaodong): Need to add some logic to prevent new replicas + # from being created once shutdown signal is sent. + + def is_ready_for_shutdown(self) -> bool: + """Return whether all deployments are shutdown. + + Check there are no deployment states and no checkpoints. + """ + return ( + self._shutting_down + and len(self._deployment_states) == 0 + and self._kv_store.get(CHECKPOINT_KEY) is None + ) + + def save_checkpoint(self) -> None: + """Write a checkpoint of all deployment states.""" + if self._shutting_down: + # Once we're told to shut down, stop writing checkpoints. + # Calling .shutdown() deletes any existing checkpoint. + return + + deployment_state_info = { + deployment_id: deployment_state.get_checkpoint_data() + for deployment_id, deployment_state in self._deployment_states.items() + } + + self._kv_store.put( + CHECKPOINT_KEY, + cloudpickle.dumps(deployment_state_info), + ) + + def get_running_replica_infos( + self, + ) -> Dict[DeploymentID, List[RunningReplicaInfo]]: + return { + id: deployment_state.get_running_replica_infos() + for id, deployment_state in self._deployment_states.items() + } + + def get_deployment_infos(self) -> Dict[DeploymentID, DeploymentInfo]: + infos: Dict[DeploymentID, DeploymentInfo] = {} + for deployment_id, deployment_state in self._deployment_states.items(): + infos[deployment_id] = deployment_state.target_info + + return infos + + def get_deployment(self, deployment_id: DeploymentID) -> Optional[DeploymentInfo]: + if deployment_id in self._deployment_states: + return self._deployment_states[deployment_id].target_info + else: + return None + + def get_deployment_docs_path(self, deployment_id: DeploymentID) -> Optional[str]: + if deployment_id in self._deployment_states: + return self._deployment_states[deployment_id].docs_path + + def get_deployment_details(self, id: DeploymentID) -> Optional[DeploymentDetails]: + """Gets detailed info on a deployment. + + Returns: + DeploymentDetails: if the deployment is live. + None: if the deployment is deleted. + """ + statuses = self.get_deployment_statuses([id]) + if len(statuses) == 0: + return None + else: + status_info = statuses[0] + deployment_state = self._deployment_states[id] + return DeploymentDetails( + name=id.name, + status=status_info.status, + status_trigger=status_info.status_trigger, + message=status_info.message, + deployment_config=_deployment_info_to_schema( + id.name, self.get_deployment(id) + ), + target_num_replicas=deployment_state._target_state.target_num_replicas, + required_resources=deployment_state.target_info.replica_config.resource_dict, + replicas=deployment_state.list_replica_details(), + ) + + def get_deployment_statuses( + self, ids: Optional[List[DeploymentID]] = None + ) -> List[DeploymentStatusInfo]: + """ + Return the statuses of the deployments with the given `ids`. + If `ids` is `None`, returns the status of all deployments. + """ + if ids is None: + # fast path for returning all deployments, + # avoids checking `if ids is None` in a loop + return [ + state.curr_status_info for state in self._deployment_states.values() + ] + else: + statuses = [] + for id in ids: + state = self._deployment_states.get(id) + if state is not None: + statuses.append(state.curr_status_info) + return statuses + + def get_alive_replica_actor_ids(self) -> Set[str]: + alive_replica_actor_ids = set() + for ds in self._deployment_states.values(): + alive_replica_actor_ids |= ds.get_alive_replica_actor_ids() + + return alive_replica_actor_ids + + def deploy( + self, + deployment_id: DeploymentID, + deployment_info: DeploymentInfo, + ) -> bool: + """Deploy the deployment. + + If the deployment already exists with the same version and config, + this is a no-op and returns False. + + Returns: + bool: Whether or not the deployment is being updated. + """ + if deployment_id not in self._deployment_states: + self._deployment_states[deployment_id] = self._create_deployment_state( + deployment_id + ) + self._app_deployment_mapping[deployment_id.app_name].add(deployment_id.name) + self._record_deployment_usage() + + return self._deployment_states[deployment_id].deploy(deployment_info) + + def get_deployments_in_application(self, app_name: str) -> List[str]: + """Return list of deployment names in application.""" + return list(self._app_deployment_mapping[app_name]) + + def delete_deployment(self, id: DeploymentID): + # This method must be idempotent. We should validate that the + # specified deployment exists on the client. + if id in self._deployment_states: + self._deployment_states[id].delete() + + def update(self) -> bool: + """Updates the state of all deployments to match their goal state. + + Returns True if any of the deployments have replicas in the RECOVERING state. + """ + + deleted_ids = [] + any_recovering = False + upscales: Dict[DeploymentID, List[ReplicaSchedulingRequest]] = {} + downscales: Dict[DeploymentID, DeploymentDownscaleRequest] = {} + + # STEP 1: Update current state + for deployment_state in self._deployment_states.values(): + if deployment_state.should_autoscale(): + deployment_state.autoscale() + + deployment_state.check_and_update_replicas() + + # STEP 2: Check current status + for deployment_state in self._deployment_states.values(): + deployment_state.check_curr_status() + + # STEP 3: Drain nodes + draining_nodes = self._cluster_node_info_cache.get_draining_nodes() + allow_new_compaction = len(draining_nodes) == 0 and all( + ds.curr_status_info.status == DeploymentStatus.HEALTHY + # TODO(zcin): Make sure that status should never be healthy if + # the number of running replicas at target version is not at + # target number, so we can remove this defensive check. + and ds.get_num_running_replicas(ds.target_version) == ds.target_num_replicas + # To be extra conservative, only actively compact if there + # are no non-running replicas + and len(ds._replicas.get()) == ds.target_num_replicas + for ds in self._deployment_states.values() + ) + if RAY_SERVE_USE_COMPACT_SCHEDULING_STRATEGY: + # Tuple of target node to compact, and its draining deadline + node_info: Optional[ + Tuple[str, float] + ] = self._deployment_scheduler.get_node_to_compact( + allow_new_compaction=allow_new_compaction + ) + if node_info: + target_node_id, deadline = node_info + draining_nodes = {target_node_id: deadline} + + for deployment_id, deployment_state in self._deployment_states.items(): + deployment_state.migrate_replicas_on_draining_nodes(draining_nodes) + + # STEP 4: Scale replicas + for deployment_id, deployment_state in self._deployment_states.items(): + upscale, downscale = deployment_state.scale_deployment_replicas() + + if upscale: + upscales[deployment_id] = upscale + if downscale: + downscales[deployment_id] = downscale + + # STEP 5: Update status + for deployment_id, deployment_state in self._deployment_states.items(): + deleted, any_replicas_recovering = deployment_state.check_curr_status() + + if deleted: + deleted_ids.append(deployment_id) + any_recovering |= any_replicas_recovering + + # Take a checkpoint before actually affecting the state of the cluster + # by starting/stopping replicas. + self.save_checkpoint() + + # STEP 6: Schedule all STARTING replicas and stop all STOPPING replicas + deployment_to_replicas_to_stop = self._deployment_scheduler.schedule( + upscales, downscales + ) + for deployment_id, replicas_to_stop in deployment_to_replicas_to_stop.items(): + self._deployment_states[deployment_id].stop_replicas(replicas_to_stop) + for deployment_id, scheduling_requests in upscales.items(): + self._handle_scheduling_request_failures(deployment_id, scheduling_requests) + + # STEP 7: Broadcast long poll information + for deployment_id, deployment_state in self._deployment_states.items(): + deployment_state.broadcast_running_replicas_if_changed() + deployment_state.broadcast_deployment_config_if_changed() + if deployment_state.should_autoscale(): + self._autoscaling_state_manager.update_running_replica_ids( + deployment_id=deployment_id, + running_replicas=deployment_state.get_running_replica_ids(), + ) + + # STEP 8: Cleanup + for deployment_id in deleted_ids: + self._deployment_scheduler.on_deployment_deleted(deployment_id) + self._autoscaling_state_manager.deregister_deployment(deployment_id) + del self._deployment_states[deployment_id] + if ( + deployment_id.app_name in self._app_deployment_mapping + and deployment_id.name + in self._app_deployment_mapping[deployment_id.app_name] + ): + self._app_deployment_mapping[deployment_id.app_name].remove( + deployment_id.name + ) + # Clean up the app_name entry if no deployments are left + if not self._app_deployment_mapping[deployment_id.app_name]: + del self._app_deployment_mapping[deployment_id.app_name] + + if len(deleted_ids): + self._record_deployment_usage() + + return any_recovering + + def _handle_scheduling_request_failures( + self, + deployment_id: DeploymentID, + scheduling_requests: List[ReplicaSchedulingRequest], + ): + """Updates internal datastructures when replicas fail to be scheduled.""" + failed_replicas: List[ReplicaID] = [] + for scheduling_request in scheduling_requests: + if ( + scheduling_request.status + == ReplicaSchedulingRequestStatus.PLACEMENT_GROUP_CREATION_FAILED + ): + failed_replicas.append(scheduling_request.replica_id) + self._deployment_states[deployment_id].record_replica_startup_failure( + "Replica scheduling failed. Failed to create a placement " + f"group for replica {scheduling_request.replica_id}. " + "See Serve controller logs for more details." + ) + elif ( + scheduling_request.status + == ReplicaSchedulingRequestStatus.ACTOR_CREATION_FAILED + ): + failed_replicas.append(scheduling_request.replica_id) + self._deployment_states[deployment_id].record_replica_startup_failure( + "Replica scheduling failed. Failed to create an actor " + f"for replica {scheduling_request.replica_id}. " + "See Serve controller logs for more details." + ) + if failed_replicas: + self._deployment_states[deployment_id].stop_replicas(failed_replicas) + + def _record_deployment_usage(self): + ServeUsageTag.NUM_DEPLOYMENTS.record(str(len(self._deployment_states))) + + num_gpu_deployments = 0 + for deployment_state in self._deployment_states.values(): + if ( + deployment_state.target_info is not None + and deployment_state.target_info.replica_config is not None + and deployment_state.target_info.replica_config.ray_actor_options + is not None + and ( + deployment_state.target_info.replica_config.ray_actor_options.get( + "num_gpus", 0 + ) + > 0 + ) + ): + num_gpu_deployments += 1 + ServeUsageTag.NUM_GPU_DEPLOYMENTS.record(str(num_gpu_deployments)) + + def record_request_routing_info(self, info: RequestRoutingInfo) -> None: + """ + Record request routing information for a replica. + + Args: + info: Request routing info including deployment name, replica tag, + multiplex model ids, and routing stats. + """ + deployment_id = info.replica_id.deployment_id + if deployment_id not in self._deployment_states: + app_msg = f" in application '{deployment_id.app_name}'" + logger.error( + f"Deployment '{deployment_id.name}'{app_msg} not found in state " + "manager." + ) + return + self._deployment_states[deployment_id].record_request_routing_info(info) + + def get_active_node_ids(self) -> Set[str]: + """Return set of node ids with running replicas of any deployment. + + This is used to determine which node has replicas. Only nodes with replicas and + head node should have active proxies. + """ + node_ids = set() + for deployment_state in self._deployment_states.values(): + node_ids.update(deployment_state.get_active_node_ids()) + return node_ids diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/endpoint_state.py b/venv/lib/python3.10/site-packages/ray/serve/_private/endpoint_state.py new file mode 100644 index 0000000000000000000000000000000000000000..fd2074fd66693d750bf64eb49dbe7e84450bed0d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/endpoint_state.py @@ -0,0 +1,109 @@ +import logging +from typing import Any, Dict, Optional + +from ray import cloudpickle +from ray.serve._private.common import DeploymentID, EndpointInfo +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.long_poll import LongPollHost, LongPollNamespace +from ray.serve._private.storage.kv_store import KVStoreBase + +CHECKPOINT_KEY = "serve-endpoint-state-checkpoint" + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class EndpointState: + """Manages all state for endpoints in the system. + + This class is *not* thread safe, so any state-modifying methods should be + called with a lock held. + """ + + def __init__(self, kv_store: KVStoreBase, long_poll_host: LongPollHost): + self._kv_store = kv_store + self._long_poll_host = long_poll_host + self._endpoints: Dict[DeploymentID, EndpointInfo] = dict() + + checkpoint = self._kv_store.get(CHECKPOINT_KEY) + if checkpoint is not None: + self._endpoints = cloudpickle.loads(checkpoint) + + self._notify_route_table_changed() + + def shutdown(self): + self._kv_store.delete(CHECKPOINT_KEY) + + def is_ready_for_shutdown(self) -> bool: + """Returns whether the endpoint checkpoint has been deleted. + + Get the endpoint checkpoint from the kv store. If it is None, then it has been + deleted. + """ + return self._kv_store.get(CHECKPOINT_KEY) is None + + def _checkpoint(self): + self._kv_store.put(CHECKPOINT_KEY, cloudpickle.dumps(self._endpoints)) + + def _notify_route_table_changed(self): + self._long_poll_host.notify_changed( + {LongPollNamespace.ROUTE_TABLE: self._endpoints} + ) + + def _get_endpoint_for_route(self, route: str) -> Optional[DeploymentID]: + for endpoint, info in self._endpoints.items(): + if info.route == route: + return endpoint + + return None + + def update_endpoint( + self, endpoint: DeploymentID, endpoint_info: EndpointInfo + ) -> None: + """Create or update the given endpoint. + + This method is idempotent - if the endpoint already exists it will be + updated to match the given parameters. Calling this twice with the same + arguments is a no-op. + """ + + if self._endpoints.get(endpoint) == endpoint_info: + return + + existing_route_endpoint = self._get_endpoint_for_route(endpoint_info.route) + if existing_route_endpoint is not None and existing_route_endpoint != endpoint: + logger.debug( + f'route_prefix "{endpoint_info.route}" is currently ' + f'registered to deployment "{existing_route_endpoint.name}". ' + f'Re-registering route_prefix "{endpoint_info.route}" to ' + f'deployment "{endpoint.name}".' + ) + del self._endpoints[existing_route_endpoint] + + self._endpoints[endpoint] = endpoint_info + + self._checkpoint() + self._notify_route_table_changed() + + def get_endpoint_route(self, endpoint: DeploymentID) -> Optional[str]: + if endpoint in self._endpoints: + return self._endpoints[endpoint].route + return None + + def get_endpoints(self) -> Dict[DeploymentID, Dict[str, Any]]: + endpoints = {} + for endpoint, info in self._endpoints.items(): + endpoints[endpoint] = { + "route": info.route, + } + return endpoints + + def delete_endpoint(self, endpoint: DeploymentID) -> None: + # This method must be idempotent. We should validate that the + # specified endpoint exists on the client. + if endpoint not in self._endpoints: + return + + del self._endpoints[endpoint] + + self._checkpoint() + self._notify_route_table_changed() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/grpc_util.py b/venv/lib/python3.10/site-packages/ray/serve/_private/grpc_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b562ccfe2fd4d47c42d87f4f0f675df9df5fea8a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/grpc_util.py @@ -0,0 +1,173 @@ +import asyncio +import logging +from copy import deepcopy +from typing import Callable, List, Optional, Sequence, Tuple +from unittest.mock import Mock + +import grpc +from grpc.aio._server import Server + +from ray.exceptions import RayActorError, RayTaskError +from ray.serve._private.constants import ( + DEFAULT_GRPC_SERVER_OPTIONS, + RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S, + SERVE_LOGGER_NAME, +) +from ray.serve._private.proxy_request_response import ResponseStatus +from ray.serve.config import gRPCOptions +from ray.serve.exceptions import BackPressureError, DeploymentUnavailableError +from ray.serve.generated.serve_pb2_grpc import add_RayServeAPIServiceServicer_to_server + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class gRPCGenericServer(Server): + """Custom gRPC server that will override all service method handlers. + + Original implementation see: https://github.com/grpc/grpc/blob/ + 60c1701f87cacf359aa1ad785728549eeef1a4b0/src/python/grpcio/grpc/aio/_server.py + """ + + def __init__( + self, + service_handler_factory: Callable, + *, + extra_options: Optional[List[Tuple[str, str]]] = None, + ): + super().__init__( + thread_pool=None, + generic_handlers=(), + interceptors=(), + maximum_concurrent_rpcs=None, + compression=None, + options=DEFAULT_GRPC_SERVER_OPTIONS + (extra_options or []), + ) + self.generic_rpc_handlers = [] + self.service_handler_factory = service_handler_factory + + def add_generic_rpc_handlers( + self, generic_rpc_handlers: Sequence[grpc.GenericRpcHandler] + ): + """Override generic_rpc_handlers before adding to the gRPC server. + + This function will override all user defined handlers to have + 1. None `response_serializer` so the server can pass back the + raw protobuf bytes to the user. + 2. `unary_unary` is always calling the unary function generated via + `self.service_handler_factory` + 3. `unary_stream` is always calling the streaming function generated via + `self.service_handler_factory` + """ + serve_rpc_handlers = {} + rpc_handler = generic_rpc_handlers[0] + for service_method, method_handler in rpc_handler._method_handlers.items(): + serve_method_handler = method_handler._replace( + response_serializer=None, + unary_unary=self.service_handler_factory( + service_method=service_method, + stream=False, + ), + unary_stream=self.service_handler_factory( + service_method=service_method, + stream=True, + ), + ) + serve_rpc_handlers[service_method] = serve_method_handler + generic_rpc_handlers[0]._method_handlers = serve_rpc_handlers + self.generic_rpc_handlers.append(generic_rpc_handlers) + super().add_generic_rpc_handlers(generic_rpc_handlers) + + +async def start_grpc_server( + service_handler_factory: Callable, + grpc_options: gRPCOptions, + *, + event_loop: asyncio.AbstractEventLoop, + enable_so_reuseport: bool = False, +) -> asyncio.Task: + """Start a gRPC server that handles requests with the service handler factory. + + Returns a task that blocks until the server exits (e.g., due to error). + """ + from ray.serve._private.default_impl import add_grpc_address + + server = gRPCGenericServer( + service_handler_factory, + extra_options=[("grpc.so_reuseport", str(int(enable_so_reuseport)))], + ) + add_grpc_address(server, f"[::]:{grpc_options.port}") + + # Add built-in gRPC service and user-defined services to the server. + # We pass a mock servicer because the actual implementation will be overwritten + # in the gRPCGenericServer implementation. + mock_servicer = Mock() + for servicer_fn in [ + add_RayServeAPIServiceServicer_to_server + ] + grpc_options.grpc_servicer_func_callable: + servicer_fn(mock_servicer, server) + + await server.start() + return event_loop.create_task(server.wait_for_termination()) + + +def get_grpc_response_status( + exc: BaseException, request_timeout_s: float, request_id: str +) -> ResponseStatus: + if isinstance(exc, TimeoutError): + message = f"Request timed out after {request_timeout_s}s." + return ResponseStatus( + code=grpc.StatusCode.DEADLINE_EXCEEDED, + is_error=True, + message=message, + ) + elif isinstance(exc, asyncio.CancelledError): + message = f"Client for request {request_id} disconnected." + return ResponseStatus( + code=grpc.StatusCode.CANCELLED, + is_error=True, + message=message, + ) + elif isinstance(exc, (BackPressureError, DeploymentUnavailableError)): + if isinstance(exc, RayTaskError): + logger.warning(f"Request failed: {exc}", extra={"log_to_stderr": False}) + return ResponseStatus( + code=grpc.StatusCode.UNAVAILABLE, + is_error=True, + message=exc.message, + ) + else: + if isinstance(exc, (RayActorError, RayTaskError)): + logger.warning(f"Request failed: {exc}", extra={"log_to_stderr": False}) + else: + logger.exception("Request failed due to unexpected error.") + return ResponseStatus( + code=grpc.StatusCode.INTERNAL, + is_error=True, + message=str(exc), + ) + + +def set_grpc_code_and_details( + context: grpc._cython.cygrpc._ServicerContext, status: ResponseStatus +): + # Only the latest code and details will take effect. If the user already + # set them to a truthy value in the context, skip setting them with Serve's + # default values. By default, if nothing is set, the code is 0 and the + # details is "", which both are falsy. So if the user did not set them or + # if they're explicitly set to falsy values, such as None, Serve will + # continue to set them with our default values. + if not context.code(): + context.set_code(status.code) + if not context.details(): + context.set_details(status.message) + + +def set_proxy_default_grpc_options(grpc_options) -> gRPCOptions: + grpc_options = deepcopy(grpc_options) or gRPCOptions() + + if grpc_options.request_timeout_s or RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S: + grpc_options.request_timeout_s = ( + grpc_options.request_timeout_s or RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S + ) + + return grpc_options diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/handle_options.py b/venv/lib/python3.10/site-packages/ray/serve/_private/handle_options.py new file mode 100644 index 0000000000000000000000000000000000000000..d0438f4ec3d7af2c57e143587868b3a057e51978 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/handle_options.py @@ -0,0 +1,72 @@ +from abc import ABC, abstractmethod +from dataclasses import dataclass, fields + +import ray +from ray.serve._private.common import DeploymentHandleSource +from ray.serve._private.utils import DEFAULT + + +@dataclass(frozen=True) +class InitHandleOptionsBase(ABC): + """Init options for each ServeHandle instance. + + These fields can be set by calling `.init()` on a handle before + sending the first request. + """ + + _prefer_local_routing: bool = False + _source: DeploymentHandleSource = DeploymentHandleSource.UNKNOWN + + @classmethod + @abstractmethod + def create(cls, **kwargs) -> "InitHandleOptionsBase": + raise NotImplementedError + + +@dataclass(frozen=True) +class InitHandleOptions(InitHandleOptionsBase): + @classmethod + def create(cls, **kwargs) -> "InitHandleOptions": + for k in list(kwargs.keys()): + if kwargs[k] == DEFAULT.VALUE: + # Use default value + del kwargs[k] + + # Detect replica source for handles + if ( + "_source" not in kwargs + and ray.serve.context._get_internal_replica_context() is not None + ): + kwargs["_source"] = DeploymentHandleSource.REPLICA + + return cls(**kwargs) + + +@dataclass(frozen=True) +class DynamicHandleOptionsBase(ABC): + """Dynamic options for each ServeHandle instance. + + These fields can be changed by calling `.options()` on a handle. + """ + + method_name: str = "__call__" + multiplexed_model_id: str = "" + stream: bool = False + + @abstractmethod + def copy_and_update(self, **kwargs) -> "DynamicHandleOptionsBase": + pass + + +@dataclass(frozen=True) +class DynamicHandleOptions(DynamicHandleOptionsBase): + def copy_and_update(self, **kwargs) -> "DynamicHandleOptions": + new_kwargs = {} + + for f in fields(self): + if f.name not in kwargs or kwargs[f.name] == DEFAULT.VALUE: + new_kwargs[f.name] = getattr(self, f.name) + else: + new_kwargs[f.name] = kwargs[f.name] + + return DynamicHandleOptions(**new_kwargs) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/http_util.py b/venv/lib/python3.10/site-packages/ray/serve/_private/http_util.py new file mode 100644 index 0000000000000000000000000000000000000000..e34544df967406492f66fb75500b54d3e50c9f4a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/http_util.py @@ -0,0 +1,841 @@ +import asyncio +import inspect +import json +import logging +import pickle +import socket +from collections import deque +from copy import deepcopy +from dataclasses import dataclass +from typing import ( + Any, + AsyncGenerator, + Awaitable, + Callable, + List, + Optional, + Tuple, + Type, + Union, +) + +import starlette +import uvicorn +from fastapi import FastAPI +from fastapi.encoders import jsonable_encoder +from packaging import version +from starlette.datastructures import MutableHeaders +from starlette.middleware import Middleware +from starlette.types import ASGIApp, Message, Receive, Scope, Send +from uvicorn.config import Config +from uvicorn.lifespan.on import LifespanOn + +from ray._common.pydantic_compat import IS_PYDANTIC_2 +from ray.exceptions import RayActorError, RayTaskError +from ray.serve._private.common import RequestMetadata +from ray.serve._private.constants import ( + RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S, + RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH, + RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S, + SERVE_HTTP_REQUEST_ID_HEADER, + SERVE_LOGGER_NAME, +) +from ray.serve._private.proxy_request_response import ResponseStatus +from ray.serve._private.utils import ( + call_function_from_import_path, + generate_request_id, + serve_encoders, +) +from ray.serve.config import HTTPOptions +from ray.serve.exceptions import ( + BackPressureError, + DeploymentUnavailableError, + RayServeException, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@dataclass(frozen=True) +class ASGIArgs: + scope: Scope + receive: Receive + send: Send + + def to_args_tuple(self) -> Tuple[Scope, Receive, Send]: + return (self.scope, self.receive, self.send) + + def to_starlette_request(self) -> starlette.requests.Request: + return starlette.requests.Request( + *self.to_args_tuple(), + ) + + +def make_buffered_asgi_receive(serialized_body: bytes) -> Receive: + """Returns an ASGI receiver that returns the provided buffered body.""" + + # Simulates receiving HTTP body from TCP socket. In reality, the body has + # already been streamed in chunks and stored in serialized_body. + received = False + + async def mock_receive(): + nonlocal received + + # If the request has already been received, starlette will keep polling + # for HTTP disconnect. We will pause forever. The coroutine should be + # cancelled by starlette after the response has been sent. + if received: + block_forever = asyncio.Event() + await block_forever.wait() + + received = True + return {"body": serialized_body, "type": "http.request", "more_body": False} + + return mock_receive + + +def convert_object_to_asgi_messages( + obj: Optional[Any] = None, status_code: int = 200 +) -> List[Message]: + """Serializes the provided object and converts it to ASGI messages. + + These ASGI messages can be sent via an ASGI `send` interface to comprise an HTTP + response. + """ + body = None + content_type = None + if obj is None: + body = b"" + content_type = b"text/plain" + elif isinstance(obj, bytes): + body = obj + content_type = b"text/plain" + elif isinstance(obj, str): + body = obj.encode("utf-8") + content_type = b"text/plain; charset=utf-8" + else: + # `separators=(",", ":")` will remove all whitespaces between separators in the + # json string and return a minimized json string. This helps to reduce the size + # of the response similar to Starlette's JSONResponse. + body = json.dumps( + jsonable_encoder(obj, custom_encoder=serve_encoders), + separators=(",", ":"), + ).encode() + content_type = b"application/json" + + return [ + { + "type": "http.response.start", + "status": status_code, + "headers": [[b"content-type", content_type]], + }, + {"type": "http.response.body", "body": body}, + ] + + +class Response: + """ASGI compliant response class. + + It is expected to be called in async context and pass along + `scope, receive, send` as in ASGI spec. + + >>> from ray.serve.http_util import Response # doctest: +SKIP + >>> scope, receive = ... # doctest: +SKIP + >>> await Response({"k": "v"}).send(scope, receive, send) # doctest: +SKIP + """ + + def __init__(self, content=None, status_code=200): + """Construct a HTTP Response based on input type. + + Args: + content: Any JSON serializable object. + status_code (int, optional): Default status code is 200. + """ + self._messages = convert_object_to_asgi_messages( + obj=content, + status_code=status_code, + ) + + async def send(self, scope, receive, send): + for message in self._messages: + await send(message) + + +async def receive_http_body(scope, receive, send): + body_buffer = [] + more_body = True + while more_body: + message = await receive() + assert message["type"] == "http.request" + + more_body = message["more_body"] + body_buffer.append(message["body"]) + + return b"".join(body_buffer) + + +class MessageQueue(Send): + """Queue enables polling for received or sent messages. + + Implements the ASGI `Send` interface. + + This class: + - Is *NOT* thread safe and should only be accessed from a single asyncio + event loop. + - Assumes a single consumer of the queue (concurrent calls to + `get_messages_nowait` and `wait_for_message` is undefined behavior). + """ + + def __init__(self): + self._message_queue = deque() + self._new_message_event = asyncio.Event() + self._closed = False + self._error = None + + def close(self): + """Close the queue, rejecting new messages. + + Once the queue is closed, existing messages will be returned from + `get_messages_nowait` and subsequent calls to `wait_for_message` will + always return immediately. + """ + self._closed = True + self._new_message_event.set() + + def set_error(self, e: BaseException): + self._error = e + + def put_nowait(self, message: Message): + self._message_queue.append(message) + self._new_message_event.set() + + async def __call__(self, message: Message): + """Send a message, putting it on the queue. + + `RuntimeError` is raised if the queue has been closed using `.close()`. + """ + if self._closed: + raise RuntimeError("New messages cannot be sent after the queue is closed.") + + self.put_nowait(message) + + async def wait_for_message(self): + """Wait until at least one new message is available. + + If a message is available, this method will return immediately on each call + until `get_messages_nowait` is called. + + After the queue is closed using `.close()`, this will always return + immediately. + """ + if not self._closed: + await self._new_message_event.wait() + + def get_messages_nowait(self) -> List[Message]: + """Returns all messages that are currently available (non-blocking). + + At least one message will be present if `wait_for_message` had previously + returned and a subsequent call to `wait_for_message` blocks until at + least one new message is available. + """ + messages = [] + while len(self._message_queue) > 0: + messages.append(self._message_queue.popleft()) + + self._new_message_event.clear() + return messages + + async def get_one_message(self) -> Message: + """This blocks until a message is ready. + + This method should not be used together with get_messages_nowait. + Please use either `get_one_message` or `get_messages_nowait`. + + Raises: + StopAsyncIteration: if the queue is closed and there are no + more messages. + Exception (self._error): if there are no more messages in + the queue and an error has been set. + """ + + if self._error: + raise self._error + + await self._new_message_event.wait() + + if len(self._message_queue) > 0: + msg = self._message_queue.popleft() + + if len(self._message_queue) == 0 and not self._closed: + self._new_message_event.clear() + + return msg + elif len(self._message_queue) == 0 and self._error: + raise self._error + elif len(self._message_queue) == 0 and self._closed: + raise StopAsyncIteration + + async def fetch_messages_from_queue( + self, call_fut: asyncio.Future + ) -> AsyncGenerator[List[Any], None]: + """Repeatedly consume messages from the queue and yield them. + + This is used to fetch queue messages in the system event loop in + a thread-safe manner. + + Args: + call_fut: The async Future pointing to the task from the user + code event loop that is pushing messages onto the queue. + + Yields: + List[Any]: Messages from the queue. + """ + # Repeatedly consume messages from the queue. + wait_for_msg_task = None + try: + while True: + wait_for_msg_task = asyncio.create_task(self.wait_for_message()) + done, _ = await asyncio.wait( + [call_fut, wait_for_msg_task], return_when=asyncio.FIRST_COMPLETED + ) + + messages = self.get_messages_nowait() + if messages: + yield messages + + # Exit once `call_fut` has finished. In this case, all + # messages must have already been sent. + if call_fut in done: + break + + e = call_fut.exception() + if e is not None: + raise e from None + finally: + if not call_fut.done(): + call_fut.cancel() + + if wait_for_msg_task is not None and not wait_for_msg_task.done(): + wait_for_msg_task.cancel() + + +class ASGIReceiveProxy: + """Proxies ASGI receive from an actor. + + The `receive_asgi_messages` callback will be called repeatedly to fetch messages + until a disconnect message is received. + """ + + def __init__( + self, + scope: Scope, + request_metadata: RequestMetadata, + receive_asgi_messages: Callable[[RequestMetadata], Awaitable[bytes]], + ): + self._type = scope["type"] # Either 'http' or 'websocket'. + # Lazy init the queue to ensure it is created in the user code event loop. + self._queue = None + self._request_metadata = request_metadata + self._receive_asgi_messages = receive_asgi_messages + self._disconnect_message = None + + def _get_default_disconnect_message(self) -> Message: + """Return the appropriate disconnect message based on the connection type. + + HTTP ASGI spec: + https://asgi.readthedocs.io/en/latest/specs/www.html#disconnect-receive-event + + WS ASGI spec: + https://asgi.readthedocs.io/en/latest/specs/www.html#disconnect-receive-event-ws + """ + if self._type == "websocket": + return { + "type": "websocket.disconnect", + # 1005 is the default disconnect code according to the ASGI spec. + "code": 1005, + } + else: + return {"type": "http.disconnect"} + + @property + def queue(self) -> asyncio.Queue: + if self._queue is None: + self._queue = asyncio.Queue() + + return self._queue + + async def fetch_until_disconnect(self): + """Fetch messages repeatedly until a disconnect message is received. + + If a disconnect message is received, this function exits and returns it. + + If an exception occurs, it will be raised on the next __call__ and no more + messages will be received. + """ + while True: + try: + pickled_messages = await self._receive_asgi_messages( + self._request_metadata + ) + if isinstance(pickled_messages, bytes): + messages = pickle.loads(pickled_messages) + else: + messages = ( + pickled_messages + if isinstance(pickled_messages, list) + else [pickled_messages] + ) + + for message in messages: + self.queue.put_nowait(message) + + if message["type"] in {"http.disconnect", "websocket.disconnect"}: + self._disconnect_message = message + return + except KeyError: + # KeyError can be raised if the request is no longer active in the proxy + # (i.e., the user disconnects). This is expected behavior and we should + # not log an error: https://github.com/ray-project/ray/issues/43290. + message = self._get_default_disconnect_message() + self.queue.put_nowait(message) + self._disconnect_message = message + return + except Exception as e: + # Raise unexpected exceptions in the next `__call__`. + self.queue.put_nowait(e) + return + + async def __call__(self) -> Message: + """Return the next message once available. + + This will repeatedly return a disconnect message once it's been received. + """ + if self.queue.empty() and self._disconnect_message is not None: + return self._disconnect_message + + message = await self.queue.get() + if isinstance(message, Exception): + raise message + + return message + + +def make_fastapi_class_based_view(fastapi_app, cls: Type) -> None: + """Transform the `cls`'s methods and class annotations to FastAPI routes. + + Modified from + https://github.com/dmontagu/fastapi-utils/blob/master/fastapi_utils/cbv.py + + Usage: + >>> from fastapi import FastAPI + >>> app = FastAPI() # doctest: +SKIP + >>> class A: # doctest: +SKIP + ... @app.route("/{i}") # doctest: +SKIP + ... def func(self, i: int) -> str: # doctest: +SKIP + ... return self.dep + i # doctest: +SKIP + >>> # just running the app won't work, here. + >>> make_fastapi_class_based_view(app, A) # doctest: +SKIP + >>> # now app can be run properly + """ + # Delayed import to prevent ciruclar imports in workers. + from fastapi import APIRouter, Depends + from fastapi.routing import APIRoute, APIWebSocketRoute + + def get_current_servable_instance(): + from ray import serve + + return serve.get_replica_context().servable_object + + # Find all the class method routes + class_method_routes = [ + route + for route in fastapi_app.routes + if + # User defined routes must all be APIRoute or APIWebSocketRoute. + isinstance(route, (APIRoute, APIWebSocketRoute)) + # We want to find the route that's bound to the `cls`. + # NOTE(simon): we can't use `route.endpoint in inspect.getmembers(cls)` + # because the FastAPI supports different routes for the methods with + # same name. See #17559. + and (cls.__qualname__ in route.endpoint.__qualname__) + ] + + # Modify these routes and mount it to a new APIRouter. + # We need to to this (instead of modifying in place) because we want to use + # the laster fastapi_app.include_router to re-run the dependency analysis + # for each routes. + new_router = APIRouter() + for route in class_method_routes: + fastapi_app.routes.remove(route) + + # This block just adds a default values to the self parameters so that + # FastAPI knows to inject the object when calling the route. + # Before: def method(self, i): ... + # After: def method(self=Depends(...), *, i):... + old_endpoint = route.endpoint + old_signature = inspect.signature(old_endpoint) + old_parameters = list(old_signature.parameters.values()) + if len(old_parameters) == 0: + # TODO(simon): make it more flexible to support no arguments. + raise RayServeException( + "Methods in FastAPI class-based view must have ``self`` as " + "their first argument." + ) + old_self_parameter = old_parameters[0] + new_self_parameter = old_self_parameter.replace( + default=Depends(get_current_servable_instance) + ) + new_parameters = [new_self_parameter] + [ + # Make the rest of the parameters keyword only because + # the first argument is no longer positional. + parameter.replace(kind=inspect.Parameter.KEYWORD_ONLY) + for parameter in old_parameters[1:] + ] + new_signature = old_signature.replace(parameters=new_parameters) + route.endpoint.__signature__ = new_signature + route.endpoint._serve_cls = cls + new_router.routes.append(route) + fastapi_app.include_router(new_router) + + routes_to_remove = list() + for route in fastapi_app.routes: + if not isinstance(route, (APIRoute, APIWebSocketRoute)): + continue + + # If there is a response model, FastAPI creates a copy of the fields. + # But FastAPI creates the field incorrectly by missing the outer_type_. + if ( + # TODO(edoakes): I don't think this check is complete because we need + # to support v1 models in v2 (from pydantic.v1 import *). + not IS_PYDANTIC_2 + and isinstance(route, APIRoute) + and route.response_model + ): + route.secure_cloned_response_field.outer_type_ = ( + route.response_field.outer_type_ + ) + + # Remove endpoints that belong to other class based views. + serve_cls = getattr(route.endpoint, "_serve_cls", None) + if serve_cls is not None and serve_cls != cls: + routes_to_remove.append(route) + fastapi_app.routes[:] = [r for r in fastapi_app.routes if r not in routes_to_remove] + + +def set_socket_reuse_port(sock: socket.socket) -> bool: + """Mutate a socket object to allow multiple process listening on the same port. + + Returns: + success: whether the setting was successful. + """ + try: + # These two socket options will allow multiple process to bind the the + # same port. Kernel will evenly load balance among the port listeners. + # Note: this will only work on Linux. + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, "SO_REUSEPORT"): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + # In some Python binary distribution (e.g., conda py3.6), this flag + # was not present at build time but available in runtime. But + # Python relies on compiler flag to include this in binary. + # Therefore, in the absence of socket.SO_REUSEPORT, we try + # to use `15` which is value in linux kernel. + # https://github.com/torvalds/linux/blob/master/tools/include/uapi/asm-generic/socket.h#L27 + else: + sock.setsockopt(socket.SOL_SOCKET, 15, 1) + return True + except Exception as e: + logger.debug( + f"Setting SO_REUSEPORT failed because of {e}. SO_REUSEPORT is disabled." + ) + return False + + +class ASGIAppReplicaWrapper: + """Provides a common wrapper for replicas running an ASGI app.""" + + def __init__(self, app_or_func: Union[ASGIApp, Callable]): + if inspect.isfunction(app_or_func): + self._asgi_app = app_or_func() + else: + self._asgi_app = app_or_func + + # Use uvicorn's lifespan handling code to properly deal with + # startup and shutdown event. + # If log_config is not None, uvicorn will use the default logger. + # and that interferes with our logging setup. + self._serve_asgi_lifespan = LifespanOn( + Config( + self._asgi_app, + lifespan="on", + log_level=None, + log_config=None, + access_log=False, + ) + ) + + # Replace uvicorn logger with our own. + self._serve_asgi_lifespan.logger = logger + + @property + def app(self) -> ASGIApp: + return self._asgi_app + + @property + def docs_path(self) -> Optional[str]: + if isinstance(self._asgi_app, FastAPI): + return self._asgi_app.docs_url + + async def _run_asgi_lifespan_startup(self): + # LifespanOn's logger logs in INFO level thus becomes spammy + # Within this block we temporarily uplevel for cleaner logging + from ray.serve._private.logging_utils import LoggingContext + + with LoggingContext(self._serve_asgi_lifespan.logger, level=logging.WARNING): + await self._serve_asgi_lifespan.startup() + if self._serve_asgi_lifespan.should_exit: + raise RuntimeError( + "ASGI lifespan startup failed. Check replica logs for details." + ) + + async def __call__( + self, + scope: Scope, + receive: Receive, + send: Send, + ) -> Optional[ASGIApp]: + """Calls into the wrapped ASGI app.""" + await self._asgi_app( + scope, + receive, + send, + ) + + # NOTE: __del__ must be async so that we can run ASGI shutdown + # in the same event loop. + async def __del__(self): + # LifespanOn's logger logs in INFO level thus becomes spammy. + # Within this block we temporarily uplevel for cleaner logging. + from ray.serve._private.logging_utils import LoggingContext + + with LoggingContext(self._serve_asgi_lifespan.logger, level=logging.WARNING): + await self._serve_asgi_lifespan.shutdown() + + +def validate_http_proxy_callback_return( + middlewares: Any, +) -> [Middleware]: + """Validate the return value of HTTP proxy callback. + + Middlewares should be a list of Starlette middlewares. If it is None, we + will treat it as an empty list. If it is not a list, we will raise an + error. If it is a list, we will check if all the items in the list are + Starlette middlewares. + """ + + if middlewares is None: + middlewares = [] + if not isinstance(middlewares, list): + raise ValueError( + "HTTP proxy callback must return a list of Starlette middlewares." + ) + else: + # All middlewares must be Starlette middlewares. + # https://www.starlette.io/middleware/#using-pure-asgi-middleware + for middleware in middlewares: + if not issubclass(type(middleware), Middleware): + raise ValueError( + "HTTP proxy callback must return a list of Starlette middlewares, " + f"instead got {type(middleware)} type item in the list." + ) + return middlewares + + +class RequestIdMiddleware: + def __init__(self, app: ASGIApp): + self._app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send): + headers = MutableHeaders(scope=scope) + request_id = headers.get(SERVE_HTTP_REQUEST_ID_HEADER) + + if request_id is None: + request_id = generate_request_id() + headers.append(SERVE_HTTP_REQUEST_ID_HEADER, request_id) + + async def send_with_request_id(message: Message): + if message["type"] == "http.response.start": + headers = MutableHeaders(scope=message) + headers.append("X-Request-ID", request_id) + if message["type"] == "websocket.accept": + message["X-Request-ID"] = request_id + await send(message) + + await self._app(scope, receive, send_with_request_id) + + +def _apply_middlewares(app: ASGIApp, middlewares: List[Callable]) -> ASGIApp: + """Wrap the ASGI app with the provided middlewares. + + The built-in RequestIdMiddleware will always be applied first. + """ + for middleware in [Middleware(RequestIdMiddleware)] + middlewares: + if version.parse(starlette.__version__) < version.parse("0.35.0"): + app = middleware.cls(app, **middleware.options) + else: + # In starlette >= 0.35.0, middleware.options does not exist: + # https://github.com/encode/starlette/pull/2381. + app = middleware.cls( + app, + *middleware.args, + **middleware.kwargs, + ) + + return app + + +async def start_asgi_http_server( + app: ASGIApp, + http_options: HTTPOptions, + *, + event_loop: asyncio.AbstractEventLoop, + enable_so_reuseport: bool = False, +) -> asyncio.Task: + """Start an HTTP server to run the ASGI app. + + Returns a task that blocks until the server exits (e.g., due to error). + """ + app = _apply_middlewares(app, http_options.middlewares) + + sock = socket.socket() + if enable_so_reuseport: + set_socket_reuse_port(sock) + + try: + sock.bind((http_options.host, http_options.port)) + except OSError as e: + raise RuntimeError( + f"Failed to bind to address '{http_options.host}:{http_options.port}'." + ) from e + + # Even though we set log_level=None, uvicorn adds MessageLoggerMiddleware + # if log level for uvicorn.error is not set. And MessageLoggerMiddleware + # has no use to us. + logging.getLogger("uvicorn.error").level = logging.CRITICAL + + # NOTE: We have to use lower level uvicorn Config and Server + # class because we want to run the server as a coroutine. The only + # alternative is to call uvicorn.run which is blocking. + server = uvicorn.Server( + config=uvicorn.Config( + lambda: app, + factory=True, + host=http_options.host, + port=http_options.port, + root_path=http_options.root_path, + timeout_keep_alive=http_options.keep_alive_timeout_s, + loop=event_loop, + lifespan="off", + access_log=False, + log_level=None, + log_config=None, + ) + ) + + # NOTE(edoakes): we need to override install_signal_handlers here + # because the existing implementation fails if it isn't running in + # the main thread and uvicorn doesn't expose a way to configure it. + server.install_signal_handlers = lambda: None + + return event_loop.create_task(server.serve(sockets=[sock])) + + +def get_http_response_status( + exc: BaseException, request_timeout_s: float, request_id: str +) -> ResponseStatus: + if isinstance(exc, TimeoutError): + return ResponseStatus( + code=408, + is_error=True, + message=f"Request {request_id} timed out after {request_timeout_s}s.", + ) + + elif isinstance(exc, asyncio.CancelledError): + message = f"Client for request {request_id} disconnected, cancelling request." + logger.info(message) + return ResponseStatus( + code=499, + is_error=True, + message=message, + ) + elif isinstance(exc, (BackPressureError, DeploymentUnavailableError)): + if isinstance(exc, RayTaskError): + logger.warning(f"Request failed: {exc}", extra={"log_to_stderr": False}) + return ResponseStatus( + code=503, + is_error=True, + message=exc.message, + ) + else: + if isinstance(exc, (RayActorError, RayTaskError)): + logger.warning(f"Request failed: {exc}", extra={"log_to_stderr": False}) + else: + logger.exception("Request failed due to unexpected error.") + return ResponseStatus( + code=500, + is_error=True, + message=str(exc), + ) + + +def send_http_response_on_exception( + status: ResponseStatus, response_started: bool +) -> List[Message]: + if response_started or status.code not in (408, 503): + return [] + return convert_object_to_asgi_messages( + status.message, + status_code=status.code, + ) + + +def configure_http_options_with_defaults(http_options: HTTPOptions) -> HTTPOptions: + """Enhanced configuration with component-specific options.""" + + http_options = deepcopy(http_options) + + # Apply environment defaults + if (RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S or 0) > 0: + http_options.keep_alive_timeout_s = RAY_SERVE_HTTP_KEEP_ALIVE_TIMEOUT_S + + # TODO: Deprecate SERVE_REQUEST_PROCESSING_TIMEOUT_S env var + if http_options.request_timeout_s or RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S: + http_options.request_timeout_s = ( + http_options.request_timeout_s or RAY_SERVE_REQUEST_PROCESSING_TIMEOUT_S + ) + + http_options.middlewares = http_options.middlewares or [] + + return http_options + + +def configure_http_middlewares(http_options: HTTPOptions) -> HTTPOptions: + http_options = deepcopy(http_options) + + # Add environment variable middleware + if RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH: + logger.info( + f"Calling user-provided callback from import path " + f"'{RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH}'." + ) + + # noinspection PyTypeChecker + http_options.middlewares.extend( + validate_http_proxy_callback_return( + call_function_from_import_path( + RAY_SERVE_HTTP_PROXY_CALLBACK_IMPORT_PATH + ) + ) + ) + + return http_options diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/local_testing_mode.py b/venv/lib/python3.10/site-packages/ray/serve/_private/local_testing_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..e09ad3ff20978fcf948adf5567c98784b63de7c6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/local_testing_mode.py @@ -0,0 +1,337 @@ +import asyncio +import concurrent.futures +import inspect +import logging +import queue +import time +from functools import wraps +from typing import Any, Callable, Coroutine, Dict, Optional, Tuple, Union + +import ray +from ray import cloudpickle +from ray.serve._private.common import DeploymentID, RequestMetadata +from ray.serve._private.constants import ( + RAY_SERVE_RUN_SYNC_IN_THREADPOOL, + SERVE_LOGGER_NAME, +) +from ray.serve._private.replica import UserCallableWrapper +from ray.serve._private.replica_result import ReplicaResult +from ray.serve._private.router import Router +from ray.serve._private.utils import GENERATOR_COMPOSITION_NOT_SUPPORTED_ERROR +from ray.serve.deployment import Deployment +from ray.serve.exceptions import RequestCancelledError +from ray.serve.handle import ( + DeploymentHandle, + DeploymentResponse, + DeploymentResponseGenerator, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +def _validate_deployment_options( + deployment: Deployment, + deployment_id: DeploymentID, +): + if "num_gpus" in deployment.ray_actor_options: + logger.warning( + f"Deployment {deployment_id} has num_gpus configured. " + "CUDA_VISIBLE_DEVICES is not managed automatically in local testing mode. " + ) + + if "runtime_env" in deployment.ray_actor_options: + logger.warning( + f"Deployment {deployment_id} has runtime_env configured. " + "runtime_envs are ignored in local testing mode." + ) + + +def make_local_deployment_handle( + deployment: Deployment, + app_name: str, +) -> DeploymentHandle: + """Constructs an in-process DeploymentHandle. + + This is used in the application build process for local testing mode, + where all deployments of an app run in the local process which enables + faster dev iterations and use of tooling like PDB. + + The user callable will be run on an asyncio loop in a separate thread + (sharing the same code that's used in the replica). + + The constructor for the user callable is run eagerly in this function to + ensure that any exceptions are raised during `serve.run`. + """ + deployment_id = DeploymentID(deployment.name, app_name) + _validate_deployment_options(deployment, deployment_id) + user_callable_wrapper = UserCallableWrapper( + deployment.func_or_class, + deployment.init_args, + deployment.init_kwargs, + deployment_id=deployment_id, + run_sync_methods_in_threadpool=RAY_SERVE_RUN_SYNC_IN_THREADPOOL, + run_user_code_in_separate_thread=True, + local_testing_mode=True, + ) + try: + logger.info(f"Initializing local replica class for {deployment_id}.") + user_callable_wrapper.initialize_callable().result() + user_callable_wrapper.call_reconfigure(deployment.user_config) + except Exception: + logger.exception(f"Failed to initialize deployment {deployment_id}.") + raise + + def _create_local_router( + handle_id: str, deployment_id: DeploymentID, handle_options: Any + ) -> Router: + return LocalRouter( + user_callable_wrapper, + deployment_id=deployment_id, + handle_options=handle_options, + ) + + return DeploymentHandle( + deployment.name, + app_name, + _create_router=_create_local_router, + ) + + +class LocalReplicaResult(ReplicaResult): + """ReplicaResult used by in-process Deployment Handles.""" + + OBJ_REF_NOT_SUPPORTED_ERROR = RuntimeError( + "Converting DeploymentResponses to ObjectRefs is not supported " + "in local testing mode." + ) + + def __init__( + self, + future: concurrent.futures.Future, + *, + request_id: str, + is_streaming: bool = False, + generator_result_queue: Optional[queue.Queue] = None, + ): + self._future = future + self._lazy_asyncio_future = None + self._request_id = request_id + self._is_streaming = is_streaming + + # For streaming requests, results must be written to this queue. + # The queue will be consumed until the future is completed. + self._generator_result_queue = generator_result_queue + if self._is_streaming: + assert ( + self._generator_result_queue is not None + ), "generator_result_queue must be provided for streaming results." + + @property + def _asyncio_future(self) -> asyncio.Future: + if self._lazy_asyncio_future is None: + self._lazy_asyncio_future = asyncio.wrap_future(self._future) + + return self._lazy_asyncio_future + + def _process_response(f: Union[Callable, Coroutine]): + @wraps(f) + def wrapper(self, *args, **kwargs): + try: + return f(self, *args, **kwargs) + except (asyncio.CancelledError, concurrent.futures.CancelledError): + raise RequestCancelledError(self._request_id) + + @wraps(f) + async def async_wrapper(self, *args, **kwargs): + try: + return await f(self, *args, **kwargs) + except (asyncio.CancelledError, concurrent.futures.CancelledError): + raise RequestCancelledError(self._request_id) + + if inspect.iscoroutinefunction(f): + return async_wrapper + else: + return wrapper + + @_process_response + def get(self, timeout_s: Optional[float]): + assert ( + not self._is_streaming + ), "get() can only be called on a non-streaming result." + + try: + return self._future.result(timeout=timeout_s) + except concurrent.futures.TimeoutError: + raise TimeoutError("Timed out waiting for result.") + + @_process_response + async def get_async(self): + assert ( + not self._is_streaming + ), "get_async() can only be called on a non-streaming result." + + return await self._asyncio_future + + @_process_response + def __next__(self): + assert self._is_streaming, "next() can only be called on a streaming result." + + while True: + if self._future.done() and self._generator_result_queue.empty(): + if self._future.exception(): + raise self._future.exception() + else: + raise StopIteration + + try: + return self._generator_result_queue.get(timeout=0.01) + except queue.Empty: + pass + + @_process_response + async def __anext__(self): + assert self._is_streaming, "anext() can only be called on a streaming result." + + # This callback does not pull from the queue, only checks that a result is + # available, else there is a race condition where the future finishes and the + # queue is empty, but this function hasn't returned the result yet. + def _wait_for_result(): + while True: + if self._future.done() or not self._generator_result_queue.empty(): + return + time.sleep(0.01) + + wait_for_result_task = asyncio.get_running_loop().create_task( + asyncio.to_thread(_wait_for_result), + ) + done, _ = await asyncio.wait( + [self._asyncio_future, wait_for_result_task], + return_when=asyncio.FIRST_COMPLETED, + ) + + if not self._generator_result_queue.empty(): + return self._generator_result_queue.get() + + if self._asyncio_future.exception(): + raise self._asyncio_future.exception() + + raise StopAsyncIteration + + def add_done_callback(self, callback: Callable): + self._future.add_done_callback(callback) + + def cancel(self): + self._future.cancel() + + def to_object_ref(self, timeout_s: Optional[float]) -> ray.ObjectRef: + raise self.OBJ_REF_NOT_SUPPORTED_ERROR + + async def to_object_ref_async(self) -> ray.ObjectRef: + raise self.OBJ_REF_NOT_SUPPORTED_ERROR + + def to_object_ref_gen(self) -> ray.ObjectRefGenerator: + raise self.OBJ_REF_NOT_SUPPORTED_ERROR + + +class LocalRouter(Router): + def __init__( + self, + user_callable_wrapper: UserCallableWrapper, + deployment_id: DeploymentID, + handle_options: Any, + ): + self._deployment_id = deployment_id + self._user_callable_wrapper = user_callable_wrapper + assert ( + self._user_callable_wrapper._callable is not None + ), "User callable must already be initialized." + + def running_replicas_populated(self) -> bool: + return True + + def _resolve_deployment_responses( + self, request_args: Tuple[Any], request_kwargs: Dict[str, Any] + ) -> Tuple[Tuple[Any], Dict[str, Any]]: + """Replace DeploymentResponse objects with their results. + + NOTE(edoakes): this currently calls the blocking `.result()` method + on the responses to resolve them to their values. This is a divergence + from the remote codepath where they're resolved concurrently. + """ + + def _new_arg(arg: Any) -> Any: + if isinstance(arg, DeploymentResponse): + new_arg = arg.result(_skip_asyncio_check=True) + elif isinstance(arg, DeploymentResponseGenerator): + raise GENERATOR_COMPOSITION_NOT_SUPPORTED_ERROR + else: + new_arg = arg + + return new_arg + + # Serialize and deserialize the arguments to mimic remote call behavior. + return cloudpickle.loads( + cloudpickle.dumps( + ( + tuple(_new_arg(arg) for arg in request_args), + {k: _new_arg(v) for k, v in request_kwargs.items()}, + ) + ) + ) + + def assign_request( + self, + request_meta: RequestMetadata, + *request_args, + **request_kwargs, + ) -> concurrent.futures.Future[LocalReplicaResult]: + request_args, request_kwargs = self._resolve_deployment_responses( + request_args, request_kwargs + ) + + if request_meta.is_streaming: + generator_result_queue = queue.Queue() + + def generator_result_callback(item: Any): + generator_result_queue.put_nowait(item) + + else: + generator_result_queue = None + generator_result_callback = None + + # Conform to the router interface of returning a future to the ReplicaResult. + if request_meta.is_http_request: + fut = self._user_callable_wrapper._call_http_entrypoint( + request_meta, + request_args, + request_kwargs, + generator_result_callback=generator_result_callback, + ) + elif request_meta.is_streaming: + fut = self._user_callable_wrapper._call_user_generator( + request_meta, + request_args, + request_kwargs, + enqueue=generator_result_callback, + ) + else: + fut = self._user_callable_wrapper.call_user_method( + request_meta, + request_args, + request_kwargs, + ) + noop_future = concurrent.futures.Future() + noop_future.set_result( + LocalReplicaResult( + fut, + request_id=request_meta.request_id, + is_streaming=request_meta.is_streaming, + generator_result_queue=generator_result_queue, + ) + ) + return noop_future + + def shutdown(self): + noop_future = concurrent.futures.Future() + noop_future.set_result(None) + return noop_future diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/logging_utils.py b/venv/lib/python3.10/site-packages/ray/serve/_private/logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d2faa5fbd7f629ea87b59511bf3c114dbaf5cbae --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/logging_utils.py @@ -0,0 +1,563 @@ +import builtins +import logging +import os +import sys +import traceback +from typing import Any, Optional, Tuple + +import ray +from ray._private.ray_constants import LOGGING_ROTATE_BACKUP_COUNT, LOGGING_ROTATE_BYTES +from ray._private.ray_logging.filters import CoreContextFilter +from ray._private.ray_logging.formatters import JSONFormatter, TextFormatter +from ray.serve._private.common import ServeComponentType +from ray.serve._private.constants import ( + RAY_SERVE_ENABLE_CPU_PROFILING, + RAY_SERVE_ENABLE_JSON_LOGGING, + RAY_SERVE_ENABLE_MEMORY_PROFILING, + RAY_SERVE_LOG_TO_STDERR, + SERVE_LOG_APPLICATION, + SERVE_LOG_COMPONENT, + SERVE_LOG_COMPONENT_ID, + SERVE_LOG_DEPLOYMENT, + SERVE_LOG_LEVEL_NAME, + SERVE_LOG_MESSAGE, + SERVE_LOG_RECORD_FORMAT, + SERVE_LOG_REPLICA, + SERVE_LOG_REQUEST_ID, + SERVE_LOG_ROUTE, + SERVE_LOG_TIME, + SERVE_LOG_UNWANTED_ATTRS, + SERVE_LOGGER_NAME, +) +from ray.serve._private.utils import get_component_file_name +from ray.serve.schema import EncodingType, LoggingConfig + +try: + import cProfile +except ImportError: + pass + + +buildin_print = builtins.print + + +class ServeComponentFilter(logging.Filter): + """Serve component filter. + + The filter will add the component name, id, and type to the log record. + """ + + def __init__( + self, + component_name: str, + component_id: str, + component_type: Optional[ServeComponentType] = None, + ): + self.component_name = component_name + self.component_id = component_id + self.component_type = component_type + + def filter(self, record: logging.LogRecord) -> bool: + """Add component attributes to the log record. + + Note: the filter doesn't do any filtering, it only adds the component + attributes. + """ + if self.component_type and self.component_type == ServeComponentType.REPLICA: + setattr(record, SERVE_LOG_DEPLOYMENT, self.component_name) + setattr(record, SERVE_LOG_REPLICA, self.component_id) + setattr(record, SERVE_LOG_COMPONENT, self.component_type) + else: + setattr(record, SERVE_LOG_COMPONENT, self.component_name) + setattr(record, SERVE_LOG_COMPONENT_ID, self.component_id) + + return True + + +class ServeContextFilter(logging.Filter): + """Serve context filter. + + The filter will add the route, request id, app name to the log record. + + Note: the filter doesn't do any filtering, it only adds the serve request context + attributes. + """ + + def filter(self, record): + request_context = ray.serve.context._get_serve_request_context() + if request_context.route: + setattr(record, SERVE_LOG_ROUTE, request_context.route) + if request_context.request_id: + setattr(record, SERVE_LOG_REQUEST_ID, request_context.request_id) + if request_context.app_name: + setattr(record, SERVE_LOG_APPLICATION, request_context.app_name) + return True + + +class ServeLogAttributeRemovalFilter(logging.Filter): + """Serve log attribute removal filter. + + The filter will remove unwanted attributes on the log record so they won't be + included in the structured logs. + + Note: the filter doesn't do any filtering, it only removes unwanted attributes. + """ + + def filter(self, record): + for key in SERVE_LOG_UNWANTED_ATTRS: + if hasattr(record, key): + delattr(record, key) + + return True + + +class ServeFormatter(TextFormatter): + """Serve Logging Formatter + + The formatter will generate the log format on the fly based on the field of record. + Optimized to pre-compute format strings and formatters for better performance. + """ + + COMPONENT_LOG_FMT = f"%({SERVE_LOG_LEVEL_NAME})s %({SERVE_LOG_TIME})s {{{SERVE_LOG_COMPONENT}}} {{{SERVE_LOG_COMPONENT_ID}}} " # noqa:E501 + + def __init__( + self, + component_name: str, + component_id: str, + fmt: Optional[str] = None, + datefmt: Optional[str] = None, + style: str = "%", + validate: bool = True, + ): + super().__init__(fmt, datefmt, style, validate) + self.component_log_fmt = ServeFormatter.COMPONENT_LOG_FMT.format( + component_name=component_name, component_id=component_id + ) + + # Pre-compute format strings and formatters for performance + self._precompute_formatters() + + def set_additional_log_standard_attrs(self, *args, **kwargs): + super().set_additional_log_standard_attrs(*args, **kwargs) + self._precompute_formatters() + + def _precompute_formatters(self): + self.base_formatter = self._create_formatter([]) + self.request_formatter = self._create_formatter( + [SERVE_LOG_RECORD_FORMAT[SERVE_LOG_REQUEST_ID]] + ) + + def _create_formatter(self, initial_attrs: list) -> logging.Formatter: + attrs = initial_attrs.copy() + attrs.extend([f"%({k})s" for k in self.additional_log_standard_attrs]) + attrs.append(SERVE_LOG_RECORD_FORMAT[SERVE_LOG_MESSAGE]) + + format_string = self.component_log_fmt + " ".join(attrs) + return logging.Formatter(format_string) + + def format(self, record: logging.LogRecord) -> str: + """Format the log record into the format string. + + Args: + record: The log record to be formatted. + Returns: + The formatted log record in string format. + """ + # Use pre-computed formatters for better performance + if SERVE_LOG_REQUEST_ID in record.__dict__: + return self.request_formatter.format(record) + else: + return self.base_formatter.format(record) + + +def access_log_msg(*, method: str, route: str, status: str, latency_ms: float): + """Returns a formatted message for an HTTP or ServeHandle access log.""" + return f"{method} {route} {status} {latency_ms:.1f}ms" + + +def log_to_stderr_filter(record: logging.LogRecord) -> bool: + """Filters log records based on a parameter in the `extra` dictionary.""" + if not hasattr(record, "log_to_stderr") or record.log_to_stderr is None: + return True + + return record.log_to_stderr + + +def log_access_log_filter(record: logging.LogRecord) -> bool: + """Filters ray serve access log based on 'serve_access_log' key in `extra` dict.""" + if not hasattr(record, "serve_access_log") or record.serve_access_log is None: + return True + + return not record.serve_access_log + + +def get_component_logger_file_path() -> Optional[str]: + """Returns the relative file path for the Serve logger, if it exists. + + If a logger was configured through configure_component_logger() for the Serve + component that's calling this function, this returns the location of the log file + relative to the ray logs directory. + """ + logger = logging.getLogger(SERVE_LOGGER_NAME) + for handler in logger.handlers: + if isinstance(handler, logging.handlers.MemoryHandler): + absolute_path = handler.target.baseFilename + ray_logs_dir = ray._private.worker._global_node.get_logs_dir_path() + if absolute_path.startswith(ray_logs_dir): + return absolute_path[len(ray_logs_dir) :] + + +class StreamToLogger(object): + """ + Fake file-like stream object that redirects writes to a logger instance. + + This comes from https://stackoverflow.com/a/36296215 directly. + """ + + def __init__(self, logger: logging.Logger, log_level: int, original_object: Any): + self._logger = logger + self._log_level = log_level + self._original_object = original_object + self._linebuf = "" + + def __getattr__(self, attr: str) -> Any: + # getting attributes from the original object + return getattr(self._original_object, attr) + + @staticmethod + def get_stacklevel() -> int: + """Rewind stack to get the stacklevel for the user code. + + Going from the back of the traceback and traverse until it's no longer in + logging_utils.py or site-packages. + """ + reverse_traces = traceback.extract_stack()[::-1] + for index, trace in enumerate(reverse_traces): + if ( + "logging_utils.py" not in trace.filename + and "site-packages" not in trace.filename + ): + return index + return 1 + + def write(self, buf: str): + temp_linebuf = self._linebuf + buf + self._linebuf = "" + for line in temp_linebuf.splitlines(True): + # From the io.TextIOWrapper docs: + # On output, if newline is None, any '\n' characters written + # are translated to the system default line separator. + # By default sys.stdout.write() expects '\n' newlines and then + # translates them so this is still cross-platform. + if line[-1] == "\n": + self._logger.log( + self._log_level, + line.rstrip(), + stacklevel=self.get_stacklevel(), + ) + else: + self._linebuf += line + + def flush(self): + if self._linebuf != "": + self._logger.log( + self._log_level, + self._linebuf.rstrip(), + stacklevel=self.get_stacklevel(), + ) + self._linebuf = "" + + def isatty(self) -> bool: + return True + + +def redirected_print(*objects, sep=" ", end="\n", file=None, flush=False): + """Implement python's print function to redirect logs to Serve's logger. + + If the file is set to anything other than stdout, stderr, or None, call the + builtin print. Else, construct the message and redirect to Serve's logger. + + See https://docs.python.org/3/library/functions.html#print + """ + if file not in [sys.stdout, sys.stderr, None]: + return buildin_print(objects, sep=sep, end=end, file=file, flush=flush) + + serve_logger = logging.getLogger(SERVE_LOGGER_NAME) + message = sep.join(map(str, objects)) + end + # We monkey patched print function, so this is always at stack level 2. + serve_logger.log(logging.INFO, message, stacklevel=2) + + +def configure_component_logger( + *, + component_name: str, + component_id: str, + logging_config: LoggingConfig, + component_type: Optional[ServeComponentType] = None, + max_bytes: Optional[int] = None, + backup_count: Optional[int] = None, + stream_handler_only: bool = False, + buffer_size: int = 1, +): + """Configure a logger to be used by a Serve component. + + The logger will log using a standard format to make components identifiable + using the provided name and unique ID for this instance (e.g., replica ID). + + This logger will *not* propagate its log messages to the parent logger(s). + """ + logger = logging.getLogger(SERVE_LOGGER_NAME) + logger.propagate = False + logger.setLevel(logging_config.log_level) + logger.handlers.clear() + + serve_formatter = ServeFormatter(component_name, component_id) + json_formatter = JSONFormatter() + if logging_config.additional_log_standard_attrs: + json_formatter.set_additional_log_standard_attrs( + logging_config.additional_log_standard_attrs + ) + serve_formatter.set_additional_log_standard_attrs( + logging_config.additional_log_standard_attrs + ) + + # Only add stream handler if RAY_SERVE_LOG_TO_STDERR is True or if + # `stream_handler_only` is set to True. + if RAY_SERVE_LOG_TO_STDERR or stream_handler_only: + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(serve_formatter) + stream_handler.addFilter(log_to_stderr_filter) + stream_handler.addFilter(ServeContextFilter()) + logger.addHandler(stream_handler) + + # Skip setting up file handler and stdout/stderr redirect if `stream_handler_only` + # is set to True. Logger such as default serve logger can be configured outside the + # context of a Serve component, we don't want those logs to redirect into serve's + # logger and log files. + if stream_handler_only: + return + + if logging_config.logs_dir: + logs_dir = logging_config.logs_dir + else: + logs_dir = get_serve_logs_dir() + os.makedirs(logs_dir, exist_ok=True) + + if max_bytes is None: + max_bytes = ray._private.worker._global_node.max_bytes + if backup_count is None: + backup_count = ray._private.worker._global_node.backup_count + + log_file_name = get_component_file_name( + component_name=component_name, + component_id=component_id, + component_type=component_type, + suffix=".log", + ) + + file_handler = logging.handlers.RotatingFileHandler( + os.path.join(logs_dir, log_file_name), + maxBytes=max_bytes, + backupCount=backup_count, + ) + if RAY_SERVE_ENABLE_JSON_LOGGING: + logger.warning( + "'RAY_SERVE_ENABLE_JSON_LOGGING' is deprecated, please use " + "'LoggingConfig' to enable json format." + ) + if RAY_SERVE_ENABLE_JSON_LOGGING or logging_config.encoding == EncodingType.JSON: + file_handler.addFilter(CoreContextFilter()) + file_handler.addFilter(ServeContextFilter()) + file_handler.addFilter( + ServeComponentFilter(component_name, component_id, component_type) + ) + file_handler.setFormatter(json_formatter) + else: + file_handler.setFormatter(serve_formatter) + + if logging_config.enable_access_log is False: + file_handler.addFilter(log_access_log_filter) + + # Remove unwanted attributes from the log record. + file_handler.addFilter(ServeLogAttributeRemovalFilter()) + + # Redirect print, stdout, and stderr to Serve logger, only when it's on the replica. + if not RAY_SERVE_LOG_TO_STDERR and component_type == ServeComponentType.REPLICA: + builtins.print = redirected_print + sys.stdout = StreamToLogger(logger, logging.INFO, sys.stdout) + sys.stderr = StreamToLogger(logger, logging.INFO, sys.stderr) + + # Create a memory handler that buffers log records and flushes to file handler + # Buffer capacity: buffer_size records + # Flush triggers: buffer full, ERROR messages, or explicit flush + memory_handler = logging.handlers.MemoryHandler( + capacity=buffer_size, + target=file_handler, + flushLevel=logging.ERROR, # Auto-flush on ERROR/CRITICAL + ) + + # Add the memory handler instead of the file handler directly + logger.addHandler(memory_handler) + + +def configure_default_serve_logger(): + """Helper function to configure the default Serve logger that's used outside of + individual Serve components.""" + configure_component_logger( + component_name="serve", + component_id=str(os.getpid()), + logging_config=LoggingConfig(), + max_bytes=LOGGING_ROTATE_BYTES, + backup_count=LOGGING_ROTATE_BACKUP_COUNT, + stream_handler_only=True, + ) + + +def configure_component_memory_profiler( + component_name: str, + component_id: str, + component_type: Optional[ServeComponentType] = None, +): + """Configures the memory logger for this component. + + Does nothing if RAY_SERVE_ENABLE_MEMORY_PROFILING is disabled. + """ + + if RAY_SERVE_ENABLE_MEMORY_PROFILING: + logger = logging.getLogger(SERVE_LOGGER_NAME) + + try: + import memray + + logs_dir = get_serve_logs_dir() + memray_file_name = get_component_file_name( + component_name=component_name, + component_id=component_id, + component_type=component_type, + suffix="_memray_0.bin", + ) + memray_file_path = os.path.join(logs_dir, memray_file_name) + + # If the actor restarted, memray requires a new file to start + # tracking memory. + restart_counter = 1 + while os.path.exists(memray_file_path): + memray_file_name = get_component_file_name( + component_name=component_name, + component_id=component_id, + component_type=component_type, + suffix=f"_memray_{restart_counter}.bin", + ) + memray_file_path = os.path.join(logs_dir, memray_file_name) + restart_counter += 1 + + # Memray usually tracks the memory usage of only a block of code + # within a context manager. We explicitly call __enter__ here + # instead of using a context manager to track memory usage across + # all of the caller's code instead. + memray.Tracker(memray_file_path, native_traces=True).__enter__() + + logger.info( + "RAY_SERVE_ENABLE_MEMORY_PROFILING is enabled. Started a " + "memray tracker on this actor. Tracker file located at " + f'"{memray_file_path}"' + ) + + except ImportError: + logger.warning( + "RAY_SERVE_ENABLE_MEMORY_PROFILING is enabled, but memray " + "is not installed. No memory profiling is happening. " + "`pip install memray` to enable memory profiling." + ) + + +def configure_component_cpu_profiler( + component_name: str, + component_id: str, + component_type: Optional[ServeComponentType] = None, +) -> Tuple[Optional[cProfile.Profile], Optional[str]]: + """Configures the CPU profiler for this component. + + Does nothing if RAY_SERVE_ENABLE_CPU_PROFILING is disabled. + + Returns: + 2-tuple containing profiler object and log file name for profile stats. + """ + + if RAY_SERVE_ENABLE_CPU_PROFILING: + logger = logging.getLogger(SERVE_LOGGER_NAME) + + try: + import cProfile + except ImportError: + logger.warning( + "RAY_SERVE_ENABLE_CPU_PROFILING is enabled, but cProfile " + "is not installed. No CPU profiling is happening." + ) + return None, None + try: + # Need marshal to dump data. Check if marshal is installed before + # starting the profiler. + import marshal # noqa: F401 + except ImportError: + logger.warning( + "RAY_SERVE_ENABLE_CPU_PROFILING is enabled, but marshal " + "is not installed. No CPU profiling is happening." + ) + return None, None + + logs_dir = get_serve_logs_dir() + cpu_profiler_file_name = get_component_file_name( + component_name=component_name, + component_id=component_id, + component_type=component_type, + suffix="_cprofile.prof", + ) + cpu_profiler_file_path = os.path.join(logs_dir, cpu_profiler_file_name) + + profile = cProfile.Profile() + profile.enable() + logger.info( + "RAY_SERVE_ENABLE_CPU_PROFILING is enabled. Started cProfile " + "on this actor." + ) + return profile, cpu_profiler_file_path + else: + return None, None + + +def get_serve_logs_dir() -> str: + """Get the directory that stores Serve log files. + + If `ray._private.worker._global_node` is None (running outside the context of Ray), + then the current working directory with subdirectory of serve is used as the logs + directory. Otherwise, the logs directory is determined by the global node's logs + directory path. + """ + if ray._private.worker._global_node is None: + return os.path.join(os.getcwd(), "serve") + + return os.path.join(ray._private.worker._global_node.get_logs_dir_path(), "serve") + + +class LoggingContext: + """ + Context manager to manage logging behaviors within a particular block, such as: + 1) Overriding logging level + + Source (python3 official documentation) + https://docs.python.org/3/howto/logging-cookbook.html#using-a-context-manager-for-selective-logging # noqa: E501 + """ + + def __init__(self, logger, level=None): + self.logger = logger + self.level = level + + def __enter__(self): + if self.level is not None: + self.old_level = self.logger.level + self.logger.setLevel(self.level) + + def __exit__(self, et, ev, tb): + if self.level is not None: + self.logger.setLevel(self.old_level) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/long_poll.py b/venv/lib/python3.10/site-packages/ray/serve/_private/long_poll.py new file mode 100644 index 0000000000000000000000000000000000000000..9d885a9ee9e2afcbb22d08f3a08c8e3b564b8c9c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/long_poll.py @@ -0,0 +1,482 @@ +import asyncio +import logging +import os +import random +from asyncio import sleep +from asyncio.events import AbstractEventLoop +from collections import defaultdict +from collections.abc import Mapping +from dataclasses import dataclass +from enum import Enum, auto +from typing import Any, Callable, DefaultDict, Dict, Optional, Set, Tuple, Union + +import ray +from ray._common.utils import get_or_create_event_loop +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve.generated.serve_pb2 import ( + DeploymentTargetInfo, + EndpointInfo as EndpointInfoProto, + EndpointSet, + LongPollRequest, + LongPollResult, + UpdatedObject as UpdatedObjectProto, +) +from ray.util import metrics + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +# Each LongPollClient will send requests to LongPollHost to poll changes +# as blocking awaitable. This doesn't scale if we have many client instances +# that will slow down, or even block controller actor's event loop if near +# its max_concurrency limit. Therefore we timeout a polling request after +# a few seconds and let each client retry on their end. +# We randomly select a timeout within this range to avoid a "thundering herd" +# when there are many clients subscribing at the same time. +LISTEN_FOR_CHANGE_REQUEST_TIMEOUT_S = ( + float(os.environ.get("LISTEN_FOR_CHANGE_REQUEST_TIMEOUT_S_LOWER_BOUND", "30")), + float(os.environ.get("LISTEN_FOR_CHANGE_REQUEST_TIMEOUT_S_UPPER_BOUND", "60")), +) + + +class LongPollNamespace(Enum): + def __repr__(self): + return f"{self.__class__.__name__}.{self.name}" + + DEPLOYMENT_TARGETS = auto() + ROUTE_TABLE = auto() + GLOBAL_LOGGING_CONFIG = auto() + DEPLOYMENT_CONFIG = auto() + + +@dataclass +class UpdatedObject: + object_snapshot: Any + # The identifier for the object's version. There is not sequential relation + # among different object's snapshot_ids. + snapshot_id: int + + +# Type signature for the update state callbacks. E.g. +# async def update_state(updated_object: Any): +# do_something(updated_object) +UpdateStateCallable = Callable[[Any], None] +KeyType = Union[str, LongPollNamespace, Tuple[LongPollNamespace, str]] + + +class LongPollState(Enum): + TIME_OUT = auto() + + +class LongPollClient: + """The asynchronous long polling client. + + Args: + host_actor: handle to actor embedding LongPollHost. + key_listeners: a dictionary mapping keys to + callbacks to be called on state update for the corresponding keys. + call_in_event_loop: an asyncio event loop + to post the callback into. + """ + + def __init__( + self, + host_actor, + key_listeners: Dict[KeyType, UpdateStateCallable], + call_in_event_loop: AbstractEventLoop, + ) -> None: + # We used to allow this to be optional, but due to Ray Client issue + # we now enforce all long poll client to post callback to event loop + # See https://github.com/ray-project/ray/issues/20971 + assert call_in_event_loop is not None + + self.host_actor = host_actor + self.key_listeners = key_listeners + self.event_loop = call_in_event_loop + self.snapshot_ids: Dict[KeyType, int] = { + # The initial snapshot id for each key is < 0, + # but real snapshot keys in the long poll host are always >= 0, + # so this will always trigger an initial update. + key: -1 + for key in self.key_listeners.keys() + } + self.is_running = True + + self._poll_next() + + def stop(self) -> None: + """Stop the long poll client after the next RPC returns.""" + self.is_running = False + + def add_key_listeners( + self, key_listeners: Dict[KeyType, UpdateStateCallable] + ) -> None: + """Add more key listeners to the client. + The new listeners will only be included in the *next* long poll request; + the current request will continue with the existing listeners. + + If a key is already in the client, the new listener will replace the old one, + but the snapshot ID will be preserved, so the new listener will only be called + on the *next* update to that key. + """ + # We need to run the underlying method in the same event loop that runs + # the long poll loop, because we need to mutate the mapping of snapshot IDs, + # which also needs to be serialized by the long poll's RPC to the + # Serve Controller. If those happened concurrently in different threads, + # we could get a `RuntimeError: dictionary changed size during iteration`. + # See https://github.com/ray-project/ray/pull/52793 for more details. + self.event_loop.call_soon_threadsafe(self._add_key_listeners, key_listeners) + + def _add_key_listeners( + self, key_listeners: Dict[KeyType, UpdateStateCallable] + ) -> None: + """Inner method that actually adds the key listeners, to be called + via call_soon_threadsafe for thread safety. + """ + # Only initialize snapshot ids for *new* keys. + self.snapshot_ids.update( + {key: -1 for key in key_listeners.keys() if key not in self.key_listeners} + ) + self.key_listeners.update(key_listeners) + + def _on_callback_completed(self, trigger_at: int): + """Called after a single callback is completed. + + When the total number of callback completed equals to trigger_at, + _poll_next() will be called. This is designed to make sure we only + _poll_next() after all the state callbacks completed. This is a + way to serialize the callback invocations between object versions. + """ + self._callbacks_processed_count += 1 + if self._callbacks_processed_count == trigger_at: + self._poll_next() + + def _poll_next(self): + """Poll the update. The callback is expected to scheduler another + _poll_next call. + """ + if not self.is_running: + return + + self._callbacks_processed_count = 0 + self._current_ref = self.host_actor.listen_for_change.remote(self.snapshot_ids) + self._current_ref._on_completed(lambda update: self._process_update(update)) + + def _schedule_to_event_loop(self, callback): + # Schedule the next iteration only if the loop is running. + # The event loop might not be running if users used a cached + # version across loops. + if self.event_loop.is_running(): + self.event_loop.call_soon_threadsafe(callback) + else: + logger.error("The event loop is closed, shutting down long poll client.") + self.is_running = False + + def _process_update(self, updates: Dict[str, UpdatedObject]): + if isinstance(updates, (ray.exceptions.RayActorError)): + # This can happen during shutdown where the controller is + # intentionally killed, the client should just gracefully + # exit. + logger.debug("LongPollClient failed to connect to host. Shutting down.") + self.is_running = False + return + + if isinstance(updates, ConnectionError): + logger.warning("LongPollClient connection failed, shutting down.") + self.is_running = False + return + + if isinstance(updates, (ray.exceptions.RayTaskError)): + # Some error happened in the controller. It could be a bug or + # some undesired state. + logger.error("LongPollHost errored\n" + updates.traceback_str) + # We must call this in event loop so it works in Ray Client. + # See https://github.com/ray-project/ray/issues/20971 + self._schedule_to_event_loop(self._poll_next) + return + + if updates == LongPollState.TIME_OUT: + logger.debug("LongPollClient polling timed out. Retrying.") + self._schedule_to_event_loop(self._poll_next) + return + + logger.debug( + f"LongPollClient {self} received updates for keys: " + f"{list(updates.keys())}.", + extra={"log_to_stderr": False}, + ) + if not updates: # no updates, no callbacks to run, just poll again + self._schedule_to_event_loop(self._poll_next) + for key, update in updates.items(): + self.snapshot_ids[key] = update.snapshot_id + callback = self.key_listeners[key] + + # Bind the parameters because closures are late-binding. + # https://docs.python-guide.org/writing/gotchas/#late-binding-closures # noqa: E501 + def chained(callback=callback, arg=update.object_snapshot): + callback(arg) + self._on_callback_completed(trigger_at=len(updates)) + + self._schedule_to_event_loop(chained) + + +class LongPollHost: + """The server side object that manages long pulling requests. + + The desired use case is to embed this in an Ray actor. Client will be + expected to call actor.listen_for_change.remote(...). On the host side, + you can call host.notify_changed({key: object}) to update the state and + potentially notify whoever is polling for these values. + + Internally, we use snapshot_ids for each object to identify client with + outdated object and immediately return the result. If the client has the + up-to-date version, then the listen_for_change call will only return when + the object is updated. + """ + + def __init__( + self, + listen_for_change_request_timeout_s: Tuple[ + int, int + ] = LISTEN_FOR_CHANGE_REQUEST_TIMEOUT_S, + ): + # Map object_key -> int + self.snapshot_ids: Dict[KeyType, int] = {} + # Map object_key -> object + self.object_snapshots: Dict[KeyType, Any] = {} + # Map object_key -> set(asyncio.Event waiting for updates) + self.notifier_events: DefaultDict[KeyType, Set[asyncio.Event]] = defaultdict( + set + ) + + self._listen_for_change_request_timeout_s = listen_for_change_request_timeout_s + self.transmission_counter = metrics.Counter( + "serve_long_poll_host_transmission_counter", + description="The number of times the long poll host transmits data.", + tag_keys=("namespace_or_state",), + ) + + def _get_num_notifier_events(self, key: Optional[KeyType] = None): + """Used for testing.""" + if key is not None: + return len(self.notifier_events[key]) + else: + return sum(len(events) for events in self.notifier_events.values()) + + def _count_send( + self, timeout_or_data: Union[LongPollState, Dict[KeyType, UpdatedObject]] + ): + """Helper method that tracks the data sent by listen_for_change. + + Records number of times long poll host sends data in the + ray_serve_long_poll_host_send_counter metric. + """ + + if isinstance(timeout_or_data, LongPollState): + # The only LongPollState is TIME_OUT– the long poll + # connection has timed out. + self.transmission_counter.inc( + value=1, tags={"namespace_or_state": "TIMEOUT"} + ) + else: + data = timeout_or_data + for key in data.keys(): + self.transmission_counter.inc( + value=1, tags={"namespace_or_state": str(key)} + ) + + async def listen_for_change( + self, + keys_to_snapshot_ids: Dict[KeyType, int], + ) -> Union[LongPollState, Dict[KeyType, UpdatedObject]]: + """Listen for changed objects. + + This method will return a dictionary of updated objects. It returns + immediately if any of the snapshot_ids are outdated, + otherwise it will block until there's an update. + """ + # If there are no keys to listen for, + # just wait for a short time to provide backpressure, + # then return an empty update. + if not keys_to_snapshot_ids: + await sleep(1) + + updated_objects = {} + self._count_send(updated_objects) + return updated_objects + + # If there are any keys with outdated snapshot ids, + # return their updated values immediately. + updated_objects = {} + for key, client_snapshot_id in keys_to_snapshot_ids.items(): + try: + existing_id = self.snapshot_ids[key] + except KeyError: + # The caller may ask for keys that we don't know about (yet), + # just ignore them. + # This can happen when, for example, + # a deployment handle is manually created for an app + # that hasn't been deployed yet (by bypassing the safety checks). + continue + + if existing_id != client_snapshot_id: + updated_objects[key] = UpdatedObject( + self.object_snapshots[key], existing_id + ) + if len(updated_objects) > 0: + self._count_send(updated_objects) + return updated_objects + + # Otherwise, register asyncio events to be waited. + async_task_to_events = {} + async_task_to_watched_keys = {} + for key in keys_to_snapshot_ids.keys(): + # Create a new asyncio event for this key. + event = asyncio.Event() + + # Make sure future caller of notify_changed will unblock this + # asyncio Event. + self.notifier_events[key].add(event) + + task = get_or_create_event_loop().create_task(event.wait()) + async_task_to_events[task] = event + async_task_to_watched_keys[task] = key + + done, not_done = await asyncio.wait( + async_task_to_watched_keys.keys(), + return_when=asyncio.FIRST_COMPLETED, + timeout=random.uniform(*self._listen_for_change_request_timeout_s), + ) + + for task in not_done: + task.cancel() + try: + event = async_task_to_events[task] + self.notifier_events[async_task_to_watched_keys[task]].remove(event) + except KeyError: + # Because we use `FIRST_COMPLETED` above, a task in `not_done` may + # actually have had its event removed in `notify_changed`. + pass + + if len(done) == 0: + self._count_send(LongPollState.TIME_OUT) + return LongPollState.TIME_OUT + else: + updated_objects = {} + for task in done: + updated_object_key = async_task_to_watched_keys[task] + updated_objects[updated_object_key] = UpdatedObject( + self.object_snapshots[updated_object_key], + self.snapshot_ids[updated_object_key], + ) + self._count_send(updated_objects) + return updated_objects + + async def listen_for_change_java( + self, + keys_to_snapshot_ids_bytes: bytes, + ) -> bytes: + """Listen for changed objects. only call by java proxy/router now. + Args: + keys_to_snapshot_ids_bytes (Dict[str, int]): the protobuf bytes of + keys_to_snapshot_ids (Dict[str, int]). + """ + request_proto = LongPollRequest.FromString(keys_to_snapshot_ids_bytes) + keys_to_snapshot_ids = { + self._parse_xlang_key(xlang_key): snapshot_id + for xlang_key, snapshot_id in request_proto.keys_to_snapshot_ids.items() + } + keys_to_updated_objects = await self.listen_for_change(keys_to_snapshot_ids) + return self._listen_result_to_proto_bytes(keys_to_updated_objects) + + def _parse_poll_namespace(self, name: str): + if name == LongPollNamespace.ROUTE_TABLE.name: + return LongPollNamespace.ROUTE_TABLE + elif name == LongPollNamespace.DEPLOYMENT_TARGETS.name: + return LongPollNamespace.DEPLOYMENT_TARGETS + else: + return name + + def _parse_xlang_key(self, xlang_key: str) -> KeyType: + if xlang_key is None: + raise ValueError("func _parse_xlang_key: xlang_key is None") + if xlang_key.startswith("(") and xlang_key.endswith(")"): + fields = xlang_key[1:-1].split(",") + if len(fields) == 2: + enum_field = self._parse_poll_namespace(fields[0].strip()) + if isinstance(enum_field, LongPollNamespace): + return enum_field, fields[1].strip() + else: + return self._parse_poll_namespace(xlang_key) + raise ValueError("can not parse key type from xlang_key {}".format(xlang_key)) + + def _build_xlang_key(self, key: KeyType) -> str: + if isinstance(key, tuple): + return "(" + key[0].name + "," + key[1] + ")" + elif isinstance(key, LongPollNamespace): + return key.name + else: + return key + + def _object_snapshot_to_proto_bytes( + self, key: KeyType, object_snapshot: Any + ) -> bytes: + if key == LongPollNamespace.ROUTE_TABLE: + # object_snapshot is Dict[DeploymentID, EndpointInfo] + # NOTE(zcin): the endpoint dictionary broadcasted to Java + # HTTP proxies should use string as key because Java does + # not yet support 2.x or applications + xlang_endpoints = { + str(endpoint_tag): EndpointInfoProto(route=endpoint_info.route) + for endpoint_tag, endpoint_info in object_snapshot.items() + } + return EndpointSet(endpoints=xlang_endpoints).SerializeToString() + elif isinstance(key, tuple) and key[0] == LongPollNamespace.DEPLOYMENT_TARGETS: + # object_snapshot.running_replicas is List[RunningReplicaInfo] + actor_name_list = [ + replica_info.replica_id.to_full_id_str() + for replica_info in object_snapshot.running_replicas + ] + return DeploymentTargetInfo( + replica_names=actor_name_list, + is_available=object_snapshot.is_available, + ).SerializeToString() + else: + return str.encode(str(object_snapshot)) + + def _listen_result_to_proto_bytes( + self, keys_to_updated_objects: Dict[KeyType, UpdatedObject] + ) -> bytes: + xlang_keys_to_updated_objects = { + self._build_xlang_key(key): UpdatedObjectProto( + snapshot_id=updated_object.snapshot_id, + object_snapshot=self._object_snapshot_to_proto_bytes( + key, updated_object.object_snapshot + ), + ) + for key, updated_object in keys_to_updated_objects.items() + } + data = { + "updated_objects": xlang_keys_to_updated_objects, + } + proto = LongPollResult(**data) + return proto.SerializeToString() + + def notify_changed(self, updates: Mapping[KeyType, Any]) -> None: + """ + Update the current snapshot of some objects + and notify any long poll clients. + """ + for object_key, updated_object in updates.items(): + try: + self.snapshot_ids[object_key] += 1 + except KeyError: + # Initial snapshot id must be >= 0, so that the long poll client + # can send a negative initial snapshot id to get a fast update. + # They should also be randomized; see + # https://github.com/ray-project/ray/pull/45881#discussion_r1645243485 + self.snapshot_ids[object_key] = random.randint(0, 1_000_000) + self.object_snapshots[object_key] = updated_object + logger.debug(f"LongPollHost: Notify change for key {object_key}.") + + for event in self.notifier_events.pop(object_key, set()): + event.set() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/metrics_utils.py b/venv/lib/python3.10/site-packages/ray/serve/_private/metrics_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..14efb553ca0981fb9a487800ab47857c2e7cc749 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/metrics_utils.py @@ -0,0 +1,216 @@ +import asyncio +import bisect +import logging +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Callable, DefaultDict, Dict, Hashable, List, Optional + +from ray.serve._private.constants import ( + METRICS_PUSHER_GRACEFUL_SHUTDOWN_TIMEOUT_S, + SERVE_LOGGER_NAME, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@dataclass +class _MetricsTask: + task_func: Callable + interval_s: float + + +class MetricsPusher: + """Periodically runs registered asyncio tasks.""" + + def __init__( + self, + *, + async_sleep: Optional[Callable[[int], None]] = None, + ): + self._async_sleep = async_sleep or asyncio.sleep + self._tasks: Dict[str, _MetricsTask] = dict() + self._async_tasks: Dict[str, asyncio.Task] = dict() + + # The event needs to be lazily initialized because this class may be constructed + # on the main thread but its methods called on a separate asyncio loop. + self._stop_event: Optional[asyncio.Event] = None + + @property + def stop_event(self) -> asyncio.Event: + if self._stop_event is None: + self._stop_event = asyncio.Event() + + return self._stop_event + + def start(self): + self.stop_event.clear() + + async def metrics_task(self, name: str): + """Periodically runs `task_func` every `interval_s` until `stop_event` is set. + + If `task_func` raises an error, an exception will be logged. + """ + + wait_for_stop_event = asyncio.create_task(self.stop_event.wait()) + while True: + if wait_for_stop_event.done(): + return + + try: + self._tasks[name].task_func() + except Exception as e: + logger.exception(f"Failed to run metrics task '{name}': {e}") + + sleep_task = asyncio.create_task( + self._async_sleep(self._tasks[name].interval_s) + ) + await asyncio.wait( + [sleep_task, wait_for_stop_event], + return_when=asyncio.FIRST_COMPLETED, + ) + + if not sleep_task.done(): + sleep_task.cancel() + + def register_or_update_task( + self, + name: str, + task_func: Callable, + interval_s: int, + ) -> None: + """Register a task under the provided name, or update it. + + This method is idempotent - if a task is already registered with + the specified name, it will update it with the most recent info. + """ + + self._tasks[name] = _MetricsTask(task_func, interval_s) + if name not in self._async_tasks or self._async_tasks[name].done(): + self._async_tasks[name] = asyncio.create_task(self.metrics_task(name)) + + def stop_tasks(self): + self.stop_event.set() + self._tasks.clear() + self._async_tasks.clear() + + async def graceful_shutdown(self): + """Shutdown metrics pusher gracefully. + + This method will ensure idempotency of shutdown call. + """ + + self.stop_event.set() + if self._async_tasks: + await asyncio.wait( + list(self._async_tasks.values()), + timeout=METRICS_PUSHER_GRACEFUL_SHUTDOWN_TIMEOUT_S, + ) + + self._tasks.clear() + self._async_tasks.clear() + + +@dataclass(order=True) +class TimeStampedValue: + timestamp: float + value: float = field(compare=False) + + +class InMemoryMetricsStore: + """A very simple, in memory time series database""" + + def __init__(self): + self.data: DefaultDict[Hashable, List[TimeStampedValue]] = defaultdict(list) + + def add_metrics_point(self, data_points: Dict[Hashable, float], timestamp: float): + """Push new data points to the store. + + Args: + data_points: dictionary containing the metrics values. The + key should uniquely identify this time series + and to be used to perform aggregation. + timestamp: the unix epoch timestamp the metrics are + collected at. + """ + for name, value in data_points.items(): + # Using in-sort to insert while maintaining sorted ordering. + bisect.insort(a=self.data[name], x=TimeStampedValue(timestamp, value)) + + def prune_keys_and_compact_data(self, start_timestamp_s: float): + """Prune keys and compact data that are outdated. + + For keys that haven't had new data recorded after the timestamp, + remove them from the database. + For keys that have, compact the datapoints that were recorded + before the timestamp. + """ + for key, datapoints in list(self.data.items()): + if len(datapoints) == 0 or datapoints[-1].timestamp < start_timestamp_s: + del self.data[key] + else: + self.data[key] = self._get_datapoints(key, start_timestamp_s) + + def _get_datapoints( + self, key: Hashable, window_start_timestamp_s: float + ) -> List[float]: + """Get all data points given key after window_start_timestamp_s""" + + datapoints = self.data[key] + + idx = bisect.bisect( + a=datapoints, + x=TimeStampedValue( + timestamp=window_start_timestamp_s, value=0 # dummy value + ), + ) + return datapoints[idx:] + + def window_average( + self, key: Hashable, window_start_timestamp_s: float, do_compact: bool = True + ) -> Optional[float]: + """Perform a window average operation for metric `key` + + Args: + key: the metric name. + window_start_timestamp_s: the unix epoch timestamp for the + start of the window. The computed average will use all datapoints + from this timestamp until now. + do_compact: whether or not to delete the datapoints that's + before `window_start_timestamp_s` to save memory. Default is + true. + Returns: + The average of all the datapoints for the key on and after time + window_start_timestamp_s, or None if there are no such points. + """ + points_after_idx = self._get_datapoints(key, window_start_timestamp_s) + + if do_compact: + self.data[key] = points_after_idx + + if len(points_after_idx) == 0: + return + return sum(point.value for point in points_after_idx) / len(points_after_idx) + + def max( + self, key: Hashable, window_start_timestamp_s: float, do_compact: bool = True + ): + """Perform a max operation for metric `key`. + + Args: + key: the metric name. + window_start_timestamp_s: the unix epoch timestamp for the + start of the window. The computed average will use all datapoints + from this timestamp until now. + do_compact: whether or not to delete the datapoints that's + before `window_start_timestamp_s` to save memory. Default is + true. + Returns: + Max value of the data points for the key on and after time + window_start_timestamp_s, or None if there are no such points. + """ + points_after_idx = self._get_datapoints(key, window_start_timestamp_s) + + if do_compact: + self.data[key] = points_after_idx + + return max((point.value for point in points_after_idx), default=None) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/proxy.py b/venv/lib/python3.10/site-packages/ray/serve/_private/proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..d99d8b28577fa5d845b4b13c81740aafb008c2df --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/proxy.py @@ -0,0 +1,1249 @@ +import asyncio +import gc +import json +import logging +import os +import pickle +import time +from abc import ABC, abstractmethod +from typing import Any, Callable, Dict, Generator, Optional, Set, Tuple + +import grpc +import starlette +import starlette.routing +from packaging import version +from starlette.types import Receive + +import ray +from ray._common.utils import get_or_create_event_loop +from ray.serve._private.common import ( + DeploymentID, + EndpointInfo, + NodeId, + ReplicaID, + RequestMetadata, + RequestProtocol, +) +from ray.serve._private.constants import ( + PROXY_MIN_DRAINING_PERIOD_S, + RAY_SERVE_ENABLE_PROXY_GC_OPTIMIZATIONS, + RAY_SERVE_PROXY_GC_THRESHOLD, + RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE, + REQUEST_LATENCY_BUCKETS_MS, + SERVE_CONTROLLER_NAME, + SERVE_HTTP_REQUEST_ID_HEADER, + SERVE_LOGGER_NAME, + SERVE_MULTIPLEXED_MODEL_ID, + SERVE_NAMESPACE, +) +from ray.serve._private.default_impl import get_proxy_handle +from ray.serve._private.grpc_util import ( + get_grpc_response_status, + set_grpc_code_and_details, + start_grpc_server, +) +from ray.serve._private.http_util import ( + MessageQueue, + configure_http_middlewares, + convert_object_to_asgi_messages, + get_http_response_status, + receive_http_body, + send_http_response_on_exception, + start_asgi_http_server, +) +from ray.serve._private.logging_utils import ( + access_log_msg, + configure_component_cpu_profiler, + configure_component_logger, + configure_component_memory_profiler, + get_component_logger_file_path, +) +from ray.serve._private.long_poll import LongPollClient, LongPollNamespace +from ray.serve._private.proxy_request_response import ( + ASGIProxyRequest, + HandlerMetadata, + ProxyRequest, + ResponseGenerator, + ResponseHandlerInfo, + ResponseStatus, + gRPCProxyRequest, +) +from ray.serve._private.proxy_response_generator import ProxyResponseGenerator +from ray.serve._private.proxy_router import ProxyRouter +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + generate_request_id, + get_head_node_id, + is_grpc_enabled, +) +from ray.serve.config import HTTPOptions, gRPCOptions +from ray.serve.generated.serve_pb2 import HealthzResponse, ListApplicationsResponse +from ray.serve.handle import DeploymentHandle +from ray.serve.schema import LoggingConfig +from ray.util import metrics + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +SOCKET_REUSE_PORT_ENABLED = ( + os.environ.get("SERVE_SOCKET_REUSE_PORT_ENABLED", "1") == "1" +) + +if os.environ.get("SERVE_REQUEST_PROCESSING_TIMEOUT_S") is not None: + logger.warning( + "The `SERVE_REQUEST_PROCESSING_TIMEOUT_S` environment variable has " + "been deprecated. Please set `request_timeout_s` in your Serve config's " + "`http_options` or `grpc_options` field instead. `SERVE_REQUEST_PROCESSING_TIMEOUT_S` will be " + "ignored in future versions. See: https://docs.ray.io/en/releases-2.5.1/serve/a" + "pi/doc/ray.serve.schema.HTTPOptionsSchema.html#ray.serve.schema.HTTPOptionsSch" + "ema.request_timeout_s and https://docs.ray.io/en/latest/serve/api/" + "doc/ray.serve.config.gRPCOptions.request_timeout_s.html#" + "ray.serve.config.gRPCOptions.request_timeout_s" + ) + + +INITIAL_BACKOFF_PERIOD_SEC = 0.05 +MAX_BACKOFF_PERIOD_SEC = 5 + +HEALTHY_MESSAGE = "success" +DRAINING_MESSAGE = "This node is being drained." + + +class GenericProxy(ABC): + """This class is served as the base class for different types of proxies. + It contains all the common setup and methods required for running a proxy. + + The proxy subclass need to implement the following methods: + - `protocol()` + - `not_found_response()` + - `routes_response()` + - `health_response()` + - `setup_request_context_and_handle()` + - `send_request_to_replica()` + """ + + def __init__( + self, + node_id: NodeId, + node_ip_address: str, + is_head: bool, + proxy_router: ProxyRouter, + request_timeout_s: Optional[float] = None, + ): + self.request_timeout_s = request_timeout_s + if self.request_timeout_s is not None and self.request_timeout_s < 0: + self.request_timeout_s = None + + self._node_id = node_id + self._is_head = is_head + + self.proxy_router = proxy_router + self.request_counter = metrics.Counter( + f"serve_num_{self.protocol.lower()}_requests", + description=f"The number of {self.protocol} requests processed.", + tag_keys=("route", "method", "application", "status_code"), + ) + + self.request_error_counter = metrics.Counter( + f"serve_num_{self.protocol.lower()}_error_requests", + description=f"The number of errored {self.protocol} responses.", + tag_keys=( + "route", + "error_code", + "method", + "application", + ), + ) + + self.deployment_request_error_counter = metrics.Counter( + f"serve_num_deployment_{self.protocol.lower()}_error_requests", + description=( + f"The number of errored {self.protocol} " + "responses returned by each deployment." + ), + tag_keys=( + "deployment", + "error_code", + "method", + "route", + "application", + ), + ) + + # log REQUEST_LATENCY_BUCKET_MS + logger.debug(f"REQUEST_LATENCY_BUCKET_MS: {REQUEST_LATENCY_BUCKETS_MS}") + self.processing_latency_tracker = metrics.Histogram( + f"serve_{self.protocol.lower()}_request_latency_ms", + description=( + f"The end-to-end latency of {self.protocol} requests " + f"(measured from the Serve {self.protocol} proxy)." + ), + boundaries=REQUEST_LATENCY_BUCKETS_MS, + tag_keys=( + "method", + "route", + "application", + "status_code", + ), + ) + + self.num_ongoing_requests_gauge = metrics.Gauge( + name=f"serve_num_ongoing_{self.protocol.lower()}_requests", + description=f"The number of ongoing requests in this {self.protocol} " + "proxy.", + tag_keys=("node_id", "node_ip_address"), + ).set_default_tags( + { + "node_id": node_id, + "node_ip_address": node_ip_address, + } + ) + + # `self._ongoing_requests` is used to count the number of ongoing requests + self._ongoing_requests = 0 + # The time when the node starts to drain. + # The node is not draining if it's None. + self._draining_start_time: Optional[float] = None + + getattr(ServeUsageTag, f"{self.protocol.upper()}_PROXY_USED").record("1") + + @property + @abstractmethod + def protocol(self) -> RequestProtocol: + """Protocol used in the proxy. + + Each proxy needs to implement its own logic for setting up the protocol. + """ + raise NotImplementedError + + def _is_draining(self) -> bool: + """Whether is proxy actor is in the draining status or not.""" + return self._draining_start_time is not None + + def is_drained(self): + """Check whether the proxy actor is drained or not. + + A proxy actor is drained if it has no ongoing requests + AND it has been draining for more than + `PROXY_MIN_DRAINING_PERIOD_S` seconds. + """ + if not self._is_draining(): + return False + + return (not self._ongoing_requests) and ( + (time.time() - self._draining_start_time) > PROXY_MIN_DRAINING_PERIOD_S + ) + + def update_draining(self, draining: bool): + """Update the draining status of the proxy. + + This is called by the proxy state manager + to drain or un-drain the proxy actor. + """ + + if draining and (not self._is_draining()): + logger.info( + f"Start to drain the proxy actor on node {self._node_id}.", + extra={"log_to_stderr": False}, + ) + self._draining_start_time = time.time() + if (not draining) and self._is_draining(): + logger.info( + f"Stop draining the proxy actor on node {self._node_id}.", + extra={"log_to_stderr": False}, + ) + self._draining_start_time = None + + @abstractmethod + async def not_found_response( + self, proxy_request: ProxyRequest + ) -> ResponseGenerator: + raise NotImplementedError + + @abstractmethod + async def routes_response( + self, *, healthy: bool, message: str + ) -> ResponseGenerator: + raise NotImplementedError + + @abstractmethod + async def health_response( + self, *, healthy: bool, message: str + ) -> ResponseGenerator: + raise NotImplementedError + + def _ongoing_requests_start(self): + """Ongoing requests start. + + The current autoscale logic can downscale nodes with ongoing requests if the + node doesn't have replicas and has no primary copies of objects in the object + store. The counter and the dummy object reference will help to keep the node + alive while draining requests, so they are not dropped unintentionally. + """ + self._ongoing_requests += 1 + self.num_ongoing_requests_gauge.set(self._ongoing_requests) + + def _ongoing_requests_end(self): + """Ongoing requests end. + + Decrement the ongoing request counter and drop the dummy object reference + signaling that the node can be downscaled safely. + """ + self._ongoing_requests -= 1 + self.num_ongoing_requests_gauge.set(self._ongoing_requests) + + def _get_health_or_routes_reponse( + self, proxy_request: ProxyRequest + ) -> ResponseHandlerInfo: + """Get the response handler for system health and route endpoints. + + If the proxy is draining or has not yet received a route table update from the + controller, both will return a non-OK status. + """ + router_ready_for_traffic, router_msg = self.proxy_router.ready_for_traffic( + self._is_head + ) + if self._is_draining(): + healthy = False + message = DRAINING_MESSAGE + elif not router_ready_for_traffic: + healthy = False + message = router_msg + else: + healthy = True + message = HEALTHY_MESSAGE + + if proxy_request.is_health_request: + response_generator = self.health_response(healthy=healthy, message=message) + else: + assert proxy_request.is_route_request + response_generator = self.routes_response(healthy=healthy, message=message) + + return ResponseHandlerInfo( + response_generator=response_generator, + metadata=HandlerMetadata( + route=proxy_request.route_path, + ), + should_record_access_log=False, + should_increment_ongoing_requests=False, + ) + + def _get_response_handler_info( + self, proxy_request: ProxyRequest + ) -> ResponseHandlerInfo: + if proxy_request.is_health_request or proxy_request.is_route_request: + return self._get_health_or_routes_reponse(proxy_request) + + matched_route = None + if self.protocol == RequestProtocol.HTTP: + matched_route = self.proxy_router.match_route(proxy_request.route_path) + elif self.protocol == RequestProtocol.GRPC: + matched_route = self.proxy_router.get_handle_for_endpoint( + proxy_request.route_path + ) + + if matched_route is None: + return ResponseHandlerInfo( + response_generator=self.not_found_response(proxy_request), + metadata=HandlerMetadata( + # Don't include the invalid route prefix because it can blow up our + # metrics' cardinality. + # See: https://github.com/ray-project/ray/issues/47999 + route="", + ), + should_record_access_log=True, + should_increment_ongoing_requests=False, + ) + else: + route_prefix, handle, app_is_cross_language = matched_route + # Modify the path and root path so that reverse lookups and redirection + # work as expected. We do this here instead of in replicas so it can be + # changed without restarting the replicas. + route_path = proxy_request.route_path + if route_prefix != "/" and self.protocol == RequestProtocol.HTTP: + assert not route_prefix.endswith("/") + proxy_request.set_root_path(proxy_request.root_path + route_prefix) + # NOTE(edoakes): starlette<0.33.0 expected the ASGI 'root_prefix' + # to be stripped from the 'path', which wasn't technically following + # the standard. See https://github.com/encode/starlette/pull/2352. + if version.parse(starlette.__version__) < version.parse("0.33.0"): + proxy_request.set_path(route_path.replace(route_prefix, "", 1)) + + # NOTE(edoakes): we use the route_prefix instead of the full HTTP path + # for logs & metrics to avoid high cardinality. + # See: https://github.com/ray-project/ray/issues/47999 + logs_and_metrics_route = ( + route_prefix + if self.protocol == RequestProtocol.HTTP + else handle.deployment_id.app_name + ) + internal_request_id = generate_request_id() + handle, request_id = self.setup_request_context_and_handle( + app_name=handle.deployment_id.app_name, + handle=handle, + route=logs_and_metrics_route, + proxy_request=proxy_request, + internal_request_id=internal_request_id, + ) + + response_generator = self.send_request_to_replica( + request_id=request_id, + internal_request_id=internal_request_id, + handle=handle, + proxy_request=proxy_request, + app_is_cross_language=app_is_cross_language, + ) + + return ResponseHandlerInfo( + response_generator=response_generator, + metadata=HandlerMetadata( + application_name=handle.deployment_id.app_name, + deployment_name=handle.deployment_id.name, + route=logs_and_metrics_route, + ), + should_record_access_log=True, + should_increment_ongoing_requests=True, + ) + + async def proxy_request(self, proxy_request: ProxyRequest) -> ResponseGenerator: + """Wrapper for proxy request. + + This method is served as common entry point by the proxy. It handles the + routing, including routes and health checks, ongoing request counter, + and metrics. + """ + assert proxy_request.request_type in {"http", "websocket", "grpc"} + + response_handler_info = self._get_response_handler_info(proxy_request) + + start_time = time.time() + if response_handler_info.should_increment_ongoing_requests: + self._ongoing_requests_start() + + try: + # The final message yielded must always be the `ResponseStatus`. + status: Optional[ResponseStatus] = None + async for message in response_handler_info.response_generator: + if isinstance(message, ResponseStatus): + status = message + + yield message + + assert status is not None and isinstance(status, ResponseStatus) + finally: + # If anything during the request failed, we still want to ensure the ongoing + # request counter is decremented. + if response_handler_info.should_increment_ongoing_requests: + self._ongoing_requests_end() + + latency_ms = (time.time() - start_time) * 1000.0 + if response_handler_info.should_record_access_log: + request_context = ray.serve.context._get_serve_request_context() + logger.info( + access_log_msg( + method=proxy_request.method, + route=request_context.route, + status=str(status.code), + latency_ms=latency_ms, + ), + extra={"log_to_stderr": False, "serve_access_log": True}, + ) + + self.request_counter.inc( + tags={ + "route": response_handler_info.metadata.route, + "method": proxy_request.method, + "application": response_handler_info.metadata.application_name, + "status_code": str(status.code), + } + ) + + self.processing_latency_tracker.observe( + latency_ms, + tags={ + "route": response_handler_info.metadata.route, + "method": proxy_request.method, + "application": response_handler_info.metadata.application_name, + "status_code": str(status.code), + }, + ) + if status.is_error: + self.request_error_counter.inc( + tags={ + "route": response_handler_info.metadata.route, + "method": proxy_request.method, + "application": response_handler_info.metadata.application_name, + "error_code": str(status.code), + } + ) + self.deployment_request_error_counter.inc( + tags={ + "route": response_handler_info.metadata.route, + "method": proxy_request.method, + "application": response_handler_info.metadata.application_name, + "error_code": str(status.code), + "deployment": response_handler_info.metadata.deployment_name, + } + ) + + @abstractmethod + def setup_request_context_and_handle( + self, + app_name: str, + handle: DeploymentHandle, + route: str, + proxy_request: ProxyRequest, + internal_request_id: str, + ) -> Tuple[DeploymentHandle, str]: + """Setup the request context and handle for the request. + + Each proxy needs to implement its own logic for setting up the request context + and handle. + """ + raise NotImplementedError + + @abstractmethod + async def send_request_to_replica( + self, + request_id: str, + internal_request_id: str, + handle: DeploymentHandle, + proxy_request: ProxyRequest, + app_is_cross_language: bool = False, + ) -> ResponseGenerator: + """Send the request to the replica and handle streaming response. + + Each proxy needs to implement its own logic for sending the request and + handling the streaming response. + """ + raise NotImplementedError + + +class gRPCProxy(GenericProxy): + """This class is meant to be instantiated and run by an gRPC server. + + This is the servicer class for the gRPC server. It implements `unary_unary` + as the entry point for unary gRPC request and `unary_stream` as the entry + point for streaming gRPC request. + """ + + @property + def protocol(self) -> RequestProtocol: + return RequestProtocol.GRPC + + async def not_found_response( + self, proxy_request: ProxyRequest + ) -> ResponseGenerator: + if not proxy_request.app_name: + application_message = "Application metadata not set." + else: + application_message = f"Application '{proxy_request.app_name}' not found." + not_found_message = ( + f"{application_message} Ping " + "/ray.serve.RayServeAPIService/ListApplications for available applications." + ) + + yield ResponseStatus( + code=grpc.StatusCode.NOT_FOUND, + message=not_found_message, + is_error=True, + ) + + async def routes_response( + self, *, healthy: bool, message: str + ) -> ResponseGenerator: + yield ListApplicationsResponse( + application_names=[ + endpoint.app_name for endpoint in self.proxy_router.endpoints + ], + ).SerializeToString() + + yield ResponseStatus( + code=grpc.StatusCode.OK if healthy else grpc.StatusCode.UNAVAILABLE, + message=message, + is_error=not healthy, + ) + + async def health_response(self, *, healthy: bool, message) -> ResponseGenerator: + yield HealthzResponse(message=message).SerializeToString() + yield ResponseStatus( + code=grpc.StatusCode.OK if healthy else grpc.StatusCode.UNAVAILABLE, + message=message, + is_error=not healthy, + ) + + def service_handler_factory(self, service_method: str, stream: bool) -> Callable: + async def unary_unary( + request_proto: Any, context: grpc._cython.cygrpc._ServicerContext + ) -> bytes: + """Entry point of the gRPC proxy unary request. + + This method is called by the gRPC server when a unary request is received. + It wraps the request in a ProxyRequest object and calls proxy_request. + The return value is serialized user defined protobuf bytes. + """ + proxy_request = gRPCProxyRequest( + request_proto=request_proto, + context=context, + service_method=service_method, + stream=False, + ) + + status = None + response = None + async for message in self.proxy_request(proxy_request=proxy_request): + if isinstance(message, ResponseStatus): + status = message + else: + response = message + + set_grpc_code_and_details(context, status) + + return response + + async def unary_stream( + request_proto: Any, context: grpc._cython.cygrpc._ServicerContext + ) -> Generator[bytes, None, None]: + """Entry point of the gRPC proxy streaming request. + + This method is called by the gRPC server when a streaming request is + received. It wraps the request in a ProxyRequest object and calls + proxy_request. The return value is a generator of serialized user defined + protobuf bytes. + """ + proxy_request = gRPCProxyRequest( + request_proto=request_proto, + context=context, + service_method=service_method, + stream=True, + ) + + status = None + async for message in self.proxy_request(proxy_request=proxy_request): + if isinstance(message, ResponseStatus): + status = message + else: + yield message + + set_grpc_code_and_details(context, status) + + return unary_stream if stream else unary_unary + + def setup_request_context_and_handle( + self, + app_name: str, + handle: DeploymentHandle, + route: str, + proxy_request: ProxyRequest, + internal_request_id: str, + ) -> Tuple[DeploymentHandle, str]: + """Setup request context and handle for the request. + + Unpack gRPC request metadata and extract info to set up request context and + handle. + """ + multiplexed_model_id = proxy_request.multiplexed_model_id + request_id = proxy_request.request_id + if not request_id: + request_id = generate_request_id() + proxy_request.request_id = request_id + + handle = handle.options( + stream=proxy_request.stream, + multiplexed_model_id=multiplexed_model_id, + method_name=proxy_request.method_name, + ) + + request_context_info = { + "route": route, + "request_id": request_id, + "_internal_request_id": internal_request_id, + "app_name": app_name, + "multiplexed_model_id": multiplexed_model_id, + "grpc_context": proxy_request.ray_serve_grpc_context, + } + ray.serve.context._serve_request_context.set( + ray.serve.context._RequestContext(**request_context_info) + ) + proxy_request.send_request_id(request_id=request_id) + return handle, request_id + + async def send_request_to_replica( + self, + request_id: str, + internal_request_id: str, + handle: DeploymentHandle, + proxy_request: ProxyRequest, + app_is_cross_language: bool = False, + ) -> ResponseGenerator: + response_generator = ProxyResponseGenerator( + handle.remote(proxy_request.serialized_replica_arg()), + timeout_s=self.request_timeout_s, + ) + + try: + async for context, result in response_generator: + context._set_on_grpc_context(proxy_request.context) + yield result + + status = ResponseStatus(code=grpc.StatusCode.OK) + except BaseException as e: + status = get_grpc_response_status(e, self.request_timeout_s, request_id) + + # The status code should always be set. + assert status is not None + yield status + + +class HTTPProxy(GenericProxy): + """This class is meant to be instantiated and run by an ASGI HTTP server.""" + + def __init__( + self, + node_id: NodeId, + node_ip_address: str, + is_head: bool, + proxy_router: ProxyRouter, + self_actor_name: str, + request_timeout_s: Optional[float] = None, + ): + super().__init__( + node_id, + node_ip_address, + is_head, + proxy_router, + request_timeout_s=request_timeout_s, + ) + self.self_actor_name = self_actor_name + self.asgi_receive_queues: Dict[str, MessageQueue] = dict() + + @property + def protocol(self) -> RequestProtocol: + return RequestProtocol.HTTP + + async def not_found_response( + self, proxy_request: ProxyRequest + ) -> ResponseGenerator: + status_code = 404 + for message in convert_object_to_asgi_messages( + f"Path '{proxy_request.path}' not found. " + "Ping http://.../-/routes for available routes.", + status_code=status_code, + ): + yield message + + yield ResponseStatus(code=status_code, is_error=True) + + async def routes_response( + self, *, healthy: bool, message: str + ) -> ResponseGenerator: + status_code = 200 if healthy else 503 + if healthy: + response = dict() + for endpoint, info in self.proxy_router.endpoints.items(): + # For 2.x deployments, return {route -> app name} + if endpoint.app_name: + response[info.route] = endpoint.app_name + # Keep compatibility with 1.x deployments. + else: + response[info.route] = endpoint.name + else: + response = message + + for asgi_message in convert_object_to_asgi_messages( + response, + status_code=status_code, + ): + yield asgi_message + + yield ResponseStatus( + code=status_code, + message=message, + is_error=not healthy, + ) + + async def health_response( + self, *, healthy: bool, message: str = "" + ) -> ResponseGenerator: + status_code = 200 if healthy else 503 + for asgi_message in convert_object_to_asgi_messages( + message, + status_code=status_code, + ): + yield asgi_message + + yield ResponseStatus( + code=status_code, + is_error=not healthy, + message=message, + ) + + async def receive_asgi_messages( + self, request_metadata: RequestMetadata + ) -> ResponseGenerator: + queue = self.asgi_receive_queues.get(request_metadata.internal_request_id, None) + if queue is None: + raise KeyError(f"Request ID {request_metadata.request_id} not found.") + + await queue.wait_for_message() + return queue.get_messages_nowait() + + async def __call__(self, scope, receive, send): + """Implements the ASGI protocol. + + See details at: + https://asgi.readthedocs.io/en/latest/specs/index.html. + """ + proxy_request = ASGIProxyRequest(scope=scope, receive=receive, send=send) + async for message in self.proxy_request(proxy_request): + if not isinstance(message, ResponseStatus): + await send(message) + + async def proxy_asgi_receive( + self, receive: Receive, queue: MessageQueue + ) -> Optional[int]: + """Proxies the `receive` interface, placing its messages into the queue. + + Once a disconnect message is received, the call exits and `receive` is no longer + called. + + For HTTP messages, `None` is always returned. + For websocket messages, the disconnect code is returned if a disconnect code is + received. + """ + try: + while True: + msg = await receive() + await queue(msg) + + if msg["type"] == "http.disconnect": + return None + + if msg["type"] == "websocket.disconnect": + return msg["code"] + finally: + # Close the queue so any subsequent calls to fetch messages return + # immediately: https://github.com/ray-project/ray/issues/38368. + queue.close() + + def setup_request_context_and_handle( + self, + app_name: str, + handle: DeploymentHandle, + route: str, + proxy_request: ProxyRequest, + internal_request_id: str, + ) -> Tuple[DeploymentHandle, str]: + """Setup request context and handle for the request. + + Unpack HTTP request headers and extract info to set up request context and + handle. + """ + request_context_info = { + "route": route, + "app_name": app_name, + "_internal_request_id": internal_request_id, + "is_http_request": True, + } + for key, value in proxy_request.headers: + if key.decode() == SERVE_MULTIPLEXED_MODEL_ID: + multiplexed_model_id = value.decode() + handle = handle.options(multiplexed_model_id=multiplexed_model_id) + request_context_info["multiplexed_model_id"] = multiplexed_model_id + if key.decode() == SERVE_HTTP_REQUEST_ID_HEADER: + request_context_info["request_id"] = value.decode() + ray.serve.context._serve_request_context.set( + ray.serve.context._RequestContext(**request_context_info) + ) + return handle, request_context_info["request_id"] + + async def _format_handle_arg_for_java( + self, + proxy_request: ProxyRequest, + ) -> bytes: + """Convert an HTTP request to the Java-accepted format (single byte string).""" + query_string = proxy_request.scope.get("query_string") + http_body_bytes = await receive_http_body( + proxy_request.scope, proxy_request.receive, proxy_request.send + ) + if query_string: + arg = query_string.decode().split("=", 1)[1] + else: + arg = http_body_bytes.decode() + + return arg + + async def send_request_to_replica( + self, + request_id: str, + internal_request_id: str, + handle: DeploymentHandle, + proxy_request: ProxyRequest, + app_is_cross_language: bool = False, + ) -> ResponseGenerator: + """Send the request to the replica and yield its response messages. + + The yielded values will be ASGI messages until the final one, which will be + the status code. + """ + if app_is_cross_language: + handle_arg_bytes = await self._format_handle_arg_for_java(proxy_request) + # Response is returned as raw bytes, convert it to ASGI messages. + result_callback = convert_object_to_asgi_messages + else: + handle_arg_bytes = proxy_request.serialized_replica_arg( + proxy_actor_name=self.self_actor_name, + ) + # Messages are returned as pickled dictionaries. + result_callback = pickle.loads + + # Proxy the receive interface by placing the received messages on a queue. + # The downstream replica must call back into `receive_asgi_messages` on this + # actor to receive the messages. + receive_queue = MessageQueue() + self.asgi_receive_queues[internal_request_id] = receive_queue + proxy_asgi_receive_task = get_or_create_event_loop().create_task( + self.proxy_asgi_receive(proxy_request.receive, receive_queue) + ) + + response_generator = ProxyResponseGenerator( + handle.remote(handle_arg_bytes), + timeout_s=self.request_timeout_s, + disconnected_task=proxy_asgi_receive_task, + result_callback=result_callback, + ) + + status: Optional[ResponseStatus] = None + response_started = False + expecting_trailers = False + try: + async for asgi_message_batch in response_generator: + # See the ASGI spec for message details: + # https://asgi.readthedocs.io/en/latest/specs/www.html. + for asgi_message in asgi_message_batch: + if asgi_message["type"] == "http.response.start": + # HTTP responses begin with exactly one + # "http.response.start" message containing the "status" + # field. Other response types (e.g., WebSockets) may not. + status_code = str(asgi_message["status"]) + status = ResponseStatus( + code=status_code, + is_error=status_code.startswith(("4", "5")), + ) + expecting_trailers = asgi_message.get("trailers", False) + elif asgi_message["type"] == "websocket.accept": + # Websocket code explicitly handles client disconnects, + # so let the ASGI disconnect message propagate instead of + # cancelling the handler. + response_generator.stop_checking_for_disconnect() + elif ( + asgi_message["type"] == "http.response.body" + and not asgi_message.get("more_body", False) + and not expecting_trailers + ): + # If the body is completed and we aren't expecting trailers, the + # response is done so we should stop listening for disconnects. + response_generator.stop_checking_for_disconnect() + elif asgi_message["type"] == "http.response.trailers": + # If we are expecting trailers, the response is only done when + # the trailers message has been sent. + if not asgi_message.get("more_trailers", False): + response_generator.stop_checking_for_disconnect() + elif asgi_message["type"] in [ + "websocket.close", + "websocket.disconnect", + ]: + status_code = str(asgi_message["code"]) + status = ResponseStatus( + code=status_code, + # All status codes are considered errors aside from: + # 1000 (CLOSE_NORMAL), 1001 (CLOSE_GOING_AWAY). + is_error=status_code not in ["1000", "1001"], + ) + response_generator.stop_checking_for_disconnect() + + yield asgi_message + response_started = True + except BaseException as e: + status = get_http_response_status(e, self.request_timeout_s, request_id) + for asgi_message in send_http_response_on_exception( + status, response_started + ): + yield asgi_message + + finally: + # For websocket connection, queue receive task is done when receiving + # disconnect message from client. + receive_client_disconnect_msg = False + if not proxy_asgi_receive_task.done(): + proxy_asgi_receive_task.cancel() + else: + receive_client_disconnect_msg = True + + # If the server disconnects, status_code can be set above from the + # disconnect message. + # If client disconnects, the disconnect code comes from + # a client message via the receive interface. + if status is None and proxy_request.request_type == "websocket": + if receive_client_disconnect_msg: + # The disconnect message is sent from the client. + status = ResponseStatus( + code=str(proxy_asgi_receive_task.result()), + is_error=True, + ) + else: + # The server disconnect without sending a disconnect message + # (otherwise the `status` would be set). + status = ResponseStatus( + code="1000", # [Sihan] is there a better code for this? + is_error=True, + ) + + del self.asgi_receive_queues[internal_request_id] + + # The status code should always be set. + assert status is not None + yield status + + +@ray.remote(num_cpus=0) +class ProxyActor: + def __init__( + self, + http_options: HTTPOptions, + grpc_options: gRPCOptions, + *, + node_id: NodeId, + node_ip_address: str, + logging_config: LoggingConfig, + long_poll_client: Optional[LongPollClient] = None, + ): # noqa: F821 + self._node_id = node_id + self._node_ip_address = node_ip_address + self._http_options = configure_http_middlewares(http_options) + self._grpc_options = grpc_options + grpc_enabled = is_grpc_enabled(self._grpc_options) + + event_loop = get_or_create_event_loop() + self.long_poll_client = long_poll_client or LongPollClient( + ray.get_actor(SERVE_CONTROLLER_NAME, namespace=SERVE_NAMESPACE), + { + LongPollNamespace.GLOBAL_LOGGING_CONFIG: self._update_logging_config, + LongPollNamespace.ROUTE_TABLE: self._update_routes_in_proxies, + }, + call_in_event_loop=event_loop, + ) + + configure_component_logger( + component_name="proxy", + component_id=node_ip_address, + logging_config=logging_config, + buffer_size=RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE, + ) + + startup_msg = f"Proxy starting on node {self._node_id} (HTTP port: {self._http_options.port}" + if grpc_enabled: + startup_msg += f", gRPC port: {self._grpc_options.port})." + else: + startup_msg += ")." + logger.info(startup_msg) + logger.debug( + f"Configure Proxy actor {ray.get_runtime_context().get_actor_id()} " + f"logger with logging config: {logging_config}" + ) + + configure_component_memory_profiler( + component_name="proxy", component_id=node_ip_address + ) + self.cpu_profiler, self.cpu_profiler_log = configure_component_cpu_profiler( + component_name="proxy", component_id=node_ip_address + ) + + is_head = self._node_id == get_head_node_id() + self.proxy_router = ProxyRouter(get_proxy_handle) + self.http_proxy = HTTPProxy( + node_id=self._node_id, + node_ip_address=self._node_ip_address, + is_head=is_head, + self_actor_name=ray.get_runtime_context().get_actor_name(), + proxy_router=self.proxy_router, + request_timeout_s=self._http_options.request_timeout_s, + ) + self.grpc_proxy = ( + gRPCProxy( + node_id=self._node_id, + node_ip_address=self._node_ip_address, + is_head=is_head, + proxy_router=self.proxy_router, + request_timeout_s=self._grpc_options.request_timeout_s, + ) + if grpc_enabled + else None + ) + + # Start a task to initialize the HTTP server. + # The result of this task is checked in the `ready` method. + self._start_http_server_task = event_loop.create_task( + start_asgi_http_server( + self.http_proxy, + self._http_options, + event_loop=event_loop, + enable_so_reuseport=SOCKET_REUSE_PORT_ENABLED, + ) + ) + # A task that runs the HTTP server until it exits (currently runs forever). + # Populated with the result of self._start_http_server_task. + self._running_http_server_task: Optional[asyncio.Task] = None + + # Start a task to initialize the gRPC server. + # The result of this task is checked in the `ready` method. + self._start_grpc_server_task: Optional[asyncio.Task] = None + if grpc_enabled: + self._start_grpc_server_task = event_loop.create_task( + start_grpc_server( + self.grpc_proxy.service_handler_factory, + self._grpc_options, + event_loop=event_loop, + enable_so_reuseport=SOCKET_REUSE_PORT_ENABLED, + ), + ) + # A task that runs the gRPC server until it exits (currently runs forever). + # Populated with the result of self._start_grpc_server_task. + self._running_grpc_server_task: Optional[asyncio.Task] = None + + _configure_gc_options() + + def _update_routes_in_proxies(self, endpoints: Dict[DeploymentID, EndpointInfo]): + self.proxy_router.update_routes(endpoints) + + def _update_logging_config(self, logging_config: LoggingConfig): + configure_component_logger( + component_name="proxy", + component_id=self._node_ip_address, + logging_config=logging_config, + ) + + def _get_logging_config(self) -> Tuple: + """Get the logging configuration (for testing purposes).""" + log_file_path = None + for handler in logger.handlers: + if isinstance(handler, logging.handlers.MemoryHandler): + log_file_path = handler.target.baseFilename + return log_file_path + + def _dump_ingress_replicas_for_testing(self, route: str) -> Set[ReplicaID]: + _, handle, _ = self.http_proxy.proxy_router.match_route(route) + return handle._router._asyncio_router._request_router._replica_id_set + + async def ready(self) -> str: + """Blocks until the proxy HTTP (and optionally gRPC) servers are running. + + Returns JSON-serialized metadata containing the proxy's worker ID and log + file path. + + Raises any exceptions that occur setting up the HTTP or gRPC server. + """ + try: + self._running_http_server_task = await self._start_http_server_task + except Exception as e: + logger.exception("Failed to start proxy HTTP server.") + raise e from None + + try: + if self._start_grpc_server_task is not None: + self._running_grpc_server_task = await self._start_grpc_server_task + except Exception as e: + logger.exception("Failed to start proxy gRPC server.") + raise e from None + + # Return proxy metadata used by the controller. + # NOTE(zcin): We need to convert the metadata to a json string because + # of cross-language scenarios. Java can't deserialize a Python tuple. + return json.dumps( + [ + ray.get_runtime_context().get_worker_id(), + get_component_logger_file_path(), + ] + ) + + async def update_draining(self, draining: bool, _after: Optional[Any] = None): + """Update the draining status of the HTTP and gRPC proxies. + + Unused `_after` argument is for scheduling: passing an ObjectRef + allows delaying this call until after the `_after` call has returned. + """ + + self.http_proxy.update_draining(draining) + if self.grpc_proxy: + self.grpc_proxy.update_draining(draining) + + async def is_drained(self, _after: Optional[Any] = None): + """Check whether both HTTP and gRPC proxies are drained or not. + + Unused `_after` argument is for scheduling: passing an ObjectRef + allows delaying this call until after the `_after` call has returned. + """ + + return self.http_proxy.is_drained() and ( + self.grpc_proxy is None or self.grpc_proxy.is_drained() + ) + + async def check_health(self): + """No-op method to check on the health of the HTTP Proxy. + + Make sure the async event loop is not blocked. + """ + logger.debug("Received health check.", extra={"log_to_stderr": False}) + + def pong(self): + """Called by the replica to initialize its handle to the proxy.""" + pass + + async def receive_asgi_messages(self, request_metadata: RequestMetadata) -> bytes: + """Get ASGI messages for the provided `request_metadata`. + + After the proxy has stopped receiving messages for this `request_metadata`, + this will always return immediately. + + Raises `KeyError` if this request ID is not found. This will happen when the + request is no longer being handled (e.g., the user disconnects). + """ + return pickle.dumps( + await self.http_proxy.receive_asgi_messages(request_metadata) + ) + + def _save_cpu_profile_data(self) -> str: + """Saves CPU profiling data, if CPU profiling is enabled. + + Logs a warning if CPU profiling is disabled. + """ + + if self.cpu_profiler is not None: + import marshal + + self.cpu_profiler.snapshot_stats() + with open(self.cpu_profiler_log, "wb") as f: + marshal.dump(self.cpu_profiler.stats, f) + logger.info(f'Saved CPU profile data to file "{self.cpu_profiler_log}"') + return self.cpu_profiler_log + else: + logger.error( + "Attempted to save CPU profile data, but failed because no " + "CPU profiler was running! Enable CPU profiling by enabling " + "the RAY_SERVE_ENABLE_CPU_PROFILING env var." + ) + + def _get_http_options(self) -> HTTPOptions: + """Internal method to get HTTP options used by the proxy.""" + return self._http_options + + +def _configure_gc_options(): + if not RAY_SERVE_ENABLE_PROXY_GC_OPTIMIZATIONS: + return + + # Collect any objects that exist already and exclude them from future GC. + gc.collect(2) + gc.freeze() + + # Tune the GC threshold to run less frequently (default is 700). + gc.set_threshold(RAY_SERVE_PROXY_GC_THRESHOLD) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_request_response.py b/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_request_response.py new file mode 100644 index 0000000000000000000000000000000000000000..922621f6242487bf842da4a2c3109564a4edf8a6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_request_response.py @@ -0,0 +1,199 @@ +import logging +import pickle +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import Any, AsyncIterator, List, Tuple, Union + +import grpc +from starlette.types import Receive, Scope, Send + +from ray.serve._private.common import StreamingHTTPRequest, gRPCRequest +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.utils import DEFAULT +from ray.serve.grpc_util import RayServegRPCContext + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class ProxyRequest(ABC): + """Base ProxyRequest class to use in the common interface among proxies""" + + @property + @abstractmethod + def request_type(self) -> str: + raise NotImplementedError + + @property + @abstractmethod + def method(self) -> str: + raise NotImplementedError + + @property + @abstractmethod + def route_path(self) -> str: + raise NotImplementedError + + @property + @abstractmethod + def is_route_request(self) -> bool: + raise NotImplementedError + + @property + @abstractmethod + def is_health_request(self) -> bool: + raise NotImplementedError + + +class ASGIProxyRequest(ProxyRequest): + """ProxyRequest implementation to wrap ASGI scope, receive, and send.""" + + def __init__(self, scope: Scope, receive: Receive, send: Send): + self.scope = scope + self.receive = receive + self.send = send + + @property + def request_type(self) -> str: + return self.scope.get("type", "") + + @property + def method(self) -> str: + # WebSocket messages don't have a 'method' field. + return self.scope.get("method", "WS").upper() + + @property + def route_path(self) -> str: + return self.scope.get("path", "")[len(self.root_path) :] + + @property + def is_route_request(self) -> bool: + return self.route_path == "/-/routes" + + @property + def is_health_request(self) -> bool: + return self.route_path == "/-/healthz" + + @property + def client(self) -> str: + return self.scope.get("client", "") + + @property + def root_path(self) -> str: + return self.scope.get("root_path", "") + + @property + def path(self) -> str: + return self.scope.get("path", "") + + @property + def headers(self) -> List[Tuple[bytes, bytes]]: + return self.scope.get("headers", []) + + def set_path(self, path: str): + self.scope["path"] = path + + def set_root_path(self, root_path: str): + self.scope["root_path"] = root_path + + def serialized_replica_arg(self, proxy_actor_name: str) -> bytes: + # NOTE(edoakes): it's important that the request is sent as raw bytes to + # skip the Ray cloudpickle serialization codepath for performance. + return pickle.dumps( + StreamingHTTPRequest( + asgi_scope=self.scope, + proxy_actor_name=proxy_actor_name, + ) + ) + + +class gRPCProxyRequest(ProxyRequest): + """ProxyRequest implementation to wrap gRPC request protobuf and metadata.""" + + def __init__( + self, + request_proto: Any, + context: grpc._cython.cygrpc._ServicerContext, + service_method: str, + stream: bool, + ): + self._request_proto = request_proto + self.context = context + self.service_method = service_method + self.stream = stream + self.app_name = "" + self.request_id = None + self.method_name = "__call__" + self.multiplexed_model_id = DEFAULT.VALUE + # ray_serve_grpc_context is a class implemented by us to be able to serialize + # the object and pass it into the deployment. + self.ray_serve_grpc_context = RayServegRPCContext(context) + self.setup_variables() + + def setup_variables(self): + if not self.is_route_request and not self.is_health_request: + service_method_split = self.service_method.split("/") + self.method_name = service_method_split[-1] + for key, value in self.context.invocation_metadata(): + if key == "application": + self.app_name = value + elif key == "request_id": + self.request_id = value + elif key == "multiplexed_model_id": + self.multiplexed_model_id = value + + @property + def request_type(self) -> str: + return "grpc" + + @property + def method(self) -> str: + return self.service_method + + @property + def route_path(self) -> str: + return self.app_name + + @property + def is_route_request(self) -> bool: + return self.service_method == "/ray.serve.RayServeAPIService/ListApplications" + + @property + def is_health_request(self) -> bool: + return self.service_method == "/ray.serve.RayServeAPIService/Healthz" + + def send_request_id(self, request_id: str): + # Setting the trailing metadata on the ray_serve_grpc_context object, so it's + # not overriding the ones set from the user and will be sent back to the + # client altogether. + self.ray_serve_grpc_context.set_trailing_metadata([("request_id", request_id)]) + + def serialized_replica_arg(self) -> bytes: + # NOTE(edoakes): it's important that the request is sent as raw bytes to + # skip the Ray cloudpickle serialization codepath for performance. + return pickle.dumps(gRPCRequest(user_request_proto=self._request_proto)) + + +@dataclass(frozen=True) +class ResponseStatus: + code: Union[str, grpc.StatusCode] # Must be convertible to a string. + is_error: bool = False + message: str = "" + + +# Yields protocol-specific messages followed by a final `ResponseStatus`. +ResponseGenerator = AsyncIterator[Union[Any, ResponseStatus]] + + +@dataclass(frozen=True) +class HandlerMetadata: + application_name: str = "" + deployment_name: str = "" + route: str = "" + + +@dataclass(frozen=True) +class ResponseHandlerInfo: + response_generator: ResponseGenerator + metadata: HandlerMetadata + should_record_access_log: bool + should_increment_ongoing_requests: bool diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_response_generator.py b/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_response_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..59f31849d4a6e317997a0213736b82762d4f9060 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_response_generator.py @@ -0,0 +1,181 @@ +import asyncio +import logging +import time +from abc import ABC, abstractmethod +from asyncio.tasks import FIRST_COMPLETED +from typing import Any, Callable, Optional, Union + +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.utils import calculate_remaining_timeout +from ray.serve.exceptions import RequestCancelledError +from ray.serve.handle import DeploymentResponse, DeploymentResponseGenerator + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class _ProxyResponseGeneratorBase(ABC): + def __init__( + self, + *, + timeout_s: Optional[float] = None, + disconnected_task: Optional[asyncio.Task] = None, + result_callback: Optional[Callable[[Any], Any]] = None, + ): + """Implements a generator wrapping a deployment response. + + Args: + - timeout_s: an end-to-end timeout for the request. If this expires and the + response is not completed, the request will be cancelled. If `None`, + there's no timeout. + - disconnected_task: a task whose completion signals that the client has + disconnected. When this happens, the request will be cancelled. If `None`, + disconnects will not be detected. + - result_callback: will be called on each result before it's returned. If + `None`, the unmodified result is returned. + """ + self._timeout_s = timeout_s + self._start_time_s = time.time() + self._disconnected_task = disconnected_task + self._result_callback = result_callback + + def __aiter__(self): + return self + + @abstractmethod + async def __anext__(self): + """Return the next message in the stream. + + Raises: + TimeoutError: On timeout. + asyncio.CancelledError: On disconnect. + StopAsyncIteration: When the stream is completed. + """ + pass + + def stop_checking_for_disconnect(self): + """Once this is called, the disconnected_task will be ignored.""" + self._disconnected_task = None + + +def swallow_cancelled(task: asyncio.Task): + try: + task.result() + except (RequestCancelledError, asyncio.CancelledError): + # We expect RequestCancelledError to be raised because for disconnect or + # timeouts, we explicitly call resp.cancel(). To avoid "Task exception + # was never retrieved" errors from spamming the proxy logs, swallow + # them here. + pass + except Exception: + # For all other exceptions, do not catch and instead re-raise here so that + # they will be logged properly. + raise + + +class ProxyResponseGenerator(_ProxyResponseGeneratorBase): + """Wraps a unary DeploymentResponse or streaming DeploymentResponseGenerator. + + In the case of a unary DeploymentResponse, __anext__ will only ever return one + result. + """ + + def __init__( + self, + response: Union[DeploymentResponse, DeploymentResponseGenerator], + *, + timeout_s: Optional[float] = None, + disconnected_task: Optional[asyncio.Task] = None, + result_callback: Optional[Callable[[Any], Any]] = None, + ): + super().__init__( + timeout_s=timeout_s, + disconnected_task=disconnected_task, + result_callback=result_callback, + ) + self._done = False + self._response = response + + def cancelled(self) -> bool: + return self._response.cancelled() + + async def __anext__(self): + if self._done: + raise StopAsyncIteration + + try: + if isinstance(self._response, DeploymentResponseGenerator): + result = await self._get_next_streaming_result() + else: + result = await self._get_unary_result() + self._done = True + + if self._result_callback is not None: + result = self._result_callback(result) + except asyncio.CancelledError as e: + # This is specifically for gRPC. The cancellation can happen from client + # dropped connection before the request is completed. If self._response is + # not already cancelled, we want to explicitly cancel the task, so it + # doesn't waste cluster resource in this case and can be terminated + # gracefully. + if not self._response.cancelled(): + self._response.cancel() + self._done = True + + raise e from None + except Exception as e: + self._done = True + raise e from None + + return result + + async def _await_response_anext(self) -> Any: + return await self._response.__anext__() + + async def _get_next_streaming_result(self) -> Any: + next_result_task = asyncio.create_task(self._await_response_anext()) + tasks = [next_result_task] + if self._disconnected_task is not None: + tasks.append(self._disconnected_task) + + done, _ = await asyncio.wait( + tasks, + return_when=FIRST_COMPLETED, + timeout=calculate_remaining_timeout( + timeout_s=self._timeout_s, + start_time_s=self._start_time_s, + curr_time_s=time.time(), + ), + ) + if next_result_task in done: + return next_result_task.result() + elif self._disconnected_task in done: + next_result_task.cancel() + next_result_task.add_done_callback(swallow_cancelled) + self._response.cancel() + raise asyncio.CancelledError() + else: + next_result_task.cancel() + next_result_task.add_done_callback(swallow_cancelled) + self._response.cancel() + raise TimeoutError() + + async def _await_response(self) -> Any: + return await self._response + + async def _get_unary_result(self) -> Any: + result_task = asyncio.create_task(self._await_response()) + tasks = [result_task] + if self._disconnected_task is not None: + tasks.append(self._disconnected_task) + + done, _ = await asyncio.wait( + tasks, return_when=FIRST_COMPLETED, timeout=self._timeout_s + ) + if result_task in done: + return result_task.result() + elif self._disconnected_task in done: + self._response.cancel() + raise asyncio.CancelledError() + else: + self._response.cancel() + raise TimeoutError() diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_router.py b/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_router.py new file mode 100644 index 0000000000000000000000000000000000000000..7c40cee8b418225859c77adcd41703e5c1440608 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_router.py @@ -0,0 +1,165 @@ +import logging +from typing import Callable, Dict, List, Optional, Tuple + +from ray.serve._private.common import ApplicationName, DeploymentID, EndpointInfo +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve.handle import DeploymentHandle + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +NO_ROUTES_MESSAGE = "Route table is not populated yet." +NO_REPLICAS_MESSAGE = "No replicas are available yet." + + +class ProxyRouter: + """Router interface for the proxy to use.""" + + def __init__( + self, + get_handle: Callable[[str, str], DeploymentHandle], + ): + # Function to get a handle given a name. Used to mock for testing. + self._get_handle = get_handle + # Contains a ServeHandle for each endpoint. + self.handles: Dict[DeploymentID, DeploymentHandle] = dict() + # Flipped to `True` once the route table has been updated at least once. + # The proxy router is not ready for traffic until the route table is populated + self._route_table_populated = False + + # Info used for HTTP proxy + # Routes sorted in order of decreasing length. + self.sorted_routes: List[str] = list() + # Endpoints associated with the routes. + self.route_info: Dict[str, DeploymentID] = dict() + # Map of application name to is_cross_language. + self.app_to_is_cross_language: Dict[ApplicationName, bool] = dict() + + # Info used for gRPC proxy + # Endpoints info associated with endpoints. + self.endpoints: Dict[DeploymentID, EndpointInfo] = dict() + + def ready_for_traffic(self, is_head: bool) -> Tuple[bool, str]: + """Whether the proxy router is ready to serve traffic. + + The first return value will be false if any of the following hold: + - The route table has not been populated yet with a non-empty set of routes + - The route table has been populated, but none of the handles + have received running replicas yet AND it lives on a worker node. + + Otherwise, the first return value will be true. + """ + + if not self._route_table_populated: + return False, NO_ROUTES_MESSAGE + + # NOTE(zcin): For the proxy on the head node, even if none of its handles have + # been populated with running replicas yet, we MUST mark the proxy as ready for + # traffic. This is to handle the case when all deployments have scaled to zero. + # If the deployments (more precisely, ingress deployments) have all scaled down + # to zero, at least one proxy needs to be able to receive incoming requests to + # trigger upscale. + if is_head: + return True, "" + + for handle in self.handles.values(): + if handle.running_replicas_populated(): + return True, "" + + return False, NO_REPLICAS_MESSAGE + + def update_routes(self, endpoints: Dict[DeploymentID, EndpointInfo]): + logger.info( + f"Got updated endpoints: {endpoints}.", extra={"log_to_stderr": True} + ) + if endpoints: + self._route_table_populated = True + + self.endpoints = endpoints + + existing_handles = set(self.handles.keys()) + routes = [] + route_info = {} + app_to_is_cross_language = {} + for endpoint, info in endpoints.items(): + routes.append(info.route) + route_info[info.route] = endpoint + app_to_is_cross_language[endpoint.app_name] = info.app_is_cross_language + if endpoint in self.handles: + existing_handles.remove(endpoint) + else: + self.handles[endpoint] = self._get_handle(endpoint, info) + + # Clean up any handles that are no longer used. + if len(existing_handles) > 0: + logger.info( + f"Deleting {len(existing_handles)} unused handles.", + extra={"log_to_stderr": False}, + ) + for endpoint in existing_handles: + del self.handles[endpoint] + + # Routes are sorted in order of decreasing length to enable longest + # prefix matching. + self.sorted_routes = sorted(routes, key=lambda x: len(x), reverse=True) + self.route_info = route_info + self.app_to_is_cross_language = app_to_is_cross_language + + def match_route( + self, target_route: str + ) -> Optional[Tuple[str, DeploymentHandle, bool]]: + """Return the longest prefix match among existing routes for the route. + Args: + target_route: route to match against. + Returns: + (route, handle, is_cross_language) if found, else None. + """ + + for route in self.sorted_routes: + if target_route.startswith(route): + matched = False + # If the route we matched on ends in a '/', then so does the + # target route and this must be a match. + if route.endswith("/"): + matched = True + # If the route we matched on doesn't end in a '/', we need to + # do another check to ensure that either this is an exact match + # or the next character in the target route is a '/'. This is + # to guard against the scenario where we have '/route' as a + # prefix and there's a request to '/routesuffix'. In this case, + # it should *not* be a match. + elif len(target_route) == len(route) or target_route[len(route)] == "/": + matched = True + + if matched: + endpoint = self.route_info[route] + return ( + route, + self.handles[endpoint], + self.app_to_is_cross_language[endpoint.app_name], + ) + + return None + + def get_handle_for_endpoint( + self, target_app_name: str + ) -> Optional[Tuple[str, DeploymentHandle, bool]]: + """Return the handle that matches with endpoint. + + Args: + target_app_name: app_name to match against. + Returns: + (route, handle, is_cross_language) for the single app if there + is only one, else find the app and handle for exact match. Else return None. + """ + for endpoint_tag, handle in self.handles.items(): + # If the target_app_name matches with the endpoint or if + # there is only one endpoint. + if target_app_name == endpoint_tag.app_name or len(self.handles) == 1: + endpoint_info = self.endpoints[endpoint_tag] + return ( + endpoint_info.route, + handle, + endpoint_info.app_is_cross_language, + ) + + return None diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_state.py b/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_state.py new file mode 100644 index 0000000000000000000000000000000000000000..c241a0f2774ce7d2e0ab8f745303d1a006255927 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/proxy_state.py @@ -0,0 +1,826 @@ +import asyncio +import json +import logging +import os +from abc import ABC, abstractmethod +from copy import deepcopy +from typing import Dict, List, Optional, Set, Tuple, Type + +import ray +from ray import ObjectRef +from ray.actor import ActorHandle +from ray.exceptions import GetTimeoutError, RayActorError +from ray.serve._private.cluster_node_info_cache import ClusterNodeInfoCache +from ray.serve._private.common import NodeId, RequestProtocol +from ray.serve._private.constants import ( + ASYNC_CONCURRENCY, + PROXY_DRAIN_CHECK_PERIOD_S, + PROXY_HEALTH_CHECK_PERIOD_S, + PROXY_HEALTH_CHECK_TIMEOUT_S, + PROXY_HEALTH_CHECK_UNHEALTHY_THRESHOLD, + PROXY_READY_CHECK_TIMEOUT_S, + RAY_SERVE_ALWAYS_RUN_PROXY_ON_HEAD_NODE, + RAY_SERVE_ENABLE_TASK_EVENTS, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, + SERVE_PROXY_NAME, +) +from ray.serve._private.proxy import ProxyActor +from ray.serve._private.utils import ( + Timer, + TimerBase, + format_actor_name, + is_grpc_enabled, +) +from ray.serve.config import DeploymentMode, HTTPOptions, gRPCOptions +from ray.serve.schema import ( + LoggingConfig, + ProxyDetails, + ProxyStatus, + Target, +) +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class ProxyWrapper(ABC): + @property + @abstractmethod + def actor_id(self) -> str: + """Return the actor id of the proxy actor.""" + raise NotImplementedError + + @abstractmethod + def is_ready(self, timeout_s: float) -> Optional[bool]: + """Return whether proxy is ready to be serving requests. + + Since actual readiness check is asynchronous, this method could return + any of the following statuses: + - None: Readiness check is pending + - True: Readiness check completed successfully (proxy is ready) + - False: Readiness check completed with failure (either timing out + or failing) + """ + raise NotImplementedError + + @abstractmethod + def is_healthy(self, timeout_s: float) -> Optional[bool]: + """Return whether the proxy actor is healthy. + + Since actual health-check is asynchronous, this method could return + either of the following statuses: + - None: Health-check is pending + - True: Health-check completed successfully (proxy is healthy) + - False: Health-check completed with failure (either timing out or failing) + """ + raise NotImplementedError + + @abstractmethod + def is_drained(self, timeout_s: float) -> Optional[bool]: + """Return whether the proxy actor is drained. + + Since actual check whether proxy is drained is asynchronous, this method could + return either of the following statuses: + - None: Drain-check is pending + - True: Drain-check completed, node *is drained* + - False: Drain-check completed, node is *NOT* drained + """ + raise NotImplementedError + + @abstractmethod + def is_shutdown(self): + """Return whether the proxy actor is shutdown.""" + raise NotImplementedError + + @abstractmethod + def update_draining(self, draining: bool): + """Update the draining status of the proxy actor.""" + raise NotImplementedError + + @abstractmethod + def kill(self): + """Kill the proxy actor.""" + raise NotImplementedError + + +class ActorProxyWrapper(ProxyWrapper): + def __init__( + self, + logging_config: LoggingConfig, + actor_handle: Optional[ActorHandle] = None, + http_options: Optional[HTTPOptions] = None, + grpc_options: Optional[gRPCOptions] = None, + name: Optional[str] = None, + node_id: Optional[str] = None, + node_ip_address: Optional[str] = None, + port: Optional[int] = None, + proxy_actor_class: Type[ProxyActor] = ProxyActor, + ): + # initialize with provided proxy actor handle or get or create a new one. + self._actor_handle = actor_handle or self._get_or_create_proxy_actor( + http_options=http_options, + grpc_options=grpc_options, + name=name, + node_id=node_id, + node_ip_address=node_ip_address, + port=port, + proxy_actor_class=proxy_actor_class, + logging_config=logging_config, + ) + self._ready_check_future = None + self._health_check_future = None + self._drained_check_future = None + + self._update_draining_obj_ref = None + + self._node_id = node_id + + self.worker_id = None + self.log_file_path = None + + @staticmethod + def _get_or_create_proxy_actor( + http_options: HTTPOptions, + grpc_options: gRPCOptions, + name: str, + node_id: str, + node_ip_address: str, + port: int, + logging_config: LoggingConfig, + proxy_actor_class: Type[ProxyActor] = ProxyActor, + ) -> ProxyWrapper: + """Helper to start or reuse existing proxy. + + Takes the name of the proxy, the node id, and the node ip address, and look up + or creates a new ProxyActor actor handle for the proxy. + """ + proxy = None + try: + proxy = ray.get_actor(name, namespace=SERVE_NAMESPACE) + except ValueError: + addr = f"{http_options.host}:{http_options.port}" + logger.info( + f"Starting proxy on node '{node_id}' listening on '{addr}'.", + extra={"log_to_stderr": False}, + ) + + return proxy or proxy_actor_class.options( + num_cpus=http_options.num_cpus, + name=name, + namespace=SERVE_NAMESPACE, + lifetime="detached", + max_concurrency=ASYNC_CONCURRENCY, + max_restarts=0, + scheduling_strategy=NodeAffinitySchedulingStrategy(node_id, soft=False), + enable_task_events=RAY_SERVE_ENABLE_TASK_EVENTS, + ).remote( + http_options, + grpc_options=grpc_options, + node_id=node_id, + node_ip_address=node_ip_address, + logging_config=logging_config, + ) + + @property + def actor_id(self) -> str: + """Return the actor id of the proxy actor.""" + return self._actor_handle._actor_id.hex() + + @property + def actor_handle(self) -> ActorHandle: + """Return the actor handle of the proxy actor. + + This is used in _start_controller() in _private/controller.py to check whether + the proxies exist. It is also used in some tests to access proxy's actor handle. + """ + return self._actor_handle + + def is_ready(self, timeout_s: float) -> Optional[bool]: + if self._ready_check_future is None: + self._ready_check_future = wrap_as_future( + self._actor_handle.ready.remote(), timeout_s=timeout_s + ) + + if not self._ready_check_future.done(): + return None + + try: + worker_id, log_file_path = json.loads(self._ready_check_future.result()) + self.worker_id = worker_id + self.log_file_path = log_file_path + return True + except TimeoutError: + logger.warning( + f"Proxy actor readiness check for proxy on {self._node_id}" + f" didn't complete in {timeout_s}s." + ) + except Exception: + logger.exception( + f"Unexpected error invoking readiness check for proxy" + f" on {self._node_id}", + ) + finally: + self._ready_check_future = None + + return False + + def is_healthy(self, timeout_s: float) -> Optional[bool]: + if self._health_check_future is None: + self._health_check_future = wrap_as_future( + self._actor_handle.check_health.remote(), timeout_s=timeout_s + ) + + if not self._health_check_future.done(): + return None + + try: + # NOTE: Since `check_health` method is responding with nothing, sole + # purpose of fetching the result is to extract any potential + # exceptions + self._health_check_future.result() + return True + except TimeoutError: + logger.warning( + f"Didn't receive health check response for proxy" + f" on {self._node_id} after {timeout_s}s." + ) + except Exception: + logger.exception( + f"Unexpected error invoking health check for proxy " + f"on {self._node_id}", + ) + finally: + self._health_check_future = None + + return False + + def is_drained(self, timeout_s: float) -> Optional[bool]: + if self._drained_check_future is None: + self._drained_check_future = wrap_as_future( + self._actor_handle.is_drained.remote(), + timeout_s=timeout_s, + ) + + if not self._drained_check_future.done(): + return None + + try: + is_drained = self._drained_check_future.result() + return is_drained + except TimeoutError: + logger.warning( + f"Didn't receive drain check response for proxy" + f" on {self._node_id} after {timeout_s}s." + ) + except Exception: + logger.exception( + f"Unexpected error invoking drain-check for proxy " + f"on {self._node_id}", + ) + finally: + self._drained_check_future = None + + return False + + def is_shutdown(self) -> bool: + """Return whether the proxy actor is shutdown. + + If the actor is dead, the health check will return RayActorError. + """ + try: + ray.get(self._actor_handle.check_health.remote(), timeout=0) + except RayActorError: + # The actor is dead, so it's ready for shutdown. + return True + except GetTimeoutError: + pass + + # The actor is still alive, so it's not ready for shutdown. + return False + + def update_draining(self, draining: bool): + """Update the draining status of the proxy actor.""" + # NOTE: All update_draining calls are implicitly serialized, by specifying + # `ObjectRef` of the previous call + self._update_draining_obj_ref = self._actor_handle.update_draining.remote( + draining, _after=self._update_draining_obj_ref + ) + # In case of cancelled draining, make sure pending draining check is cancelled + # as well + if not draining: + future = self._drained_check_future + self._drained_check_future = None + if future: + future.cancel() + + def kill(self): + """Kill the proxy actor.""" + ray.kill(self._actor_handle, no_restart=True) + + +class ProxyState: + def __init__( + self, + actor_proxy_wrapper: ProxyWrapper, + actor_name: str, + node_id: str, + node_ip: str, + node_instance_id: str, + proxy_restart_count: int = 0, + timer: TimerBase = Timer(), + ): + self._actor_proxy_wrapper = actor_proxy_wrapper + self._actor_name = actor_name + self._node_id = node_id + self._status = ProxyStatus.STARTING + self._timer = timer + self._shutting_down = False + self._consecutive_health_check_failures: int = 0 + self._proxy_restart_count = proxy_restart_count + self._last_health_check_time: Optional[float] = None + self._last_drain_check_time: Optional[float] = None + + self._actor_details = ProxyDetails( + node_id=node_id, + node_ip=node_ip, + node_instance_id=node_instance_id, + actor_id=self._actor_proxy_wrapper.actor_id, + actor_name=self._actor_name, + status=self._status, + ) + + @property + def actor_handle(self) -> ActorHandle: + return self._actor_proxy_wrapper.actor_handle + + @property + def actor_name(self) -> str: + return self._actor_name + + @property + def actor_id(self) -> str: + return self._actor_proxy_wrapper.actor_id + + @property + def status(self) -> ProxyStatus: + return self._status + + @property + def actor_details(self) -> ProxyDetails: + return self._actor_details + + @property + def proxy_restart_count(self) -> int: + return self._proxy_restart_count + + def _set_status(self, status: ProxyStatus) -> None: + """Sets _status and updates _actor_details with the new status. + + NOTE: This method should not be used directly, instead please + use `try_update_status` method + """ + self._status = status + self.update_actor_details(status=self._status) + + def try_update_status(self, status: ProxyStatus): + """Try update with the new status and only update when the conditions are met. + + Status will only set to UNHEALTHY after PROXY_HEALTH_CHECK_UNHEALTHY_THRESHOLD + consecutive failures. A warning will be logged when the status is set to + UNHEALTHY. Also, when status is set to HEALTHY, we will reset + self._consecutive_health_check_failures to 0. + """ + + if status == ProxyStatus.UNHEALTHY: + self._consecutive_health_check_failures += 1 + # Early return to skip setting UNHEALTHY status if there are still room for + # retry. + if ( + self._consecutive_health_check_failures + < PROXY_HEALTH_CHECK_UNHEALTHY_THRESHOLD + ): + return + else: + # If all retries have been exhausted and setting the status to + # UNHEALTHY, log a warning message to the user. + logger.warning( + f"Proxy {self._actor_name} failed the health check " + f"{self._consecutive_health_check_failures} times in a row, marking" + f" it unhealthy." + ) + else: + # Reset self._consecutive_health_check_failures when status is not + # UNHEALTHY + self._consecutive_health_check_failures = 0 + + self._set_status(status=status) + + def update_actor_details(self, **kwargs) -> None: + """Updates _actor_details with passed in kwargs.""" + details_kwargs = self._actor_details.dict() + details_kwargs.update(kwargs) + self._actor_details = ProxyDetails(**details_kwargs) + + def reconcile(self, draining: bool = False): + try: + self._reconcile_internal(draining) + except Exception as e: + self.try_update_status(ProxyStatus.UNHEALTHY) + logger.error( + "Unexpected error occurred when reconciling stae of " + f"proxy on node {self._node_id}", + exc_info=e, + ) + + def _reconcile_internal(self, draining: bool): + """Update the status of the current proxy. + + The state machine is: + STARTING -> HEALTHY or UNHEALTHY + HEALTHY -> DRAINING or UNHEALTHY + DRAINING -> HEALTHY or UNHEALTHY or DRAINED + + UNHEALTHY is a terminal state upon reaching which, Proxy is going to be + restarted by the controller + """ + if ( + self._shutting_down + or self._status == ProxyStatus.DRAINED + or self._status == ProxyStatus.UNHEALTHY + ): + return + + # Doing a linear backoff for the ready check timeout. + ready_check_timeout = ( + self.proxy_restart_count + 1 + ) * PROXY_READY_CHECK_TIMEOUT_S + + if self._status == ProxyStatus.STARTING: + is_ready_response = self._actor_proxy_wrapper.is_ready(ready_check_timeout) + if is_ready_response is not None: + if is_ready_response: + self.try_update_status(ProxyStatus.HEALTHY) + self.update_actor_details( + worker_id=self._actor_proxy_wrapper.worker_id, + log_file_path=self._actor_proxy_wrapper.log_file_path, + status=self._status, + ) + else: + self.try_update_status(ProxyStatus.UNHEALTHY) + logger.warning( + f"Proxy actor reported not ready on node {self._node_id}" + ) + else: + # At this point, the proxy is either in HEALTHY or DRAINING status. + assert self._status in {ProxyStatus.HEALTHY, ProxyStatus.DRAINING} + + should_check_health = self._last_health_check_time is None or ( + self._timer.time() - self._last_health_check_time + >= PROXY_HEALTH_CHECK_PERIOD_S + ) + # Perform health-check for proxy's actor (if necessary) + if should_check_health: + is_healthy_response = self._actor_proxy_wrapper.is_healthy( + PROXY_HEALTH_CHECK_TIMEOUT_S + ) + if is_healthy_response is not None: + if is_healthy_response: + # At this stage status is either HEALTHY or DRAINING, and here + # we simply reset the status + self.try_update_status(self._status) + else: + self.try_update_status(ProxyStatus.UNHEALTHY) + + self._last_health_check_time = self._timer.time() + + # Handle state transitions (if necessary) + if self._status == ProxyStatus.UNHEALTHY: + return + elif self._status == ProxyStatus.HEALTHY: + if draining: + logger.info(f"Draining proxy on node '{self._node_id}'.") + assert self._last_drain_check_time is None + + self._actor_proxy_wrapper.update_draining(draining=True) + self.try_update_status(ProxyStatus.DRAINING) + elif self._status == ProxyStatus.DRAINING: + if not draining: + logger.info(f"No longer draining proxy on node '{self._node_id}'.") + self._last_drain_check_time = None + + self._actor_proxy_wrapper.update_draining(draining=False) + self.try_update_status(ProxyStatus.HEALTHY) + else: + should_check_drain = self._last_drain_check_time is None or ( + self._timer.time() - self._last_drain_check_time + >= PROXY_DRAIN_CHECK_PERIOD_S + ) + if should_check_drain: + # NOTE: We use the same timeout as for readiness checking + is_drained_response = self._actor_proxy_wrapper.is_drained( + PROXY_READY_CHECK_TIMEOUT_S + ) + if is_drained_response is not None: + if is_drained_response: + self.try_update_status(ProxyStatus.DRAINED) + + self._last_drain_check_time = self._timer.time() + + def shutdown(self): + self._shutting_down = True + self._actor_proxy_wrapper.kill() + + def is_ready_for_shutdown(self) -> bool: + """Return whether the proxy actor is shutdown. + + For a proxy actor to be considered shutdown, it must be marked as + _shutting_down and the actor must be shut down. + """ + if not self._shutting_down: + return False + + return self._actor_proxy_wrapper.is_shutdown() + + +class ProxyStateManager: + """Manages all state for proxies in the system. + + This class is *not* thread safe, so any state-modifying methods should be + called with a lock held. + """ + + def __init__( + self, + http_options: HTTPOptions, + head_node_id: str, + cluster_node_info_cache: ClusterNodeInfoCache, + logging_config: LoggingConfig, + grpc_options: Optional[gRPCOptions] = None, + proxy_actor_class: Type[ProxyActor] = ProxyActor, + actor_proxy_wrapper_class: Type[ProxyWrapper] = ActorProxyWrapper, + timer: TimerBase = Timer(), + ): + self.logging_config = logging_config + self._http_options = http_options or HTTPOptions() + self._grpc_options = grpc_options or gRPCOptions() + self._proxy_states: Dict[NodeId, ProxyState] = dict() + self._proxy_restart_counts: Dict[NodeId, int] = dict() + self._head_node_id: str = head_node_id + self._proxy_actor_class = proxy_actor_class + self._actor_proxy_wrapper_class = actor_proxy_wrapper_class + self._timer = timer + + self._cluster_node_info_cache = cluster_node_info_cache + + assert isinstance(head_node_id, str) + + def reconfigure_logging_config(self, logging_config: LoggingConfig): + self.logging_config = logging_config + + def shutdown(self) -> None: + for proxy_state in self._proxy_states.values(): + proxy_state.shutdown() + + def is_ready_for_shutdown(self) -> bool: + """Return whether all proxies are shutdown. + + Iterate through all proxy states and check if all their proxy actors + are shutdown. + """ + return all( + proxy_state.is_ready_for_shutdown() + for proxy_state in self._proxy_states.values() + ) + + def get_config(self) -> HTTPOptions: + return self._http_options + + def get_grpc_config(self) -> gRPCOptions: + return self._grpc_options + + def get_proxy_handles(self) -> Dict[NodeId, ActorHandle]: + return { + node_id: state.actor_handle for node_id, state in self._proxy_states.items() + } + + def get_proxy_names(self) -> Dict[NodeId, str]: + return { + node_id: state.actor_name for node_id, state in self._proxy_states.items() + } + + def get_proxy_details(self) -> Dict[NodeId, ProxyDetails]: + return { + node_id: state.actor_details + for node_id, state in self._proxy_states.items() + } + + def get_targets(self, protocol: RequestProtocol) -> List[Target]: + """In Ray Serve, every proxy is responsible for routing requests to the + correct application. Here we curate a list of targets for the given protocol. + Where each target represents how to reach a proxy. + + Args: + protocol: Either "http" or "grpc" + """ + targets = [] + if protocol == RequestProtocol.HTTP: + port = self._http_options.port + elif protocol == RequestProtocol.GRPC: + if not is_grpc_enabled(self._grpc_options): + return [] + port = self._grpc_options.port + else: + raise ValueError(f"Invalid protocol: {protocol}") + + targets = [ + Target( + ip=state.actor_details.node_ip, + port=port, + instance_id=state.actor_details.node_instance_id, + ) + for _, state in self._proxy_states.items() + if state.actor_details.status == ProxyStatus.HEALTHY + ] + return targets + + def get_alive_proxy_actor_ids(self) -> Set[str]: + return {state.actor_id for state in self._proxy_states.values()} + + def update(self, proxy_nodes: Set[NodeId] = None) -> Set[str]: + """Update the state of all proxies. + + Start proxies on all nodes if not already exist and stop the proxies on nodes + that are no longer exist. Update all proxy states. Kill and restart + unhealthy proxies. + """ + if proxy_nodes is None: + proxy_nodes = set() + + # Ensure head node always has a proxy (unless FF'd off). + if RAY_SERVE_ALWAYS_RUN_PROXY_ON_HEAD_NODE: + proxy_nodes.add(self._head_node_id) + + target_nodes = self._get_target_nodes(proxy_nodes) + target_node_ids = {node_id for node_id, _, _ in target_nodes} + + for node_id, proxy_state in self._proxy_states.items(): + draining = node_id not in target_node_ids + proxy_state.reconcile(draining) + + self._stop_proxies_if_needed() + self._start_proxies_if_needed(target_nodes) + + def _get_target_nodes(self, proxy_nodes) -> List[Tuple[str, str, str]]: + """Return the list of (node_id, ip_address) to deploy HTTP and gRPC servers + on.""" + location = self._http_options.location + + if location == DeploymentMode.NoServer: + return [] + + target_nodes = [ + (node_id, ip_address, instance_id) + for node_id, ip_address, instance_id in self._cluster_node_info_cache.get_alive_nodes() + if node_id in proxy_nodes + ] + + if location == DeploymentMode.HeadOnly: + nodes = [ + (node_id, ip_address, instance_id) + for node_id, ip_address, instance_id in target_nodes + if node_id == self._head_node_id + ] + assert len(nodes) == 1, ( + f"Head node not found! Head node id: {self._head_node_id}, " + f"all nodes: {target_nodes}." + ) + return nodes + + return target_nodes + + def _generate_actor_name(self, node_id: str) -> str: + return format_actor_name(SERVE_PROXY_NAME, node_id) + + def _start_proxy( + self, + name: str, + node_id: str, + node_ip_address: str, + ) -> ProxyWrapper: + """Helper to start or reuse existing proxy and wrap in the proxy actor wrapper. + + Compute the HTTP port based on `TEST_WORKER_NODE_HTTP_PORT` env var and gRPC + port based on `TEST_WORKER_NODE_GRPC_PORT` env var. Passed all the required + variables into the proxy actor wrapper class and return the proxy actor wrapper. + """ + http_options = self._http_options + grpc_options = self._grpc_options + + if ( + node_id != self._head_node_id + and os.getenv("TEST_WORKER_NODE_HTTP_PORT") is not None + ): + logger.warning( + f"`TEST_WORKER_NODE_HTTP_PORT` env var is set. " + f"Using it for worker node {node_id}." + ) + http_options = deepcopy(http_options) + http_options.port = int(os.getenv("TEST_WORKER_NODE_HTTP_PORT")) + + if ( + node_id != self._head_node_id + and os.getenv("TEST_WORKER_NODE_GRPC_PORT") is not None + ): + logger.warning( + f"`TEST_WORKER_NODE_GRPC_PORT` env var is set. " + f"Using it for worker node {node_id}." + f"{int(os.getenv('TEST_WORKER_NODE_GRPC_PORT'))}" + ) + grpc_options = deepcopy(grpc_options) + grpc_options.port = int(os.getenv("TEST_WORKER_NODE_GRPC_PORT")) + + return self._actor_proxy_wrapper_class( + logging_config=self.logging_config, + http_options=http_options, + grpc_options=grpc_options, + name=name, + node_id=node_id, + node_ip_address=node_ip_address, + proxy_actor_class=self._proxy_actor_class, + ) + + def _start_proxies_if_needed(self, target_nodes) -> None: + """Start a proxy on every node if it doesn't already exist.""" + + for node_id, node_ip_address, node_instance_id in target_nodes: + if node_id in self._proxy_states: + continue + + name = self._generate_actor_name(node_id=node_id) + actor_proxy_wrapper = self._start_proxy( + name=name, + node_id=node_id, + node_ip_address=node_ip_address, + ) + + self._proxy_states[node_id] = ProxyState( + actor_proxy_wrapper=actor_proxy_wrapper, + actor_name=name, + node_id=node_id, + node_ip=node_ip_address, + node_instance_id=node_instance_id, + proxy_restart_count=self._proxy_restart_counts.get(node_id, 0), + timer=self._timer, + ) + + def _stop_proxies_if_needed(self) -> bool: + """Removes proxy actors. + + Removes proxy actors from any nodes that no longer exist or unhealthy proxy. + """ + alive_node_ids = self._cluster_node_info_cache.get_alive_node_ids() + to_stop = [] + for node_id, proxy_state in self._proxy_states.items(): + if node_id not in alive_node_ids: + logger.info(f"Removing proxy on removed node '{node_id}'.") + to_stop.append(node_id) + elif proxy_state.status == ProxyStatus.UNHEALTHY: + logger.info( + f"Proxy on node '{node_id}' is unhealthy. Shutting down " + "the unhealthy proxy and starting a new one." + ) + to_stop.append(node_id) + elif proxy_state.status == ProxyStatus.DRAINED: + logger.info(f"Removing drained proxy on node '{node_id}'.") + to_stop.append(node_id) + + for node_id in to_stop: + proxy_state = self._proxy_states.pop(node_id) + self._proxy_restart_counts[node_id] = proxy_state.proxy_restart_count + 1 + proxy_state.shutdown() + + +def _try_set_exception(fut: asyncio.Future, e: Exception): + if not fut.done(): + fut.set_exception(e) + + +def wrap_as_future(ref: ObjectRef, timeout_s: Optional[float] = None) -> asyncio.Future: + loop = asyncio.get_running_loop() + + aio_fut = asyncio.wrap_future(ref.future()) + + if timeout_s is not None: + assert timeout_s >= 0, "Timeout value should be non-negative" + # Schedule handler to complete future exceptionally + timeout_handler = loop.call_later( + max(timeout_s, 0), + _try_set_exception, + aio_fut, + TimeoutError(f"Future cancelled after timeout {timeout_s}s"), + ) + # Cancel timeout handler upon completion of the future + aio_fut.add_done_callback(lambda _: timeout_handler.cancel()) + + return aio_fut diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/replica.py b/venv/lib/python3.10/site-packages/ray/serve/_private/replica.py new file mode 100644 index 0000000000000000000000000000000000000000..23e74f8c173f992d5760bb76bcaba261011f5979 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/replica.py @@ -0,0 +1,1900 @@ +import asyncio +import concurrent.futures +import functools +import inspect +import logging +import os +import pickle +import threading +import time +import traceback +import warnings +from abc import ABC, abstractmethod +from collections import defaultdict, deque +from contextlib import asynccontextmanager, contextmanager +from dataclasses import dataclass +from importlib import import_module +from typing import ( + Any, + AsyncGenerator, + Callable, + Dict, + Generator, + Optional, + Tuple, + Union, +) + +import starlette.responses +from anyio import to_thread +from fastapi import Request +from starlette.applications import Starlette +from starlette.types import ASGIApp, Receive, Scope, Send + +import ray +from ray import cloudpickle +from ray._common.utils import get_or_create_event_loop +from ray.actor import ActorClass, ActorHandle +from ray.remote_function import RemoteFunction +from ray.serve import metrics +from ray.serve._private.common import ( + DeploymentID, + ReplicaID, + ReplicaQueueLengthInfo, + RequestMetadata, + ServeComponentType, + StreamingHTTPRequest, + gRPCRequest, +) +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import ( + GRPC_CONTEXT_ARG_NAME, + HEALTH_CHECK_METHOD, + RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE, + RAY_SERVE_METRICS_EXPORT_INTERVAL_MS, + RAY_SERVE_REPLICA_AUTOSCALING_METRIC_RECORD_PERIOD_S, + RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE, + RAY_SERVE_RUN_SYNC_IN_THREADPOOL, + RAY_SERVE_RUN_SYNC_IN_THREADPOOL_WARNING, + RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD, + RECONFIGURE_METHOD, + REQUEST_LATENCY_BUCKETS_MS, + REQUEST_ROUTING_STATS_METHOD, + SERVE_CONTROLLER_NAME, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.default_impl import ( + create_replica_impl, + create_replica_metrics_manager, +) +from ray.serve._private.http_util import ( + ASGIAppReplicaWrapper, + ASGIArgs, + ASGIReceiveProxy, + MessageQueue, + Response, +) +from ray.serve._private.logging_utils import ( + access_log_msg, + configure_component_cpu_profiler, + configure_component_logger, + configure_component_memory_profiler, + get_component_logger_file_path, +) +from ray.serve._private.metrics_utils import InMemoryMetricsStore, MetricsPusher +from ray.serve._private.thirdparty.get_asgi_route_name import get_asgi_route_name +from ray.serve._private.utils import ( + Semaphore, + get_component_file_name, # noqa: F401 + parse_import_path, +) +from ray.serve._private.version import DeploymentVersion +from ray.serve.config import AutoscalingConfig +from ray.serve.context import _get_in_flight_requests +from ray.serve.deployment import Deployment +from ray.serve.exceptions import ( + BackPressureError, + DeploymentUnavailableError, + RayServeException, +) +from ray.serve.schema import LoggingConfig + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +ReplicaMetadata = Tuple[ + DeploymentConfig, + DeploymentVersion, + Optional[float], + Optional[int], + Optional[str], +] + + +def _load_deployment_def_from_import_path(import_path: str) -> Callable: + module_name, attr_name = parse_import_path(import_path) + deployment_def = getattr(import_module(module_name), attr_name) + + # For ray or serve decorated class or function, strip to return + # original body. + if isinstance(deployment_def, RemoteFunction): + deployment_def = deployment_def._function + elif isinstance(deployment_def, ActorClass): + deployment_def = deployment_def.__ray_metadata__.modified_class + elif isinstance(deployment_def, Deployment): + logger.warning( + f'The import path "{import_path}" contains a ' + "decorated Serve deployment. The decorator's settings " + "are ignored when deploying via import path." + ) + deployment_def = deployment_def.func_or_class + + return deployment_def + + +class ReplicaMetricsManager: + """Manages metrics for the replica. + + A variety of metrics are managed: + - Fine-grained metrics are set for every request. + - Autoscaling statistics are periodically pushed to the controller. + - Queue length metrics are periodically recorded as user-facing gauges. + """ + + PUSH_METRICS_TO_CONTROLLER_TASK_NAME = "push_metrics_to_controller" + RECORD_METRICS_TASK_NAME = "record_metrics" + SET_REPLICA_REQUEST_METRIC_GAUGE_TASK_NAME = "set_replica_request_metric_gauge" + + def __init__( + self, + replica_id: ReplicaID, + event_loop: asyncio.BaseEventLoop, + autoscaling_config: Optional[AutoscalingConfig], + ingress: bool, + ): + self._replica_id = replica_id + self._metrics_pusher = MetricsPusher() + self._metrics_store = InMemoryMetricsStore() + self._autoscaling_config = autoscaling_config + self._ingress = ingress + self._controller_handle = ray.get_actor( + SERVE_CONTROLLER_NAME, namespace=SERVE_NAMESPACE + ) + self._num_ongoing_requests = 0 + + # If the interval is set to 0, eagerly sets all metrics. + self._cached_metrics_enabled = RAY_SERVE_METRICS_EXPORT_INTERVAL_MS != 0 + self._cached_metrics_interval_s = RAY_SERVE_METRICS_EXPORT_INTERVAL_MS / 1000 + + # Request counter (only set on replica startup). + self._restart_counter = metrics.Counter( + "serve_deployment_replica_starts", + description=( + "The number of times this replica has been restarted due to failure." + ), + ) + self._restart_counter.inc() + + # Per-request metrics. + self._request_counter = metrics.Counter( + "serve_deployment_request_counter", + description=( + "The number of queries that have been processed in this replica." + ), + tag_keys=("route",), + ) + if self._cached_metrics_enabled: + self._cached_request_counter = defaultdict(int) + + self._error_counter = metrics.Counter( + "serve_deployment_error_counter", + description=( + "The number of exceptions that have occurred in this replica." + ), + tag_keys=("route",), + ) + if self._cached_metrics_enabled: + self._cached_error_counter = defaultdict(int) + + # log REQUEST_LATENCY_BUCKET_MS + logger.debug(f"REQUEST_LATENCY_BUCKETS_MS: {REQUEST_LATENCY_BUCKETS_MS}") + self._processing_latency_tracker = metrics.Histogram( + "serve_deployment_processing_latency_ms", + description="The latency for queries to be processed.", + boundaries=REQUEST_LATENCY_BUCKETS_MS, + tag_keys=("route",), + ) + if self._cached_metrics_enabled: + self._cached_latencies = defaultdict(deque) + + self._num_ongoing_requests_gauge = metrics.Gauge( + "serve_replica_processing_queries", + description="The current number of queries being processed.", + ) + + self.set_autoscaling_config(autoscaling_config) + + if self._cached_metrics_enabled: + event_loop.create_task(self._report_cached_metrics_forever()) + + def _report_cached_metrics(self): + for route, count in self._cached_request_counter.items(): + self._request_counter.inc(count, tags={"route": route}) + self._cached_request_counter.clear() + + for route, count in self._cached_error_counter.items(): + self._error_counter.inc(count, tags={"route": route}) + self._cached_error_counter.clear() + + for route, latencies in self._cached_latencies.items(): + for latency_ms in latencies: + self._processing_latency_tracker.observe( + latency_ms, tags={"route": route} + ) + self._cached_latencies.clear() + + self._num_ongoing_requests_gauge.set(self._num_ongoing_requests) + + async def _report_cached_metrics_forever(self): + assert self._cached_metrics_interval_s > 0 + + consecutive_errors = 0 + while True: + try: + await asyncio.sleep(self._cached_metrics_interval_s) + self._report_cached_metrics() + consecutive_errors = 0 + except Exception: + logger.exception("Unexpected error reporting metrics.") + + # Exponential backoff starting at 1s and capping at 10s. + backoff_time_s = min(10, 2**consecutive_errors) + consecutive_errors += 1 + await asyncio.sleep(backoff_time_s) + + async def shutdown(self): + """Stop periodic background tasks.""" + + await self._metrics_pusher.graceful_shutdown() + + def should_collect_metrics(self) -> bool: + return ( + not RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE + and self._autoscaling_config + ) + + def set_autoscaling_config(self, autoscaling_config: Optional[AutoscalingConfig]): + """Dynamically update autoscaling config.""" + + self._autoscaling_config = autoscaling_config + + if self.should_collect_metrics(): + self._metrics_pusher.start() + + # Push autoscaling metrics to the controller periodically. + self._metrics_pusher.register_or_update_task( + self.PUSH_METRICS_TO_CONTROLLER_TASK_NAME, + self._push_autoscaling_metrics, + self._autoscaling_config.metrics_interval_s, + ) + # Collect autoscaling metrics locally periodically. + self._metrics_pusher.register_or_update_task( + self.RECORD_METRICS_TASK_NAME, + self._add_autoscaling_metrics_point, + min( + RAY_SERVE_REPLICA_AUTOSCALING_METRIC_RECORD_PERIOD_S, + self._autoscaling_config.metrics_interval_s, + ), + ) + + def inc_num_ongoing_requests(self, request_metadata: RequestMetadata) -> int: + """Increment the current total queue length of requests for this replica.""" + self._num_ongoing_requests += 1 + if not self._cached_metrics_enabled: + self._num_ongoing_requests_gauge.set(self._num_ongoing_requests) + + def dec_num_ongoing_requests(self, request_metadata: RequestMetadata) -> int: + """Decrement the current total queue length of requests for this replica.""" + self._num_ongoing_requests -= 1 + if not self._cached_metrics_enabled: + self._num_ongoing_requests_gauge.set(self._num_ongoing_requests) + + def get_num_ongoing_requests(self) -> int: + """Get current total queue length of requests for this replica.""" + return self._num_ongoing_requests + + def record_request_metrics(self, *, route: str, latency_ms: float, was_error: bool): + """Records per-request metrics.""" + if self._cached_metrics_enabled: + self._cached_latencies[route].append(latency_ms) + if was_error: + self._cached_error_counter[route] += 1 + else: + self._cached_request_counter[route] += 1 + else: + self._processing_latency_tracker.observe(latency_ms, tags={"route": route}) + if was_error: + self._error_counter.inc(tags={"route": route}) + else: + self._request_counter.inc(tags={"route": route}) + + def _push_autoscaling_metrics(self) -> Dict[str, Any]: + look_back_period = self._autoscaling_config.look_back_period_s + self._controller_handle.record_autoscaling_metrics.remote( + replica_id=self._replica_id, + window_avg=self._metrics_store.window_average( + self._replica_id, time.time() - look_back_period + ), + send_timestamp=time.time(), + ) + + def _add_autoscaling_metrics_point(self) -> None: + self._metrics_store.add_metrics_point( + {self._replica_id: self._num_ongoing_requests}, + time.time(), + ) + + +StatusCodeCallback = Callable[[str], None] + + +class ReplicaBase(ABC): + def __init__( + self, + replica_id: ReplicaID, + deployment_def: Callable, + init_args: Tuple, + init_kwargs: Dict, + deployment_config: DeploymentConfig, + version: DeploymentVersion, + ingress: bool, + route_prefix: str, + ): + self._version = version + self._replica_id = replica_id + self._deployment_id = replica_id.deployment_id + self._deployment_config = deployment_config + self._ingress = ingress + self._route_prefix = route_prefix + self._component_name = f"{self._deployment_id.name}" + if self._deployment_id.app_name: + self._component_name = ( + f"{self._deployment_id.app_name}_" + self._component_name + ) + + self._component_id = self._replica_id.unique_id + self._configure_logger_and_profilers(self._deployment_config.logging_config) + self._event_loop = get_or_create_event_loop() + + self._user_callable_wrapper = UserCallableWrapper( + deployment_def, + init_args, + init_kwargs, + deployment_id=self._deployment_id, + run_sync_methods_in_threadpool=RAY_SERVE_RUN_SYNC_IN_THREADPOOL, + run_user_code_in_separate_thread=RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD, + local_testing_mode=False, + ) + self._semaphore = Semaphore(lambda: self.max_ongoing_requests) + + # Guards against calling the user's callable constructor multiple times. + self._user_callable_initialized = False + self._user_callable_initialized_lock = asyncio.Lock() + self._initialization_latency: Optional[float] = None + + # Flipped to `True` when health checks pass and `False` when they fail. May be + # used by replica subclass implementations. + self._healthy = False + # Flipped to `True` once graceful shutdown is initiated. May be used by replica + # subclass implementations. + self._shutting_down = False + + # Will be populated with the wrapped ASGI app if the user callable is an + # `ASGIAppReplicaWrapper` (i.e., they are using the FastAPI integration). + self._user_callable_asgi_app: Optional[ASGIApp] = None + + # Set metadata for logs and metrics. + # servable_object will be populated in `initialize_and_get_metadata`. + self._set_internal_replica_context(servable_object=None) + + self._metrics_manager = create_replica_metrics_manager( + replica_id=replica_id, + event_loop=self._event_loop, + autoscaling_config=self._deployment_config.autoscaling_config, + ingress=ingress, + ) + + self._port: Optional[int] = None + self._docs_path: Optional[str] = None + + @property + def max_ongoing_requests(self) -> int: + return self._deployment_config.max_ongoing_requests + + def get_num_ongoing_requests(self) -> int: + return self._metrics_manager.get_num_ongoing_requests() + + def get_metadata(self) -> ReplicaMetadata: + return ( + self._version.deployment_config, + self._version, + self._initialization_latency, + self._port, + self._docs_path, + ) + + def _set_internal_replica_context(self, *, servable_object: Callable = None): + ray.serve.context._set_internal_replica_context( + replica_id=self._replica_id, + servable_object=servable_object, + _deployment_config=self._deployment_config, + ) + + def _configure_logger_and_profilers( + self, logging_config: Union[None, Dict, LoggingConfig] + ): + + if logging_config is None: + logging_config = {} + if isinstance(logging_config, dict): + logging_config = LoggingConfig(**logging_config) + + configure_component_logger( + component_type=ServeComponentType.REPLICA, + component_name=self._component_name, + component_id=self._component_id, + logging_config=logging_config, + buffer_size=RAY_SERVE_REQUEST_PATH_LOG_BUFFER_SIZE, + ) + configure_component_memory_profiler( + component_type=ServeComponentType.REPLICA, + component_name=self._component_name, + component_id=self._component_id, + ) + self.cpu_profiler, self.cpu_profiler_log = configure_component_cpu_profiler( + component_type=ServeComponentType.REPLICA, + component_name=self._component_name, + component_id=self._component_id, + ) + + def _can_accept_request(self, request_metadata: RequestMetadata) -> bool: + # This replica gates concurrent request handling with an asyncio.Semaphore. + # Each in-flight request acquires the semaphore. When the number of ongoing + # requests reaches max_ongoing_requests, the semaphore becomes locked. + # A new request can be accepted if the semaphore is currently unlocked. + return not self._semaphore.locked() + + def _maybe_get_http_route( + self, request_metadata: RequestMetadata, request_args: Tuple[Any] + ) -> Optional[str]: + """Get the matched route string for ASGI apps to be used in logs & metrics. + + If this replica does not wrap an ASGI app or there is no matching for the + request, returns the existing route from the request metadata. + """ + route = request_metadata.route + if self._user_callable_asgi_app is not None: + req: StreamingHTTPRequest = request_args[0] + try: + matched_route = get_asgi_route_name( + self._user_callable_asgi_app, req.asgi_scope + ) + except Exception: + matched_route = None + logger.exception( + "Failed unexpectedly trying to get route name for request. " + "Routes in metric tags and log messages may be inaccurate. " + "Please file a GitHub issue containing this traceback." + ) + + # If there is no match in the ASGI app, don't overwrite the route_prefix + # from the proxy. + if matched_route is not None: + route = matched_route + + return route + + @contextmanager + def _handle_errors_and_metrics( + self, request_metadata: RequestMetadata + ) -> Generator[StatusCodeCallback, None, None]: + start_time = time.time() + user_exception = None + + status_code = None + + def _status_code_callback(s: str): + nonlocal status_code + status_code = s + + try: + yield _status_code_callback + except asyncio.CancelledError as e: + user_exception = e + self._on_request_cancelled(request_metadata, e) + except Exception as e: + user_exception = e + logger.exception("Request failed.") + self._on_request_failed(request_metadata, e) + + latency_ms = (time.time() - start_time) * 1000 + self._record_errors_and_metrics( + user_exception, status_code, latency_ms, request_metadata + ) + + if user_exception is not None: + raise user_exception from None + + def _record_errors_and_metrics( + self, + user_exception: Optional[BaseException], + status_code: Optional[str], + latency_ms: float, + request_metadata: RequestMetadata, + ): + http_method = request_metadata._http_method + http_route = request_metadata.route + call_method = request_metadata.call_method + if user_exception is None: + status_str = "OK" + elif isinstance(user_exception, asyncio.CancelledError): + status_str = "CANCELLED" + else: + status_str = "ERROR" + + # Set in _wrap_request. + logger.info( + access_log_msg( + method=http_method or "CALL", + route=http_route or call_method, + # Prefer the HTTP status code if it was populated. + status=status_code or status_str, + latency_ms=latency_ms, + ), + extra={"serve_access_log": True}, + ) + self._metrics_manager.record_request_metrics( + route=http_route, + latency_ms=latency_ms, + was_error=user_exception is not None, + ) + + def _unpack_proxy_args( + self, + request_metadata: RequestMetadata, + request_args: Tuple[Any], + request_kwargs: Dict[str, Any], + ): + if request_metadata.is_http_request: + assert len(request_args) == 1 and isinstance( + request_args[0], StreamingHTTPRequest + ) + request: StreamingHTTPRequest = request_args[0] + scope = request.asgi_scope + receive = ASGIReceiveProxy( + scope, request_metadata, request.receive_asgi_messages + ) + + request_metadata._http_method = scope.get("method", "WS") + request_metadata.route = self._maybe_get_http_route( + request_metadata, request_args + ) + + request_args = (scope, receive) + elif request_metadata.is_grpc_request: + assert len(request_args) == 1 and isinstance(request_args[0], gRPCRequest) + request: gRPCRequest = request_args[0] + + method_info = self._user_callable_wrapper.get_user_method_info( + request_metadata.call_method + ) + request_args = (request.user_request_proto,) + request_kwargs = ( + {GRPC_CONTEXT_ARG_NAME: request_metadata.grpc_context} + if method_info.takes_grpc_context_kwarg + else {} + ) + + return request_args, request_kwargs + + async def handle_request( + self, request_metadata: RequestMetadata, *request_args, **request_kwargs + ) -> Tuple[bytes, Any]: + request_args, request_kwargs = self._unpack_proxy_args( + request_metadata, request_args, request_kwargs + ) + with self._wrap_request(request_metadata): + async with self._start_request(request_metadata): + return await self._user_callable_wrapper.call_user_method( + request_metadata, request_args, request_kwargs + ) + + async def handle_request_streaming( + self, request_metadata: RequestMetadata, *request_args, **request_kwargs + ) -> AsyncGenerator[Any, None]: + """Generator that is the entrypoint for all `stream=True` handle calls.""" + request_args, request_kwargs = self._unpack_proxy_args( + request_metadata, request_args, request_kwargs + ) + with self._wrap_request(request_metadata) as status_code_callback: + async with self._start_request(request_metadata): + if request_metadata.is_http_request: + scope, receive = request_args + async for msgs in self._user_callable_wrapper.call_http_entrypoint( + request_metadata, + status_code_callback, + scope, + receive, + ): + yield pickle.dumps(msgs) + else: + async for result in self._user_callable_wrapper.call_user_generator( + request_metadata, + request_args, + request_kwargs, + ): + yield result + + async def handle_request_with_rejection( + self, request_metadata: RequestMetadata, *request_args, **request_kwargs + ): + # Check if the replica has capacity for the request. + if not self._can_accept_request(request_metadata): + limit = self.max_ongoing_requests + logger.warning( + f"Replica at capacity of max_ongoing_requests={limit}, " + f"rejecting request {request_metadata.request_id}.", + extra={"log_to_stderr": False}, + ) + yield ReplicaQueueLengthInfo(False, self.get_num_ongoing_requests()) + return + + request_args, request_kwargs = self._unpack_proxy_args( + request_metadata, request_args, request_kwargs + ) + with self._wrap_request(request_metadata) as status_code_callback: + async with self._start_request(request_metadata): + yield ReplicaQueueLengthInfo( + accepted=True, + # NOTE(edoakes): `_wrap_request` will increment the number + # of ongoing requests to include this one, so re-fetch the value. + num_ongoing_requests=self.get_num_ongoing_requests(), + ) + + if request_metadata.is_http_request: + scope, receive = request_args + async for msgs in self._user_callable_wrapper.call_http_entrypoint( + request_metadata, + status_code_callback, + scope, + receive, + ): + yield pickle.dumps(msgs) + elif request_metadata.is_streaming: + async for result in self._user_callable_wrapper.call_user_generator( + request_metadata, + request_args, + request_kwargs, + ): + yield result + else: + yield await self._user_callable_wrapper.call_user_method( + request_metadata, request_args, request_kwargs + ) + + @abstractmethod + async def _on_initialized(self): + raise NotImplementedError + + async def initialize(self, deployment_config: DeploymentConfig): + try: + # Ensure that initialization is only performed once. + # When controller restarts, it will call this method again. + async with self._user_callable_initialized_lock: + self._initialization_start_time = time.time() + if not self._user_callable_initialized: + self._user_callable_asgi_app = ( + await self._user_callable_wrapper.initialize_callable() + ) + if self._user_callable_asgi_app: + self._docs_path = ( + self._user_callable_wrapper._callable.docs_path + ) + await self._on_initialized() + self._user_callable_initialized = True + + if deployment_config: + await self._user_callable_wrapper.set_sync_method_threadpool_limit( + deployment_config.max_ongoing_requests + ) + await self._user_callable_wrapper.call_reconfigure( + deployment_config.user_config + ) + + # A new replica should not be considered healthy until it passes + # an initial health check. If an initial health check fails, + # consider it an initialization failure. + await self.check_health() + except Exception: + raise RuntimeError(traceback.format_exc()) from None + + async def reconfigure(self, deployment_config: DeploymentConfig): + try: + user_config_changed = ( + deployment_config.user_config != self._deployment_config.user_config + ) + logging_config_changed = ( + deployment_config.logging_config + != self._deployment_config.logging_config + ) + self._deployment_config = deployment_config + self._version = DeploymentVersion.from_deployment_version( + self._version, deployment_config + ) + + self._metrics_manager.set_autoscaling_config( + deployment_config.autoscaling_config + ) + if logging_config_changed: + self._configure_logger_and_profilers(deployment_config.logging_config) + + await self._user_callable_wrapper.set_sync_method_threadpool_limit( + deployment_config.max_ongoing_requests + ) + if user_config_changed: + await self._user_callable_wrapper.call_reconfigure( + deployment_config.user_config + ) + + # We need to update internal replica context to reflect the new + # deployment_config. + self._set_internal_replica_context( + servable_object=self._user_callable_wrapper.user_callable + ) + except Exception: + raise RuntimeError(traceback.format_exc()) from None + + @abstractmethod + def _on_request_cancelled( + self, request_metadata: RequestMetadata, e: asyncio.CancelledError + ): + pass + + @abstractmethod + def _on_request_failed(self, request_metadata: RequestMetadata, e: Exception): + pass + + @abstractmethod + @contextmanager + def _wrap_request( + self, request_metadata: RequestMetadata + ) -> Generator[StatusCodeCallback, None, None]: + pass + + @asynccontextmanager + async def _start_request(self, request_metadata: RequestMetadata): + async with self._semaphore: + try: + self._metrics_manager.inc_num_ongoing_requests(request_metadata) + yield + finally: + self._metrics_manager.dec_num_ongoing_requests(request_metadata) + + async def _drain_ongoing_requests(self): + """Wait for any ongoing requests to finish. + + Sleep for a grace period before the first time we check the number of ongoing + requests to allow the notification to remove this replica to propagate to + callers first. + """ + wait_loop_period_s = self._deployment_config.graceful_shutdown_wait_loop_s + while True: + await asyncio.sleep(wait_loop_period_s) + + num_ongoing_requests = self._metrics_manager.get_num_ongoing_requests() + if num_ongoing_requests > 0: + logger.info( + f"Waiting for an additional {wait_loop_period_s}s to shut down " + f"because there are {num_ongoing_requests} ongoing requests." + ) + else: + logger.info( + "Graceful shutdown complete; replica exiting.", + extra={"log_to_stderr": False}, + ) + break + + async def shutdown(self): + try: + await self._user_callable_wrapper.call_destructor() + except: # noqa: E722 + # We catch a blanket exception since the constructor may still be + # running, so instance variables used by the destructor may not exist. + if self._user_callable_initialized: + logger.exception( + "__del__ ran before replica finished initializing, and " + "raised an exception." + ) + else: + logger.exception("__del__ raised an exception.") + + await self._metrics_manager.shutdown() + + async def perform_graceful_shutdown(self): + self._shutting_down = True + + # If the replica was never initialized it never served traffic, so we + # can skip the wait period. + if self._user_callable_initialized: + await self._drain_ongoing_requests() + + await self.shutdown() + + async def check_health(self): + try: + # If there's no user-defined health check, nothing runs on the user code event + # loop and no future is returned. + f = self._user_callable_wrapper.call_user_health_check() + if f is not None: + await f + self._healthy = True + except Exception as e: + logger.warning("Replica health check failed.") + self._healthy = False + raise e from None + + async def record_routing_stats(self) -> Dict[str, Any]: + try: + f = self._user_callable_wrapper.call_user_record_routing_stats() + if f is not None: + return await f + return {} + except Exception as e: + logger.warning("Replica record routing stats failed.") + raise e from None + + +class Replica(ReplicaBase): + async def _on_initialized(self): + self._set_internal_replica_context( + servable_object=self._user_callable_wrapper.user_callable + ) + + # Save the initialization latency if the replica is initializing + # for the first time. + if self._initialization_latency is None: + self._initialization_latency = time.time() - self._initialization_start_time + + def _on_request_cancelled( + self, metadata: RequestMetadata, e: asyncio.CancelledError + ): + """Recursively cancels child requests.""" + requests_pending_assignment = ( + ray.serve.context._get_requests_pending_assignment( + metadata.internal_request_id + ) + ) + for task in requests_pending_assignment.values(): + task.cancel() + + # Cancel child requests that have already been assigned. + in_flight_requests = _get_in_flight_requests(metadata.internal_request_id) + for replica_result in in_flight_requests.values(): + replica_result.cancel() + + def _on_request_failed(self, request_metadata: RequestMetadata, e: Exception): + if ray.util.pdb._is_ray_debugger_post_mortem_enabled(): + ray.util.pdb._post_mortem() + + @contextmanager + def _wrap_request( + self, request_metadata: RequestMetadata + ) -> Generator[StatusCodeCallback, None, None]: + """Context manager that wraps user method calls. + + 1) Sets the request context var with appropriate metadata. + 2) Records the access log message (if not disabled). + 3) Records per-request metrics via the metrics manager. + """ + ray.serve.context._serve_request_context.set( + ray.serve.context._RequestContext( + route=request_metadata.route, + request_id=request_metadata.request_id, + _internal_request_id=request_metadata.internal_request_id, + app_name=self._deployment_id.app_name, + multiplexed_model_id=request_metadata.multiplexed_model_id, + grpc_context=request_metadata.grpc_context, + ) + ) + + with self._handle_errors_and_metrics(request_metadata) as status_code_callback: + yield status_code_callback + + +class ReplicaActor: + """Actor definition for replicas of Ray Serve deployments. + + This class defines the interface that the controller and deployment handles + (i.e., from proxies and other replicas) use to interact with a replica. + + All interaction with the user-provided callable is done via the + `UserCallableWrapper` class. + """ + + async def __init__( + self, + replica_id: ReplicaID, + serialized_deployment_def: bytes, + serialized_init_args: bytes, + serialized_init_kwargs: bytes, + deployment_config_proto_bytes: bytes, + version: DeploymentVersion, + ingress: bool, + route_prefix: str, + ): + deployment_config = DeploymentConfig.from_proto_bytes( + deployment_config_proto_bytes + ) + deployment_def = cloudpickle.loads(serialized_deployment_def) + if isinstance(deployment_def, str): + deployment_def = _load_deployment_def_from_import_path(deployment_def) + self._replica_impl: ReplicaBase = create_replica_impl( + replica_id=replica_id, + deployment_def=deployment_def, + init_args=cloudpickle.loads(serialized_init_args), + init_kwargs=cloudpickle.loads(serialized_init_kwargs), + deployment_config=deployment_config, + version=version, + ingress=ingress, + route_prefix=route_prefix, + ) + + def push_proxy_handle(self, handle: ActorHandle): + # NOTE(edoakes): it's important to call a method on the proxy handle to + # initialize its state in the C++ core worker. + handle.pong.remote() + + def get_num_ongoing_requests(self) -> int: + """Fetch the number of ongoing requests at this replica (queue length). + + This runs on a separate thread (using a Ray concurrency group) so it will + not be blocked by user code. + """ + return self._replica_impl.get_num_ongoing_requests() + + async def is_allocated(self) -> str: + """poke the replica to check whether it's alive. + + When calling this method on an ActorHandle, it will complete as + soon as the actor has started running. We use this mechanism to + detect when a replica has been allocated a worker slot. + At this time, the replica can transition from PENDING_ALLOCATION + to PENDING_INITIALIZATION startup state. + + Returns: + The PID, actor ID, node ID, node IP, and log filepath id of the replica. + """ + + return ( + os.getpid(), + ray.get_runtime_context().get_actor_id(), + ray.get_runtime_context().get_worker_id(), + ray.get_runtime_context().get_node_id(), + ray.util.get_node_ip_address(), + ray.util.get_node_instance_id(), + get_component_logger_file_path(), + ) + + async def initialize_and_get_metadata( + self, deployment_config: DeploymentConfig = None, _after: Optional[Any] = None + ) -> ReplicaMetadata: + """Handles initializing the replica. + + Returns: 3-tuple containing + 1. DeploymentConfig of the replica + 2. DeploymentVersion of the replica + 3. Initialization duration in seconds + """ + # Unused `_after` argument is for scheduling: passing an ObjectRef + # allows delaying this call until after the `_after` call has returned. + await self._replica_impl.initialize(deployment_config) + return self._replica_impl.get_metadata() + + async def check_health(self): + await self._replica_impl.check_health() + + async def record_routing_stats(self) -> Dict[str, Any]: + return await self._replica_impl.record_routing_stats() + + async def reconfigure(self, deployment_config) -> ReplicaMetadata: + await self._replica_impl.reconfigure(deployment_config) + return self._replica_impl.get_metadata() + + def _preprocess_request_args( + self, + pickled_request_metadata: bytes, + request_args: Tuple[Any], + ) -> Tuple[RequestMetadata, Tuple[Any]]: + request_metadata = pickle.loads(pickled_request_metadata) + if request_metadata.is_http_request or request_metadata.is_grpc_request: + request_args = (pickle.loads(request_args[0]),) + + return request_metadata, request_args + + async def handle_request( + self, + pickled_request_metadata: bytes, + *request_args, + **request_kwargs, + ) -> Tuple[bytes, Any]: + """Entrypoint for `stream=False` calls.""" + request_metadata, request_args = self._preprocess_request_args( + pickled_request_metadata, request_args + ) + result = await self._replica_impl.handle_request( + request_metadata, *request_args, **request_kwargs + ) + if request_metadata.is_grpc_request: + result = (request_metadata.grpc_context, result.SerializeToString()) + + return result + + async def handle_request_streaming( + self, + pickled_request_metadata: bytes, + *request_args, + **request_kwargs, + ) -> AsyncGenerator[Any, None]: + """Generator that is the entrypoint for all `stream=True` handle calls.""" + request_metadata, request_args = self._preprocess_request_args( + pickled_request_metadata, request_args + ) + async for result in self._replica_impl.handle_request_streaming( + request_metadata, *request_args, **request_kwargs + ): + if request_metadata.is_grpc_request: + result = (request_metadata.grpc_context, result.SerializeToString()) + + yield result + + async def handle_request_with_rejection( + self, + pickled_request_metadata: bytes, + *request_args, + **request_kwargs, + ) -> AsyncGenerator[Any, None]: + """Entrypoint for all requests with strict max_ongoing_requests enforcement. + + The first response from this generator is always a system message indicating + if the request was accepted (the replica has capacity for the request) or + rejected (the replica is already at max_ongoing_requests). + + For non-streaming requests, there will only be one more message, the unary + result of the user request handler. + + For streaming requests, the subsequent messages will be the results of the + user request handler (which must be a generator). + """ + request_metadata, request_args = self._preprocess_request_args( + pickled_request_metadata, request_args + ) + async for result in self._replica_impl.handle_request_with_rejection( + request_metadata, *request_args, **request_kwargs + ): + if isinstance(result, ReplicaQueueLengthInfo): + yield pickle.dumps(result) + else: + if request_metadata.is_grpc_request: + result = (request_metadata.grpc_context, result.SerializeToString()) + + yield result + + async def handle_request_from_java( + self, + proto_request_metadata: bytes, + *request_args, + **request_kwargs, + ) -> Any: + from ray.serve.generated.serve_pb2 import ( + RequestMetadata as RequestMetadataProto, + ) + + proto = RequestMetadataProto.FromString(proto_request_metadata) + request_metadata: RequestMetadata = RequestMetadata( + request_id=proto.request_id, + internal_request_id=proto.internal_request_id, + call_method=proto.call_method, + multiplexed_model_id=proto.multiplexed_model_id, + route=proto.route, + ) + return await self._replica_impl.handle_request( + request_metadata, *request_args, **request_kwargs + ) + + async def perform_graceful_shutdown(self): + await self._replica_impl.perform_graceful_shutdown() + + def _save_cpu_profile_data(self) -> str: + """Saves CPU profiling data, if CPU profiling is enabled. + + Logs a warning if CPU profiling is disabled. + """ + + if self.cpu_profiler is not None: + import marshal + + self.cpu_profiler.snapshot_stats() + with open(self.cpu_profiler_log, "wb") as f: + marshal.dump(self.cpu_profiler.stats, f) + logger.info(f'Saved CPU profile data to file "{self.cpu_profiler_log}"') + return self.cpu_profiler_log + else: + logger.error( + "Attempted to save CPU profile data, but failed because no " + "CPU profiler was running! Enable CPU profiling by enabling " + "the RAY_SERVE_ENABLE_CPU_PROFILING env var." + ) + + +@dataclass +class UserMethodInfo: + """Wrapper for a user method and its relevant metadata.""" + + callable: Callable + name: str + is_asgi_app: bool + takes_any_args: bool + takes_grpc_context_kwarg: bool + + @classmethod + def from_callable(cls, c: Callable, *, is_asgi_app: bool) -> "UserMethodInfo": + params = inspect.signature(c).parameters + return cls( + callable=c, + name=c.__name__, + is_asgi_app=is_asgi_app, + takes_any_args=len(params) > 0, + takes_grpc_context_kwarg=GRPC_CONTEXT_ARG_NAME in params, + ) + + +class UserCallableWrapper: + """Wraps a user-provided callable that is used to handle requests to a replica.""" + + service_unavailable_exceptions = (BackPressureError, DeploymentUnavailableError) + + def __init__( + self, + deployment_def: Callable, + init_args: Tuple, + init_kwargs: Dict, + *, + deployment_id: DeploymentID, + run_sync_methods_in_threadpool: bool, + run_user_code_in_separate_thread: bool, + local_testing_mode: bool, + ): + if not (inspect.isfunction(deployment_def) or inspect.isclass(deployment_def)): + raise TypeError( + "deployment_def must be a function or class. Instead, its type was " + f"{type(deployment_def)}." + ) + + self._deployment_def = deployment_def + self._init_args = init_args + self._init_kwargs = init_kwargs + self._is_function = inspect.isfunction(deployment_def) + self._deployment_id = deployment_id + self._local_testing_mode = local_testing_mode + self._destructor_called = False + self._run_sync_methods_in_threadpool = run_sync_methods_in_threadpool + self._run_user_code_in_separate_thread = run_user_code_in_separate_thread + self._warned_about_sync_method_change = False + self._cached_user_method_info: Dict[str, UserMethodInfo] = {} + + # Will be populated in `initialize_callable`. + self._callable = None + + if self._run_user_code_in_separate_thread: + # All interactions with user code run on this loop to avoid blocking the + # replica's main event loop. + self._user_code_event_loop: asyncio.AbstractEventLoop = ( + asyncio.new_event_loop() + ) + + def _run_user_code_event_loop(): + # Required so that calls to get the current running event loop work + # properly in user code. + asyncio.set_event_loop(self._user_code_event_loop) + self._user_code_event_loop.run_forever() + + self._user_code_event_loop_thread = threading.Thread( + daemon=True, + target=_run_user_code_event_loop, + ) + self._user_code_event_loop_thread.start() + else: + self._user_code_event_loop = asyncio.get_running_loop() + + @property + def event_loop(self) -> asyncio.AbstractEventLoop: + return self._user_code_event_loop + + def _run_user_code(f: Callable) -> Callable: + """Decorator to run a coroutine method on the user code event loop. + + The method will be modified to be a sync function that returns a + `asyncio.Future` if user code is running in a separate event loop. + Otherwise, it will return the coroutine directly. + """ + assert inspect.iscoroutinefunction( + f + ), "_run_user_code can only be used on coroutine functions." + + @functools.wraps(f) + def wrapper(self, *args, **kwargs) -> Any: + coro = f(self, *args, **kwargs) + if self._run_user_code_in_separate_thread: + fut = asyncio.run_coroutine_threadsafe(coro, self._user_code_event_loop) + if self._local_testing_mode: + return fut + + return asyncio.wrap_future(fut) + else: + return coro + + return wrapper + + @_run_user_code + async def set_sync_method_threadpool_limit(self, limit: int): + # NOTE(edoakes): the limit is thread local, so this must + # be run on the user code event loop. + to_thread.current_default_thread_limiter().total_tokens = limit + + def get_user_method_info(self, method_name: str) -> UserMethodInfo: + """Get UserMethodInfo for the provided call method name. + + This method is cached to avoid repeated expensive calls to `inspect.signature`. + """ + if method_name in self._cached_user_method_info: + return self._cached_user_method_info[method_name] + + if self._is_function: + user_method = self._callable + elif hasattr(self._callable, method_name): + user_method = getattr(self._callable, method_name) + else: + # Filter to methods that don't start with '__' prefix. + def callable_method_filter(attr): + if attr.startswith("__"): + return False + elif not callable(getattr(self._callable, attr)): + return False + + return True + + methods = list(filter(callable_method_filter, dir(self._callable))) + raise RayServeException( + f"Tried to call a method '{method_name}' " + "that does not exist. Available methods: " + f"{methods}." + ) + + info = UserMethodInfo.from_callable( + user_method, + is_asgi_app=isinstance(self._callable, ASGIAppReplicaWrapper), + ) + self._cached_user_method_info[method_name] = info + return info + + async def _send_user_result_over_asgi( + self, + result: Any, + asgi_args: ASGIArgs, + ): + """Handle the result from user code and send it over the ASGI interface. + + If the result is already a Response type, it is sent directly. Otherwise, it + is converted to a custom Response type that handles serialization for + common Python objects. + """ + scope, receive, send = asgi_args.to_args_tuple() + if isinstance(result, starlette.responses.Response): + await result(scope, receive, send) + else: + await Response(result).send(scope, receive, send) + + async def _call_func_or_gen( + self, + callable: Callable, + *, + args: Optional[Tuple[Any]] = None, + kwargs: Optional[Dict[str, Any]] = None, + is_streaming: bool = False, + generator_result_callback: Optional[Callable] = None, + run_sync_methods_in_threadpool_override: Optional[bool] = None, + ) -> Tuple[Any, bool]: + """Call the callable with the provided arguments. + + This is a convenience wrapper that will work for `def`, `async def`, + generator, and async generator functions. + + Returns the result and a boolean indicating if the result was a sync generator + that has already been consumed. + """ + sync_gen_consumed = False + args = args if args is not None else tuple() + kwargs = kwargs if kwargs is not None else dict() + run_sync_in_threadpool = ( + self._run_sync_methods_in_threadpool + if run_sync_methods_in_threadpool_override is None + else run_sync_methods_in_threadpool_override + ) + is_sync_method = ( + inspect.isfunction(callable) or inspect.ismethod(callable) + ) and not ( + inspect.iscoroutinefunction(callable) + or inspect.isasyncgenfunction(callable) + ) + + if is_sync_method and run_sync_in_threadpool: + is_generator = inspect.isgeneratorfunction(callable) + if is_generator: + sync_gen_consumed = True + if not is_streaming: + # TODO(edoakes): make this check less redundant with the one in + # _handle_user_method_result. + raise TypeError( + f"Method '{callable.__name__}' returned a generator. " + "You must use `handle.options(stream=True)` to call " + "generators on a deployment." + ) + + def run_callable(): + result = callable(*args, **kwargs) + if is_generator: + for r in result: + generator_result_callback(r) + + result = None + + return result + + # NOTE(edoakes): we use anyio.to_thread here because it's what Starlette + # uses (and therefore FastAPI too). The max size of the threadpool is + # set to max_ongoing_requests in the replica wrapper. + # anyio.to_thread propagates ContextVars to the worker thread automatically. + result = await to_thread.run_sync(run_callable) + else: + if ( + is_sync_method + and not self._warned_about_sync_method_change + and run_sync_methods_in_threadpool_override is None + ): + self._warned_about_sync_method_change = True + warnings.warn( + RAY_SERVE_RUN_SYNC_IN_THREADPOOL_WARNING.format( + method_name=callable.__name__, + ) + ) + + result = callable(*args, **kwargs) + if inspect.iscoroutine(result): + result = await result + + return result, sync_gen_consumed + + @property + def user_callable(self) -> Optional[Callable]: + return self._callable + + async def _initialize_asgi_callable(self) -> None: + self._callable: ASGIAppReplicaWrapper + + app: Starlette = self._callable.app + + # The reason we need to do this is because BackPressureError is a serve internal exception + # and FastAPI doesn't know how to handle it, so it treats it as a 500 error. + # With same reasoning, we are not handling TimeoutError because it's a generic exception + # the FastAPI knows how to handle. See https://www.starlette.io/exceptions/ + def handle_exception(_: Request, exc: Exception): + return self.handle_exception(exc) + + for exc in self.service_unavailable_exceptions: + app.add_exception_handler(exc, handle_exception) + + await self._callable._run_asgi_lifespan_startup() + + @_run_user_code + async def initialize_callable(self) -> Optional[ASGIApp]: + """Initialize the user callable. + + If the callable is an ASGI app wrapper (e.g., using @serve.ingress), returns + the ASGI app object, which may be used *read only* by the caller. + """ + if self._callable is not None: + raise RuntimeError("initialize_callable should only be called once.") + + # This closure initializes user code and finalizes replica + # startup. By splitting the initialization step like this, + # we can already access this actor before the user code + # has finished initializing. + # The supervising state manager can then wait + # for allocation of this replica by using the `is_allocated` + # method. After that, it calls `reconfigure` to trigger + # user code initialization. + logger.info( + "Started initializing replica.", + extra={"log_to_stderr": False}, + ) + + if self._is_function: + self._callable = self._deployment_def + else: + # This allows deployments to define an async __init__ + # method (mostly used for testing). + self._callable = self._deployment_def.__new__(self._deployment_def) + await self._call_func_or_gen( + self._callable.__init__, + args=self._init_args, + kwargs=self._init_kwargs, + # Always run the constructor on the main user code thread. + run_sync_methods_in_threadpool_override=False, + ) + + if isinstance(self._callable, ASGIAppReplicaWrapper): + await self._initialize_asgi_callable() + + self._user_health_check = getattr(self._callable, HEALTH_CHECK_METHOD, None) + self._user_record_routing_stats = getattr( + self._callable, REQUEST_ROUTING_STATS_METHOD, None + ) + + logger.info( + "Finished initializing replica.", + extra={"log_to_stderr": False}, + ) + + return ( + self._callable.app + if isinstance(self._callable, ASGIAppReplicaWrapper) + else None + ) + + def _raise_if_not_initialized(self, method_name: str): + if self._callable is None: + raise RuntimeError( + f"`initialize_callable` must be called before `{method_name}`." + ) + + def call_user_health_check(self) -> Optional[concurrent.futures.Future]: + self._raise_if_not_initialized("call_user_health_check") + + # If the user provided a health check, call it on the user code thread. If user + # code blocks the event loop the health check may time out. + # + # To avoid this issue for basic cases without a user-defined health check, skip + # interacting with the user callable entirely. + if self._user_health_check is not None: + return self._call_user_health_check() + + return None + + def call_user_record_routing_stats(self) -> Optional[concurrent.futures.Future]: + self._raise_if_not_initialized("call_user_record_routing_stats") + + if self._user_record_routing_stats is not None: + return self._call_user_record_routing_stats() + + return None + + @_run_user_code + async def _call_user_health_check(self): + await self._call_func_or_gen(self._user_health_check) + + @_run_user_code + async def _call_user_record_routing_stats(self) -> Dict[str, Any]: + result, _ = await self._call_func_or_gen(self._user_record_routing_stats) + return result + + @_run_user_code + async def call_reconfigure(self, user_config: Any): + self._raise_if_not_initialized("call_reconfigure") + + # NOTE(edoakes): there is the possibility of a race condition in user code if + # they don't have any form of concurrency control between `reconfigure` and + # other methods. See https://github.com/ray-project/ray/pull/42159. + if user_config is not None: + if self._is_function: + raise ValueError("deployment_def must be a class to use user_config") + elif not hasattr(self._callable, RECONFIGURE_METHOD): + raise RayServeException( + "user_config specified but deployment " + + self._deployment_id + + " missing " + + RECONFIGURE_METHOD + + " method" + ) + await self._call_func_or_gen( + getattr(self._callable, RECONFIGURE_METHOD), + args=(user_config,), + ) + + async def _handle_user_method_result( + self, + result: Any, + user_method_info: UserMethodInfo, + *, + is_streaming: bool, + is_http_request: bool, + sync_gen_consumed: bool, + generator_result_callback: Optional[Callable], + asgi_args: Optional[ASGIArgs], + ) -> Any: + """Postprocess the result of a user method. + + User methods can be regular unary functions or return a sync or async generator. + This method will raise an exception if the result is not of the expected type + (e.g., non-generator for streaming requests or generator for unary requests). + + Generator outputs will be written to the `generator_result_callback`. + + Note that HTTP requests are an exception: they are *always* streaming requests, + but for ASGI apps (like FastAPI), the actual method will be a regular function + implementing the ASGI `__call__` protocol. + """ + result_is_gen = inspect.isgenerator(result) + result_is_async_gen = inspect.isasyncgen(result) + if is_streaming: + if result_is_gen: + for r in result: + generator_result_callback(r) + elif result_is_async_gen: + async for r in result: + generator_result_callback(r) + elif is_http_request and not user_method_info.is_asgi_app: + # For the FastAPI codepath, the response has already been sent over + # ASGI, but for the vanilla deployment codepath we need to send it. + await self._send_user_result_over_asgi(result, asgi_args) + elif not is_http_request and not sync_gen_consumed: + # If a unary method is called with stream=True for anything EXCEPT + # an HTTP request, raise an error. + # HTTP requests are always streaming regardless of if the method + # returns a generator, because it's provided the result queue as its + # ASGI `send` interface to stream back results. + raise TypeError( + f"Called method '{user_method_info.name}' with " + "`handle.options(stream=True)` but it did not return a " + "generator." + ) + else: + assert ( + not is_http_request + ), "All HTTP requests go through the streaming codepath." + + if result_is_gen or result_is_async_gen: + raise TypeError( + f"Method '{user_method_info.name}' returned a generator. " + "You must use `handle.options(stream=True)` to call " + "generators on a deployment." + ) + + return result + + async def call_http_entrypoint( + self, + request_metadata: RequestMetadata, + status_code_callback: StatusCodeCallback, + scope: Scope, + receive: Receive, + ) -> Any: + result_queue = MessageQueue() + user_method_info = self.get_user_method_info(request_metadata.call_method) + + if self._run_user_code_in_separate_thread: + # `asyncio.Event`s are not thread safe, so `call_soon_threadsafe` must be + # used to interact with the result queue from the user callable thread. + system_event_loop = asyncio.get_running_loop() + + async def enqueue(item: Any): + system_event_loop.call_soon_threadsafe(result_queue.put_nowait, item) + + call_future = self._call_http_entrypoint( + user_method_info, scope, receive, enqueue + ) + else: + + async def enqueue(item: Any): + result_queue.put_nowait(item) + + call_future = asyncio.create_task( + self._call_http_entrypoint(user_method_info, scope, receive, enqueue) + ) + + first_message_peeked = False + async for messages in result_queue.fetch_messages_from_queue(call_future): + # HTTP (ASGI) messages are only consumed by the proxy so batch them + # and use vanilla pickle (we know it's safe because these messages + # only contain primitive Python types). + # Peek the first ASGI message to determine the status code. + if not first_message_peeked: + msg = messages[0] + first_message_peeked = True + if msg["type"] == "http.response.start": + # HTTP responses begin with exactly one + # "http.response.start" message containing the "status" + # field. Other response types like WebSockets may not. + status_code_callback(str(msg["status"])) + + yield messages + + @_run_user_code + async def _call_http_entrypoint( + self, + user_method_info: UserMethodInfo, + scope: Scope, + receive: Receive, + send: Send, + ) -> Any: + """Call an HTTP entrypoint. + + `send` is used to communicate the results of streaming responses. + + Raises any exception raised by the user code so it can be propagated as a + `RayTaskError`. + """ + self._raise_if_not_initialized("_call_http_entrypoint") + + logger.info( + f"Started executing request to method '{user_method_info.name}'.", + extra={"log_to_stderr": False, "serve_access_log": True}, + ) + + if user_method_info.is_asgi_app: + request_args = (scope, receive, send) + elif not user_method_info.takes_any_args: + # Edge case to support empty HTTP handlers: don't pass the Request + # argument if the callable has no parameters. + request_args = tuple() + else: + # Non-FastAPI HTTP handlers take only the starlette `Request`. + request_args = (starlette.requests.Request(scope, receive, send),) + + receive_task = None + try: + receive_task = asyncio.create_task(receive.fetch_until_disconnect()) + result, sync_gen_consumed = await self._call_func_or_gen( + user_method_info.callable, + args=request_args, + kwargs={}, + is_streaming=True, + generator_result_callback=send, + ) + final_result = await self._handle_user_method_result( + result, + user_method_info, + is_streaming=True, + is_http_request=True, + sync_gen_consumed=sync_gen_consumed, + generator_result_callback=send, + asgi_args=ASGIArgs(scope, receive, send), + ) + + if receive_task is not None and not receive_task.done(): + receive_task.cancel() + + return final_result + except Exception as e: + if not user_method_info.is_asgi_app: + response = self.handle_exception(e) + await self._send_user_result_over_asgi( + response, ASGIArgs(scope, receive, send) + ) + + if receive_task is not None and not receive_task.done(): + receive_task.cancel() + + raise + except asyncio.CancelledError: + if receive_task is not None and not receive_task.done(): + # Do NOT cancel the receive task if the request has been + # cancelled, but the call is a batched call. This is + # because we cannot guarantee cancelling the batched + # call, so in the case that the call continues executing + # we should continue fetching data from the client. + if not hasattr(user_method_info.callable, "set_max_batch_size"): + receive_task.cancel() + + raise + + async def call_user_generator( + self, + request_metadata: RequestMetadata, + request_args: Tuple[Any], + request_kwargs: Dict[str, Any], + ) -> AsyncGenerator[Any, None]: + """Calls a user method for a streaming call and yields its results. + + The user method is called in an asyncio `Task` and places its results on a + `result_queue`. This method pulls and yields from the `result_queue`. + """ + if not self._run_user_code_in_separate_thread: + gen = await self._call_user_generator( + request_metadata, request_args, request_kwargs + ) + async for result in gen: + yield result + else: + result_queue = MessageQueue() + + # `asyncio.Event`s are not thread safe, so `call_soon_threadsafe` must be + # used to interact with the result queue from the user callable thread. + system_event_loop = asyncio.get_running_loop() + + def _enqueue_thread_safe(item: Any): + system_event_loop.call_soon_threadsafe(result_queue.put_nowait, item) + + call_future = self._call_user_generator( + request_metadata, + request_args, + request_kwargs, + enqueue=_enqueue_thread_safe, + ) + + async for messages in result_queue.fetch_messages_from_queue(call_future): + for msg in messages: + yield msg + + @_run_user_code + async def _call_user_generator( + self, + request_metadata: RequestMetadata, + request_args: Tuple[Any], + request_kwargs: Dict[str, Any], + *, + enqueue: Optional[Callable] = None, + ) -> Optional[AsyncGenerator[Any, None]]: + """Call a user generator. + + The `generator_result_callback` is used to communicate the results of generator + methods. + + Raises any exception raised by the user code so it can be propagated as a + `RayTaskError`. + """ + self._raise_if_not_initialized("_call_user_generator") + + request_args = request_args if request_args is not None else tuple() + request_kwargs = request_kwargs if request_kwargs is not None else dict() + + user_method_info = self.get_user_method_info(request_metadata.call_method) + callable = user_method_info.callable + is_sync_method = ( + inspect.isfunction(callable) or inspect.ismethod(callable) + ) and not ( + inspect.iscoroutinefunction(callable) + or inspect.isasyncgenfunction(callable) + ) + + logger.info( + f"Started executing request to method '{user_method_info.name}'.", + extra={"log_to_stderr": False, "serve_access_log": True}, + ) + + async def _call_generator_async() -> AsyncGenerator[Any, None]: + gen = callable(*request_args, **request_kwargs) + if inspect.iscoroutine(gen): + gen = await gen + + if inspect.isgenerator(gen): + for result in gen: + yield result + elif inspect.isasyncgen(gen): + async for result in gen: + yield result + else: + raise TypeError( + f"Called method '{user_method_info.name}' with " + "`handle.options(stream=True)` but it did not return a generator." + ) + + def _call_generator_sync(): + gen = callable(*request_args, **request_kwargs) + if inspect.isgenerator(gen): + for result in gen: + enqueue(result) + else: + raise TypeError( + f"Called method '{user_method_info.name}' with " + "`handle.options(stream=True)` but it did not return a generator." + ) + + if enqueue and is_sync_method and self._run_sync_methods_in_threadpool: + await to_thread.run_sync(_call_generator_sync) + elif enqueue: + + async def gen_coro_wrapper(): + async for result in _call_generator_async(): + enqueue(result) + + await gen_coro_wrapper() + else: + return _call_generator_async() + + @_run_user_code + async def call_user_method( + self, + request_metadata: RequestMetadata, + request_args: Tuple[Any], + request_kwargs: Dict[str, Any], + ) -> Any: + """Call a (unary) user method. + + Raises any exception raised by the user code so it can be propagated as a + `RayTaskError`. + """ + self._raise_if_not_initialized("call_user_method") + + logger.info( + f"Started executing request to method '{request_metadata.call_method}'.", + extra={"log_to_stderr": False, "serve_access_log": True}, + ) + + user_method_info = self.get_user_method_info(request_metadata.call_method) + result, _ = await self._call_func_or_gen( + user_method_info.callable, + args=request_args, + kwargs=request_kwargs, + is_streaming=False, + ) + if inspect.isgenerator(result) or inspect.isasyncgen(result): + raise TypeError( + f"Method '{user_method_info.name}' returned a generator. " + "You must use `handle.options(stream=True)` to call " + "generators on a deployment." + ) + return result + + def handle_exception(self, exc: Exception): + if isinstance(exc, self.service_unavailable_exceptions): + return starlette.responses.Response(exc.message, status_code=503) + else: + return starlette.responses.Response( + "Internal Server Error", status_code=500 + ) + + @_run_user_code + async def call_destructor(self): + """Explicitly call the `__del__` method of the user callable. + + Calling this multiple times has no effect; only the first call will + actually call the destructor. + """ + if self._callable is None: + logger.info( + "This replica has not yet started running user code. " + "Skipping __del__." + ) + return + + # Only run the destructor once. This is safe because there is no `await` between + # checking the flag here and flipping it to `True` below. + if self._destructor_called: + return + + self._destructor_called = True + try: + if hasattr(self._callable, "__del__"): + # Make sure to accept `async def __del__(self)` as well. + await self._call_func_or_gen( + self._callable.__del__, + # Always run the destructor on the main user callable thread. + run_sync_methods_in_threadpool_override=False, + ) + + if hasattr(self._callable, "__serve_multiplex_wrapper"): + await getattr(self._callable, "__serve_multiplex_wrapper").shutdown() + + except Exception as e: + logger.exception(f"Exception during graceful shutdown of replica: {e}") diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/replica_result.py b/venv/lib/python3.10/site-packages/ray/serve/_private/replica_result.py new file mode 100644 index 0000000000000000000000000000000000000000..780b4a44bd45135454337c6733823454d75d8f53 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/replica_result.py @@ -0,0 +1,211 @@ +import asyncio +import inspect +import threading +import time +from abc import ABC, abstractmethod +from functools import wraps +from typing import Callable, Coroutine, Optional, Union + +import ray +from ray.serve._private.common import RequestMetadata +from ray.serve._private.utils import calculate_remaining_timeout, generate_request_id +from ray.serve.exceptions import RequestCancelledError + + +class ReplicaResult(ABC): + @abstractmethod + def get(self, timeout_s: Optional[float]): + raise NotImplementedError + + @abstractmethod + async def get_async(self): + raise NotImplementedError + + @abstractmethod + def __next__(self): + raise NotImplementedError + + @abstractmethod + async def __anext__(self): + raise NotImplementedError + + @abstractmethod + def add_done_callback(self, callback: Callable): + raise NotImplementedError + + @abstractmethod + def cancel(self): + raise NotImplementedError + + @abstractmethod + def to_object_ref(self, timeout_s: Optional[float]) -> ray.ObjectRef: + raise NotImplementedError + + @abstractmethod + async def to_object_ref_async(self) -> ray.ObjectRef: + raise NotImplementedError + + @abstractmethod + def to_object_ref_gen(self) -> ray.ObjectRefGenerator: + # NOTE(edoakes): there is only a sync version of this method because it + # does not block like `to_object_ref` (so there's also no timeout argument). + raise NotImplementedError + + +class ActorReplicaResult(ReplicaResult): + def __init__( + self, + obj_ref_or_gen: Union[ray.ObjectRef, ray.ObjectRefGenerator], + metadata: RequestMetadata, + ): + self._obj_ref: Optional[ray.ObjectRef] = None + self._obj_ref_gen: Optional[ray.ObjectRefGenerator] = None + self._is_streaming: bool = metadata.is_streaming + self._request_id: str = metadata.request_id + self._object_ref_or_gen_sync_lock = threading.Lock() + self._lazy_object_ref_or_gen_asyncio_lock = None + + if isinstance(obj_ref_or_gen, ray.ObjectRefGenerator): + self._obj_ref_gen = obj_ref_or_gen + else: + self._obj_ref = obj_ref_or_gen + + if self._is_streaming: + assert ( + self._obj_ref_gen is not None + ), "An ObjectRefGenerator must be passed for streaming requests." + + request_context = ray.serve.context._get_serve_request_context() + if request_context.cancel_on_parent_request_cancel: + # Keep track of in-flight requests. + self._response_id = generate_request_id() + ray.serve.context._add_in_flight_request( + request_context._internal_request_id, self._response_id, self + ) + self.add_done_callback( + lambda _: ray.serve.context._remove_in_flight_request( + request_context._internal_request_id, self._response_id + ) + ) + + @property + def _object_ref_or_gen_asyncio_lock(self) -> asyncio.Lock: + """Lazy `asyncio.Lock` object.""" + if self._lazy_object_ref_or_gen_asyncio_lock is None: + self._lazy_object_ref_or_gen_asyncio_lock = asyncio.Lock() + + return self._lazy_object_ref_or_gen_asyncio_lock + + def _process_response(f: Union[Callable, Coroutine]): + @wraps(f) + def wrapper(self, *args, **kwargs): + try: + return f(self, *args, **kwargs) + except ray.exceptions.TaskCancelledError: + raise RequestCancelledError(self._request_id) + + @wraps(f) + async def async_wrapper(self, *args, **kwargs): + try: + return await f(self, *args, **kwargs) + except ray.exceptions.TaskCancelledError: + raise asyncio.CancelledError() + + if inspect.iscoroutinefunction(f): + return async_wrapper + else: + return wrapper + + @_process_response + def get(self, timeout_s: Optional[float]): + assert ( + not self._is_streaming + ), "get() can only be called on a unary ActorReplicaResult." + + start_time_s = time.time() + object_ref = self.to_object_ref(timeout_s=timeout_s) + remaining_timeout_s = calculate_remaining_timeout( + timeout_s=timeout_s, + start_time_s=start_time_s, + curr_time_s=time.time(), + ) + return ray.get(object_ref, timeout=remaining_timeout_s) + + @_process_response + async def get_async(self): + assert ( + not self._is_streaming + ), "get_async() can only be called on a unary ActorReplicaResult." + + return await (await self.to_object_ref_async()) + + @_process_response + def __next__(self): + assert ( + self._is_streaming + ), "next() can only be called on a streaming ActorReplicaResult." + + next_obj_ref = self._obj_ref_gen.__next__() + return ray.get(next_obj_ref) + + @_process_response + async def __anext__(self): + assert ( + self._is_streaming + ), "__anext__() can only be called on a streaming ActorReplicaResult." + + next_obj_ref = await self._obj_ref_gen.__anext__() + return await next_obj_ref + + def add_done_callback(self, callback: Callable): + if self._obj_ref_gen is not None: + self._obj_ref_gen.completed()._on_completed(callback) + else: + self._obj_ref._on_completed(callback) + + def cancel(self): + if self._obj_ref_gen is not None: + ray.cancel(self._obj_ref_gen) + else: + ray.cancel(self._obj_ref) + + def to_object_ref(self, *, timeout_s: Optional[float] = None) -> ray.ObjectRef: + assert ( + not self._is_streaming + ), "to_object_ref can only be called on a unary ReplicaActorResult." + + # NOTE(edoakes): this section needs to be guarded with a lock and the resulting + # object ref cached in order to avoid calling `__next__()` to + # resolve to the underlying object ref more than once. + # See: https://github.com/ray-project/ray/issues/43879. + with self._object_ref_or_gen_sync_lock: + if self._obj_ref is None: + obj_ref = self._obj_ref_gen._next_sync(timeout_s=timeout_s) + if obj_ref.is_nil(): + raise TimeoutError("Timed out resolving to ObjectRef.") + + self._obj_ref = obj_ref + + return self._obj_ref + + async def to_object_ref_async(self) -> ray.ObjectRef: + assert ( + not self._is_streaming + ), "to_object_ref_async can only be called on a unary ReplicaActorResult." + + # NOTE(edoakes): this section needs to be guarded with a lock and the resulting + # object ref cached in order to avoid calling `__anext__()` to + # resolve to the underlying object ref more than once. + # See: https://github.com/ray-project/ray/issues/43879. + async with self._object_ref_or_gen_asyncio_lock: + if self._obj_ref is None: + self._obj_ref = await self._obj_ref_gen.__anext__() + + return self._obj_ref + + def to_object_ref_gen(self) -> ray.ObjectRefGenerator: + assert ( + self._is_streaming + ), "to_object_ref_gen can only be called on a streaming ReplicaActorResult." + + return self._obj_ref_gen diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__init__.py b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b4b7616810775a7b1857bc1247a3dc7126990572 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__init__.py @@ -0,0 +1,10 @@ +from ray.serve._private.request_router.common import PendingRequest # noqa: F401 +from ray.serve._private.request_router.pow_2_router import ( # noqa: F401 + PowerOfTwoChoicesRequestRouter, +) +from ray.serve._private.request_router.replica_wrapper import ( # noqa: F401 + RunningReplica, +) +from ray.serve._private.request_router.request_router import ( # noqa: F401 + RequestRouter, +) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4e991a7ef77efe960c7295da4730d80eee05a11 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/common.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2ec72fe8661fd7b5260952392e99bb5468b16fb Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/common.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/pow_2_router.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/pow_2_router.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45a86a90fd6df4ec8c59088281a9ca5e187cb8dd Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/pow_2_router.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/replica_wrapper.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/replica_wrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5068ac38c38a6324fac947b29f5bf4e34596ce88 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/replica_wrapper.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/request_router.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/request_router.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ce07cddac6b10ae36bb3133a1f71d501932f221 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/__pycache__/request_router.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/common.py b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/common.py new file mode 100644 index 0000000000000000000000000000000000000000..a58659d11ad2f1b6cd01a608e0de1365f3a8c2e9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/common.py @@ -0,0 +1,104 @@ +import asyncio +import logging +import time +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, List, Optional, Set + +from ray.serve._private.common import ReplicaID, RequestMetadata +from ray.serve._private.constants import ( + RAY_SERVE_QUEUE_LENGTH_CACHE_TIMEOUT_S, + SERVE_LOGGER_NAME, +) +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@dataclass() +class RequestRoutingContext: + multiplexed_start_matching_time: Optional[float] = None + tried_fewest_multiplexed_models: bool = False + tried_first_multiplexed_models: bool = False + tried_same_node: bool = False + tried_same_az: bool = False + should_backoff: bool = False + + +@PublicAPI(stability="alpha") +@dataclass +class PendingRequest: + """A request that is pending execution by a replica.""" + + args: List[Any] + """Positional arguments for the request.""" + + kwargs: Dict[Any, Any] + """Keyword arguments for the request.""" + + metadata: RequestMetadata + """Metadata for the request, including request ID and whether it's streaming.""" + + created_at: float = field(default_factory=time.time) + """Timestamp when the request was created.""" + + future: asyncio.Future = field(default_factory=lambda: asyncio.Future()) + """An asyncio Future that will be set when the request is routed.""" + + routing_context: RequestRoutingContext = field( + default_factory=RequestRoutingContext + ) + """Context for request routing, used to track routing attempts and backoff.""" + + def reset_future(self): + """Reset the `asyncio.Future`, must be called if this request is re-used.""" + self.future = asyncio.Future() + + +@dataclass(frozen=True) +class ReplicaQueueLengthCacheEntry: + queue_len: int + timestamp: float + + +class ReplicaQueueLengthCache: + def __init__( + self, + *, + staleness_timeout_s: float = RAY_SERVE_QUEUE_LENGTH_CACHE_TIMEOUT_S, + get_curr_time_s: Optional[Callable[[], float]] = None, + ): + self._cache: Dict[ReplicaID, ReplicaQueueLengthCacheEntry] = {} + self._staleness_timeout_s = staleness_timeout_s + self._get_curr_time_s = ( + get_curr_time_s if get_curr_time_s is not None else time.time + ) + + def _is_timed_out(self, timestamp_s: int) -> bool: + return self._get_curr_time_s() - timestamp_s > self._staleness_timeout_s + + def get(self, replica_id: ReplicaID) -> Optional[int]: + """Get the queue length for a replica. + + Returns `None` if the replica ID is not present or the entry is timed out. + """ + entry = self._cache.get(replica_id) + if entry is None or self._is_timed_out(entry.timestamp): + return None + + return entry.queue_len + + def update(self, replica_id: ReplicaID, queue_len: int): + """Set (or update) the queue length for a replica ID.""" + self._cache[replica_id] = ReplicaQueueLengthCacheEntry( + queue_len, self._get_curr_time_s() + ) + + def invalidate_key(self, replica_id: ReplicaID): + self._cache.pop(replica_id, None) + + def remove_inactive_replicas(self, *, active_replica_ids: Set[ReplicaID]): + """Removes entries for all replica IDs not in the provided active set.""" + # NOTE: the size of the cache dictionary changes during this loop. + for replica_id in list(self._cache.keys()): + if replica_id not in active_replica_ids: + self._cache.pop(replica_id) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/pow_2_router.py b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/pow_2_router.py new file mode 100644 index 0000000000000000000000000000000000000000..c929e3204a345455fe76509146a89e97ac7da456 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/pow_2_router.py @@ -0,0 +1,89 @@ +import logging +import random +from typing import ( + List, + Optional, +) + +from ray.serve._private.constants import ( + SERVE_LOGGER_NAME, +) +from ray.serve._private.request_router.common import ( + PendingRequest, +) +from ray.serve._private.request_router.replica_wrapper import ( + RunningReplica, +) +from ray.serve._private.request_router.request_router import ( + FIFOMixin, + LocalityMixin, + MultiplexMixin, + RequestRouter, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class PowerOfTwoChoicesRequestRouter( + FIFOMixin, LocalityMixin, MultiplexMixin, RequestRouter +): + """Chooses a replica for each request using the "power of two choices" procedure. + + Requests are routed in FIFO order. + + When a request comes in, two candidate replicas are chosen randomly. Each replica + is sent a control message to fetch its queue length. + + The replica responds with two items: (queue_len, accepted). Only replicas that + accept the request are considered; between those, the one with the lower queue + length is chosen. + + In the case when neither replica accepts the request (e.g., their queues are full), + the procedure is repeated with backoff. This backoff repeats indefinitely until a + replica is chosen, so the caller should use timeouts and cancellation to avoid + hangs. + + Each request being routed may spawn an independent task that runs the routing + procedure concurrently. This task will not necessarily satisfy the request that + started it (in order to maintain the FIFO order). The total number of tasks is + capped at (2 * num_replicas). + """ + + async def choose_replicas( + self, + candidate_replicas: List[RunningReplica], + pending_request: Optional[PendingRequest] = None, + ) -> List[List[RunningReplica]]: + """One iteration of the power of two choices procedure that chooses + (at most) two random available replicas. + + For multiplexing, this will first attempt to choose replicas that have the + requested model ID for a configured timeout. If no replicas with the matching + model ID are available after that timeout, it will fall back to the regular + procedure. + """ + if ( + pending_request is not None + and pending_request.metadata.multiplexed_model_id + ): + # Get candidates for multiplexed model ID. + candidate_replica_ids = self.apply_multiplex_routing( + pending_request=pending_request, + ) + else: + # Get candidates for locality preference. + candidate_replica_ids = self.apply_locality_routing( + pending_request=pending_request, + ) + + if not candidate_replica_ids: + return [] + + chosen_ids = random.sample( + list(candidate_replica_ids), + k=min(2, len(candidate_replica_ids)), + ) + replica_id_to_replica_map = { + replica.replica_id: replica for replica in candidate_replicas + } + return [[replica_id_to_replica_map[chosen_id] for chosen_id in chosen_ids]] diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/replica_wrapper.py b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/replica_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..af4fcbe05c7f33387d3f17afb2db940c01f23d76 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/replica_wrapper.py @@ -0,0 +1,212 @@ +import asyncio +import logging +import pickle +from abc import ABC, abstractmethod +from typing import Any, Dict, Optional, Set, Tuple, Union + +import ray +from ray import ObjectRef, ObjectRefGenerator +from ray.actor import ActorHandle +from ray.exceptions import TaskCancelledError +from ray.serve._private.common import ( + ReplicaID, + ReplicaQueueLengthInfo, + RunningReplicaInfo, +) +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.replica_result import ActorReplicaResult, ReplicaResult +from ray.serve._private.request_router.common import PendingRequest +from ray.serve._private.utils import JavaActorHandleProxy +from ray.serve.generated.serve_pb2 import RequestMetadata as RequestMetadataProto +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class ReplicaWrapper(ABC): + """This is used to abstract away details of the transport layer + when communicating with the replica. + """ + + @abstractmethod + def send_request_java(self, pr: PendingRequest) -> ReplicaResult: + """Send request to Java replica.""" + pass + + @abstractmethod + def send_request_python( + self, pr: PendingRequest, *, with_rejection: bool + ) -> Tuple[ReplicaResult, Optional[ReplicaQueueLengthInfo]]: + """Send request to Python replica. + + If sending request with rejection, the replica will yield a + system message (ReplicaQueueLengthInfo) before executing the + actual request. This can cause it to reject the request. The + result will *always* be a generator, so for non-streaming + requests it's up to the caller to resolve it to its first (and + only) ObjectRef. + """ + pass + + +class ActorReplicaWrapper(ReplicaWrapper): + def __init__(self, actor_handle): + self._actor_handle = actor_handle + + def send_request_java(self, pr: PendingRequest) -> ActorReplicaResult: + """Send the request to a Java replica. + Does not currently support streaming. + """ + if pr.metadata.is_streaming: + raise RuntimeError("Streaming not supported for Java.") + + if len(pr.args) != 1: + raise ValueError("Java handle calls only support a single argument.") + + return ActorReplicaResult( + self._actor_handle.handle_request.remote( + RequestMetadataProto( + request_id=pr.metadata.request_id, + # Default call method in java is "call," not "__call__" like Python. + call_method="call" + if pr.metadata.call_method == "__call__" + else pr.metadata.call_method, + ).SerializeToString(), + pr.args, + ), + pr.metadata, + ) + + def _send_request_python( + self, pr: PendingRequest, *, with_rejection: bool + ) -> Union[ObjectRef, ObjectRefGenerator]: + """Send the request to a Python replica.""" + if with_rejection: + # Call a separate handler that may reject the request. + # This handler is *always* a streaming call and the first message will + # be a system message that accepts or rejects. + method = self._actor_handle.handle_request_with_rejection.options( + num_returns="streaming" + ) + elif pr.metadata.is_streaming: + method = self._actor_handle.handle_request_streaming.options( + num_returns="streaming" + ) + else: + method = self._actor_handle.handle_request + + return method.remote(pickle.dumps(pr.metadata), *pr.args, **pr.kwargs) + + async def send_request_python( + self, pr: PendingRequest, with_rejection: bool + ) -> Tuple[ActorReplicaResult, Optional[ReplicaQueueLengthInfo]]: + obj_ref_gen = self._send_request_python(pr, with_rejection=with_rejection) + + if not with_rejection: + return ActorReplicaResult(obj_ref_gen, pr.metadata), None + + try: + first_ref = await obj_ref_gen.__anext__() + queue_len_info: ReplicaQueueLengthInfo = pickle.loads(await first_ref) + return ActorReplicaResult(obj_ref_gen, pr.metadata), queue_len_info + except asyncio.CancelledError as e: + # HTTP client disconnected or request was explicitly canceled. + logger.info( + "Cancelling request that has already been assigned to a replica." + ) + ray.cancel(obj_ref_gen) + raise e from None + except TaskCancelledError: + raise asyncio.CancelledError() + + +@PublicAPI(stability="alpha") +class RunningReplica: + """Contains info on a running replica. + Also defines the interface for a request router to talk to a replica. + """ + + def __init__(self, replica_info: RunningReplicaInfo): + self._replica_info = replica_info + self._multiplexed_model_ids = set(replica_info.multiplexed_model_ids) + + if replica_info.is_cross_language: + self._actor_handle = JavaActorHandleProxy(replica_info.actor_handle) + else: + self._actor_handle = replica_info.actor_handle + + @property + def replica_id(self) -> ReplicaID: + """ID of this replica.""" + return self._replica_info.replica_id + + @property + def actor_id(self) -> ray.ActorID: + """Actor ID of this replica.""" + return self._actor_handle._actor_id + + @property + def node_id(self) -> str: + """Node ID of the node this replica is running on.""" + return self._replica_info.node_id + + @property + def availability_zone(self) -> Optional[str]: + """Availability zone of the node this replica is running on.""" + return self._replica_info.availability_zone + + @property + def multiplexed_model_ids(self) -> Set[str]: + """Set of model IDs on this replica.""" + return self._multiplexed_model_ids + + @property + def routing_stats(self) -> Dict[str, Any]: + """Dictionary of routing stats.""" + return self._replica_info.routing_stats + + @property + def max_ongoing_requests(self) -> int: + """Max concurrent requests that can be sent to this replica.""" + return self._replica_info.max_ongoing_requests + + @property + def is_cross_language(self) -> bool: + """Whether this replica is cross-language (Java).""" + return self._replica_info.is_cross_language + + def _get_replica_wrapper(self, pr: PendingRequest) -> ReplicaWrapper: + return ActorReplicaWrapper(self._actor_handle) + + def push_proxy_handle(self, handle: ActorHandle): + """When on proxy, push proxy's self handle to replica""" + self._actor_handle.push_proxy_handle.remote(handle) + + async def get_queue_len(self, *, deadline_s: float) -> int: + """Returns current queue len for the replica. + `deadline_s` is passed to verify backoff for testing. + """ + # NOTE(edoakes): the `get_num_ongoing_requests` method name is shared by + # the Python and Java replica implementations. If you change it, you need to + # change both (or introduce a branch here). + obj_ref = self._actor_handle.get_num_ongoing_requests.remote() + try: + return await obj_ref + except asyncio.CancelledError: + ray.cancel(obj_ref) + raise + + async def send_request( + self, pr: PendingRequest, with_rejection: bool + ) -> Tuple[Optional[ReplicaResult], Optional[ReplicaQueueLengthInfo]]: + """Send request to this replica.""" + wrapper = self._get_replica_wrapper(pr) + if self._replica_info.is_cross_language: + assert not with_rejection, "Request rejection not supported for Java." + return wrapper.send_request_java(pr), None + + result, queue_len_info = await wrapper.send_request_python(pr, with_rejection) + if queue_len_info and not queue_len_info.accepted: + return None, queue_len_info + + return result, queue_len_info diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/request_router.py b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/request_router.py new file mode 100644 index 0000000000000000000000000000000000000000..ebfc2bc6a1814a43d48e38de4795b8ee65048853 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/request_router/request_router.py @@ -0,0 +1,1140 @@ +import asyncio +import enum +import logging +import math +import random +import time +from abc import ABC, abstractmethod +from collections import defaultdict, deque +from typing import ( + AsyncGenerator, + Callable, + DefaultDict, + Deque, + Dict, + List, + Optional, + Set, + Tuple, +) + +from ray.actor import ActorHandle +from ray.exceptions import ActorDiedError, ActorUnavailableError +from ray.serve._private.common import ( + DeploymentHandleSource, + DeploymentID, + ReplicaID, + ReplicaQueueLengthInfo, + RequestMetadata, + RunningReplicaInfo, +) +from ray.serve._private.constants import ( + RAY_SERVE_MAX_QUEUE_LENGTH_RESPONSE_DEADLINE_S, + RAY_SERVE_MULTIPLEXED_MODEL_ID_MATCHING_TIMEOUT_S, + RAY_SERVE_QUEUE_LENGTH_RESPONSE_DEADLINE_S, + SERVE_LOGGER_NAME, +) +from ray.serve._private.replica_result import ReplicaResult +from ray.serve._private.request_router.common import ( + PendingRequest, + ReplicaQueueLengthCache, +) +from ray.serve._private.request_router.replica_wrapper import RunningReplica +from ray.util import metrics +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class LocalityScope(str, enum.Enum): + NODE = "NODE" + AVAILABILITY_ZONE = "AVAILABILITY_ZONE" + + +@PublicAPI(stability="alpha") +class LocalityMixin: + """Mixin for locality routing. + + This mixin is used to route requests to replicas that are colocated + with the handle. It adds necessary attributes and methods to keep track of + locality scopes and offer the helpers to apply locality routing and + rank replicas based on locality. + """ + + def __init__( + self, + self_node_id: Optional[str] = None, + prefer_local_node_routing: bool = False, + prefer_local_az_routing: bool = False, + self_availability_zone: Optional[str] = None, + *args, + **kwargs, + ): + super().__init__(*args, **kwargs) + self._self_node_id = self_node_id + self._prefer_local_node_routing = prefer_local_node_routing + self._prefer_local_az_routing = prefer_local_az_routing + self._self_availability_zone = self_availability_zone + + # Colocated replicas (e.g. wrt node, AZ) + self._colocated_replica_ids: DefaultDict[ + LocalityScope, Set[ReplicaID] + ] = defaultdict(set) + self._replica_id_set: Set[ReplicaID] = set() + + def _discard_colocated_replica_ids_on_replica_actor_died( + self, replica_id: ReplicaID + ): + """Remove the replica ID from the colocated replica IDs. + This is called when a replica actor dies. + """ + for id_set in self._colocated_replica_ids.values(): + id_set.discard(replica_id) + + def _update_colocated_replica_ids_with_replicas( + self, replicas: List[RunningReplica] + ): + """Update the colocated replica IDs based on the replicas. + This is called when the replicas are updated. + """ + new_colocated_replica_ids = defaultdict(set) + + for r in replicas: + if self._self_node_id is not None and r.node_id == self._self_node_id: + new_colocated_replica_ids[LocalityScope.NODE].add(r.replica_id) + if ( + self._self_availability_zone is not None + and r.availability_zone == self._self_availability_zone + ): + new_colocated_replica_ids[LocalityScope.AVAILABILITY_ZONE].add( + r.replica_id + ) + + self._colocated_replica_ids = new_colocated_replica_ids + + def apply_locality_routing( + self, + pending_request: Optional[PendingRequest] = None, + ) -> Set[ReplicaID]: + """Apply locality routing to the pending request. + + When the reqeust is None, return all replicas. Each call will try to + route the request to replicas in the priority of first on the + same node, then in the same availability zone, and finally all + replicas. + + Args: + pending_request: The pending request to be routed. + Returns: + A set of replica IDs that are candidates based on + the locality policy. + """ + + if not pending_request: + return self._replica_id_set + + if ( + self._prefer_local_node_routing + and not pending_request.routing_context.tried_same_node + and len(self._colocated_replica_ids[LocalityScope.NODE]) > 0 + ): + # Attempt to route requests to replicas on the + # same node at most once + candidate_replica_ids = self._colocated_replica_ids[LocalityScope.NODE] + pending_request.routing_context.tried_same_node = True + pending_request.routing_context.should_backoff = False + elif ( + self._prefer_local_az_routing + and not pending_request.routing_context.tried_same_az + and len(self._colocated_replica_ids[LocalityScope.AVAILABILITY_ZONE]) > 0 + ): + # Attempt to route requests to replicas in the same + # AZ at most once + candidate_replica_ids = self._colocated_replica_ids[ + LocalityScope.AVAILABILITY_ZONE + ] + pending_request.routing_context.tried_same_az = True + pending_request.routing_context.should_backoff = False + else: + # On subsequent iterations or when there are no replicas on the same + # node or AZ, consider all available replicas. + candidate_replica_ids = self._replica_id_set + pending_request.routing_context.should_backoff = True + return candidate_replica_ids + + def rank_replicas_via_locality( + self, + replicas: List[RunningReplica], + ) -> List[List[RunningReplica]]: + """Rank the replicas based on the locality preference. + Rank 0 is the list of replicas that are on the same node. + Rank 1 is the list of replicas that are on the same availability zone. + Rank 2 is the list of all other replicas. + """ + ranked_replicas = [[] for _ in range(3)] + for replica in replicas: + if replica.replica_id in self._colocated_replica_ids[LocalityScope.NODE]: + ranked_replicas[0].append(replica) + elif ( + replica.replica_id + in self._colocated_replica_ids[LocalityScope.AVAILABILITY_ZONE] + ): + ranked_replicas[1].append(replica) + else: + ranked_replicas[2].append(replica) + return ranked_replicas + + +@PublicAPI(stability="alpha") +class MultiplexMixin: + """Mixin for multiplex routing. + + This mixin is used to route requests to replicas that are multiplexed. + It adds necessary attributes and methods to keep track of multiplexed + model IDs and offer the helpers to apply multiplex routing and rank + replicas based on multiplexed model IDs. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._multiplexed_model_id_to_replica_ids: DefaultDict[ + str, Set[ReplicaID] + ] = defaultdict(set) + + # When there is no match for a multiplexed model id, we will try to fall back + # to all replicas immediately. This set is used to make sure we only fall back + # once for concurrent requests for the same model id. + # Whenever there is a match, we will remove the model id from this set. + self._multiplexed_model_id_fallback_match: Set[str] = set() + self._replica_id_set: Set[ReplicaID] = set() + self._replicas: Dict[ReplicaID, RunningReplica] = {} + + def _get_pending_request_matching_multiplexed_model_id( + self, + request_metadata: Optional[RequestMetadata] = None, + ) -> Optional[PendingRequest]: + """Matching pending request based on the request metadata.""" + if request_metadata is None or not request_metadata.multiplexed_model_id: + return None + + for pr in self._pending_requests_to_fulfill: + if ( + not pr.future.done() + and pr.metadata.multiplexed_model_id + == request_metadata.multiplexed_model_id + ): + return pr + + def _update_multiplexed_model_ids_with_replicas( + self, replicas: List[RunningReplica] + ): + """Update the multiplexed model IDs based on the replicas. + + This should be called when the replicas are updated. + """ + new_multiplexed_model_id_to_replica_ids = defaultdict(set) + + for r in replicas: + for model_id in r.multiplexed_model_ids: + new_multiplexed_model_id_to_replica_ids[model_id].add(r.replica_id) + + self._multiplexed_model_id_to_replica_ids = ( + new_multiplexed_model_id_to_replica_ids + ) + + def _get_replica_ids_with_fewest_multiplexed_models(self) -> Set[str]: + """Get the set of replicas that have the fewest multiplexed models loaded.""" + candidates = set() + sorted_replicas = sorted( + self._replicas.values(), key=lambda x: len(x.multiplexed_model_ids) + ) + least_num_multiplexed_model_ids = math.inf + for replica in sorted_replicas: + if len(replica.multiplexed_model_ids) <= least_num_multiplexed_model_ids: + candidates.add(replica.replica_id) + least_num_multiplexed_model_ids = len(replica.multiplexed_model_ids) + else: + break + + return candidates + + @property + def _multiplexed_matching_timeout(self) -> float: + return random.uniform( + RAY_SERVE_MULTIPLEXED_MODEL_ID_MATCHING_TIMEOUT_S, + RAY_SERVE_MULTIPLEXED_MODEL_ID_MATCHING_TIMEOUT_S * 2, + ) + + def apply_multiplex_routing( + self, + pending_request: Optional[PendingRequest] = None, + ) -> Set[ReplicaID]: + """Apply multiplex routing to the pending request. + + When the request is None, return all replicas. Each call will try to + route the request to the replicas that have the multiplexed model ID + to the hierarchy of first the replicas with the multiplexed model ID, + then the replicas with the fewest multiplexed models, and finally all + replicas. + + Args: + pending_request: The pending request to be routed based on + multiplexed model policy. + + Returns: + A set of replica IDs that are candidates for the existing + routing call. + """ + if not pending_request: + return self._replica_id_set + + if not pending_request.routing_context.multiplexed_start_matching_time: + pending_request.routing_context.multiplexed_start_matching_time = ( + time.time() + ) + + multiplexed_start_matching_time = ( + pending_request.routing_context.multiplexed_start_matching_time + ) + multiplexed_model_id = pending_request.metadata.multiplexed_model_id + if ( + time.time() - multiplexed_start_matching_time + < self._multiplexed_matching_timeout + ): + candidate_replica_ids = self._multiplexed_model_id_to_replica_ids.get( + multiplexed_model_id, None + ) + if ( + not candidate_replica_ids + and multiplexed_model_id + not in self._multiplexed_model_id_fallback_match + ) or pending_request.routing_context.tried_first_multiplexed_models: + # When there is no match for a multiplexed model id + # or when the replica(s) with the matching model id is busy, + # first try to fall back to replicas with the fewest models. + candidate_replica_ids = ( + self._get_replica_ids_with_fewest_multiplexed_models() + ) + self._multiplexed_model_id_fallback_match.add(multiplexed_model_id) + elif candidate_replica_ids: + self._multiplexed_model_id_fallback_match.discard(multiplexed_model_id) + pending_request.routing_context.tried_first_multiplexed_models = True + elif not pending_request.routing_context.tried_fewest_multiplexed_models: + # After the `_multiplexed_matching_timeout` is up, first try + # routing to replicas that have the fewest models loaded. + # We only try this once to avoid deterministically retrying on + # the same replicas repeatedly. + candidate_replica_ids = ( + self._get_replica_ids_with_fewest_multiplexed_models() + ) + pending_request.routing_context.tried_fewest_multiplexed_models = True + else: + # If the timeout is up, and we've already tried the candidates + # with the fewest models loaded, fall back to all replicas. + candidate_replica_ids = self._replica_id_set + + pending_request.routing_context.should_backoff = True + return candidate_replica_ids + + def rank_replicas_via_multiplex( + self, + replicas: List[RunningReplica], + multiplexed_model_id: str, + ) -> List[List[RunningReplica]]: + """Rank the replicas based on the multiplexed model ID. + Rank 0 is the list of replicas that have the multiplexed model ID. + Rank 1 is the list of replicas that have the fewest multiplexed models. + Rank 2 is the list of all other replicas. + """ + replica_ids_with_multiplexed_model = ( + self._multiplexed_model_id_to_replica_ids.get(multiplexed_model_id, set()) + ) + replica_ids_with_fewest_multiplexed_models = ( + self._get_replica_ids_with_fewest_multiplexed_models() + ) + + ranked_replicas = [[] for _ in range(3)] + for replica in replicas: + if replica.replica_id in replica_ids_with_multiplexed_model: + ranked_replicas[0].append(replica) + elif replica.replica_id in replica_ids_with_fewest_multiplexed_models: + ranked_replicas[1].append(replica) + else: + ranked_replicas[2].append(replica) + return ranked_replicas + + +@PublicAPI(stability="alpha") +class FIFOMixin: + """Mixin for FIFO routing. + + This mixin is used to route requests in FIFO order, optionally prioritizing + requests with matching metadata. RequestRouter's default behavior is + out-of-order routing and match exactly the internal request id of + the request. This mixin doesn't provide any helper methods. By including it + in your custom implementation of RequestRouter, it will override the + reqeust matching algorithm to match based on the request metadata + multiplexed model id, if available, and then fall back to the first pending + request in the queue. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def _get_pending_request_matching_metadata( + self, + request_metadata: Optional[RequestMetadata] = None, + ) -> Optional[PendingRequest]: + """Matching pending request based on the request metadata. + + If multiplex mixin is used, this will be using the multiplexed model + id for the matching. Else, it will return none as no matching pending request. + """ + if hasattr(self, "_get_pending_request_matching_multiplexed_model_id"): + return self._get_pending_request_matching_multiplexed_model_id( + request_metadata + ) + + return None + + def _fulfill_next_pending_request( + self, + replica: RunningReplica, + request_metadata: Optional[RequestMetadata] = None, + ): + """Assign the replica to the next pending request in FIFO order. + + If a pending request has been cancelled, it will be popped from the queue + and not assigned. + """ + # First try to match a pending request based on the request metadata. + matched_pending_request = self._get_pending_request_matching_metadata( + request_metadata + ) + if matched_pending_request is not None: + matched_pending_request.future.set_result(replica) + self._pending_requests_to_fulfill.remove(matched_pending_request) + return + + # If no pending request matches the request metadata, fulfill the next in the + # queue in FIFO order, passing over futures that have been cancelled. + while len(self._pending_requests_to_fulfill) > 0: + pr = self._pending_requests_to_fulfill.popleft() + if not pr.future.done(): + pr.future.set_result(replica) + break + + +@PublicAPI(stability="alpha") +class RequestRouter(ABC): + """Abstract interface for a request router (how the router calls it).""" + + backoff_sequence_s = [0, 0.05, 0.1, 0.15, 0.2, 0.5, 1.0] + """ + The sequence of backoff timeouts to use when all replicas' queues are full. + The last item in the list is the max timeout and will be used repeatedly. + """ + + # Deadline for replicas to respond with their queue length. If the response isn't + # received within this deadline, the replica will not be considered. + # If this deadline is repeatedly missed, it will be exponentially increased up to + # the maximum configured here. + queue_len_response_deadline_s = RAY_SERVE_QUEUE_LENGTH_RESPONSE_DEADLINE_S + """Deadline for receiving queue length info from replicas.""" + + max_queue_len_response_deadline_s = RAY_SERVE_MAX_QUEUE_LENGTH_RESPONSE_DEADLINE_S + """Maximum deadline for receiving queue length info from replicas.""" + + max_num_routing_tasks_cap = 50 + """ + Hard limit on the maximum number of routing tasks to run. Having too many of + these tasks can cause stability issue due to too much load on the local process + and many too requests in flight to fetch replicas' queue lengths. + """ + + def __init__( + self, + deployment_id: DeploymentID, + handle_source: DeploymentHandleSource, + self_actor_id: Optional[str] = None, + self_actor_handle: Optional[ActorHandle] = None, + use_replica_queue_len_cache: bool = False, + get_curr_time_s: Optional[Callable[[], float]] = None, + create_replica_wrapper_func: Optional[ + Callable[[RunningReplicaInfo], RunningReplica] + ] = None, + *args, + **kwargs, + ): + self._deployment_id = deployment_id + self._handle_source = handle_source + self._self_actor_handle = self_actor_handle + self._use_replica_queue_len_cache = use_replica_queue_len_cache + self._create_replica_wrapper_func = create_replica_wrapper_func + + # Current replicas available to be routed. + # Updated via `update_replicas`. + self._replica_id_set: Set[ReplicaID] = set() + self._replicas: Dict[ReplicaID, RunningReplica] = {} + self._replica_queue_len_cache = ReplicaQueueLengthCache( + get_curr_time_s=get_curr_time_s, + ) + + # NOTE(edoakes): Python 3.10 removed the `loop` parameter to `asyncio.Event`. + # Now, the `asyncio.Event` will call `get_running_loop` in its constructor to + # determine the loop to attach to. This class can be constructed for the handle + # from a different loop than it uses for routing, so we need to construct it + # lazily to avoid an error due to the event being attached to the wrong loop. + self._lazily_constructed_replicas_updated_event: Optional[asyncio.Event] = None + self._lazily_fetched_loop: Optional[asyncio.AbstractEventLoop] = None + + # Tasks running the routing loop. The size of this set may vary over time + # as new tasks will be routed when a request comes in or new replicas are + # added, but it will not exceed self.max_num_routing_tasks. + self._routing_tasks: Set[asyncio.Task] = set() + + # We keep two separate queues of pending requests: + # - self._pending_requests_to_fulfill is a queue that will be used to fulfill + # requests (potentially out of order) by routing tasks once they've acquired a replica. + # - self.routing is a queue that is used for tasks to + # best-effort grab the metadata of requests waiting to be fulfilled. This is + # currently used for routing tasks to know which multiplexed model IDs they + # should be trying to get replicas for. + self._pending_requests_to_fulfill: Deque[PendingRequest] = deque() + self._pending_requests_to_route: Deque[PendingRequest] = deque() + + # Prepare request router metrics. + self.num_routing_tasks_gauge = metrics.Gauge( + "serve_num_scheduling_tasks", + description="The number of request routing tasks in the router.", + tag_keys=("app", "deployment", "actor_id"), + ).set_default_tags( + { + "app": self._deployment_id.app_name, + "deployment": self._deployment_id.name, + "actor_id": self_actor_id if self_actor_id else "", + } + ) + self.num_routing_tasks_gauge.set(0) + + self.num_routing_tasks_in_backoff = 0 + self.num_routing_tasks_in_backoff_gauge = metrics.Gauge( + "serve_num_scheduling_tasks_in_backoff", + description=( + "The number of request routing tasks in the router " + "that are undergoing backoff." + ), + tag_keys=("app", "deployment", "actor_id"), + ).set_default_tags( + { + "app": self._deployment_id.app_name, + "deployment": self._deployment_id.name, + "actor_id": self_actor_id if self_actor_id else "", + } + ) + self.num_routing_tasks_in_backoff_gauge.set(self.num_routing_tasks_in_backoff) + + def initialize_state(self, **kwargs): + """ + Initialize the state of the request router. Called by the Ray Serve framework with the + contents of `RequestRouter.request_router_kwargs`. + """ + pass + + @property + def _event_loop(self) -> asyncio.AbstractEventLoop: + if self._lazily_fetched_loop is None: + self._lazily_fetched_loop = asyncio.get_running_loop() + + return self._lazily_fetched_loop + + @property + def _replicas_updated_event(self) -> asyncio.Event: + """Lazily construct `asyncio.Event`. + + See comment for self._lazily_constructed_replicas_updated_event. + """ + if self._lazily_constructed_replicas_updated_event is None: + self._lazily_constructed_replicas_updated_event = asyncio.Event() + + return self._lazily_constructed_replicas_updated_event + + @property + def num_pending_requests(self) -> int: + """Current number of requests pending assignment.""" + return len(self._pending_requests_to_fulfill) + + @property + def curr_num_routing_tasks(self) -> int: + """Current number of routing tasks running.""" + return len(self._routing_tasks) + + @property + def max_num_routing_tasks(self) -> int: + """Max number of routing tasks to run at any time.""" + return min(self.max_num_routing_tasks_cap, 2 * len(self._replicas)) + + @property + def target_num_routing_tasks(self) -> int: + """Target number of routing tasks to be running based on pending requests. + + This will never exceed `self.max_num_routing_tasks`. + """ + return min(self.num_pending_requests, self.max_num_routing_tasks) + + @property + def curr_replicas(self) -> Dict[ReplicaID, RunningReplica]: + """Current replicas available to be routed.""" + return self._replicas + + @property + def app_name(self) -> str: + """Name of the app this router is serving.""" + return self._deployment_id.app_name + + @property + def replica_queue_len_cache(self) -> ReplicaQueueLengthCache: + """Get the replica queue length cache.""" + return self._replica_queue_len_cache + + def create_replica_wrapper( + self, replica_info: RunningReplicaInfo + ) -> RunningReplica: + return self._create_replica_wrapper_func(replica_info) + + def on_replica_actor_died(self, replica_id: ReplicaID): + """Drop replica from replica set so it's not considered for future requests.""" + self._replicas.pop(replica_id, None) + self._replica_id_set.discard(replica_id) + if hasattr(self, "_discard_colocated_replica_ids_on_replica_actor_died"): + self._discard_colocated_replica_ids_on_replica_actor_died(replica_id) + + def on_replica_actor_unavailable(self, replica_id: ReplicaID): + """Invalidate cache entry so active probing is required for the next request.""" + self._replica_queue_len_cache.invalidate_key(replica_id) + + def on_new_queue_len_info( + self, replica_id: ReplicaID, queue_len_info: ReplicaQueueLengthInfo + ): + """Update queue length cache with new info received from replica.""" + if self._use_replica_queue_len_cache: + self._replica_queue_len_cache.update( + replica_id, queue_len_info.num_ongoing_requests + ) + + def update_replicas(self, replicas: List[RunningReplica]): + """Update the set of available replicas to be considered for routing. + + When the set of replicas changes, we may spawn additional routing tasks + if there are pending requests. + """ + new_replicas = {} + new_replica_id_set = set() + if hasattr(self, "_update_colocated_replica_ids_with_replicas"): + self._update_colocated_replica_ids_with_replicas(replicas) + if hasattr(self, "_update_multiplexed_model_ids_with_replicas"): + self._update_multiplexed_model_ids_with_replicas(replicas) + + for r in replicas: + # If on the proxy, replica needs to call back into the proxy with + # `receive_asgi_messages` which can be blocked when GCS is down. + # To prevent that from happening, push proxy handle eagerly + if ( + self._handle_source == DeploymentHandleSource.PROXY + and r.replica_id not in self._replicas + ): + r.push_proxy_handle(self._self_actor_handle) + + new_replicas[r.replica_id] = r + new_replica_id_set.add(r.replica_id) + + if self._replica_id_set != new_replica_id_set: + replica_id_set_strs = {r.unique_id for r in new_replica_id_set} + logger.info( + f"Got updated replicas for {self._deployment_id}: " + f"{replica_id_set_strs}.", + extra={"log_to_stderr": False}, + ) + + # Get list of new replicas + new_ids = new_replica_id_set - self._replica_id_set + replicas_to_ping = [new_replicas.get(id) for id in new_ids] + + self._replicas = new_replicas + self._replica_id_set = new_replica_id_set + self._replica_queue_len_cache.remove_inactive_replicas( + active_replica_ids=new_replica_id_set + ) + # Populate cache for new replicas + self._event_loop.create_task(self._probe_queue_lens(replicas_to_ping, 0)) + self._replicas_updated_event.set() + self._maybe_start_routing_tasks() + + async def _probe_queue_lens( + self, + replicas: List[RunningReplica], + backoff_index: int, + ) -> List[Tuple[RunningReplica, Optional[int]]]: + """Actively probe the queue length from each of the replicas. + + Sends an RPC to each replica to fetch its queue length, with a response deadline + that increases exponentially in backoff. + + Returns a list of queue lengths in the same order as the replicas passed in. + Replicas whose RPCs fail or don't respond within the deadline will have a queue + length of `None`. Replicas that return a `RayActorError` will be removed from + future consideration for requests. + + This method also updates the local cache of replica queue lengths according to + the responses. + """ + result: List[Tuple[RunningReplica, Optional[int]]] = [] + if len(replicas) == 0: + return result + + # Ensure the max deadline is always >= the initial deadline. + max_queue_len_response_deadline_s = max( + self.queue_len_response_deadline_s, + self.max_queue_len_response_deadline_s, + ) + + try: + queue_len_response_deadline_s = min( + self.queue_len_response_deadline_s * (2**backoff_index), + max_queue_len_response_deadline_s, + ) + except OverflowError: + # self.queue_len_response_deadline_s * (2**backoff_index) + # can overflow if backoff_index gets sufficiently large (e.g. + # 1024 when queue_len_response_deadline_s is 0.1). + queue_len_response_deadline_s = max_queue_len_response_deadline_s + + get_queue_len_tasks = [] + for r in replicas: + t = self._event_loop.create_task( + r.get_queue_len(deadline_s=queue_len_response_deadline_s) + ) + t.replica = r + get_queue_len_tasks.append(t) + + done, pending = await asyncio.wait( + get_queue_len_tasks, + timeout=queue_len_response_deadline_s, + return_when=asyncio.ALL_COMPLETED, + ) + for t in pending: + replica = t.replica + result.append((replica, None)) + t.cancel() + logger.warning( + f"Failed to get queue length from {replica.replica_id} " + f"within {queue_len_response_deadline_s}s. If this happens repeatedly " + "it's likely caused by high network latency in the cluster. You can " + "configure the deadline using the " + "`RAY_SERVE_QUEUE_LENGTH_RESPONSE_DEADLINE_S` environment variable." + ) + + for t in done: + replica = t.replica + if t.exception() is not None: + result.append((replica, None)) + msg = ( + "Failed to fetch queue length for " + f"{replica.replica_id}: '{t.exception()}'" + ) + # If we get an ActorDiedError, the replica actor has died. This + # is not recoverable (the controller will start a new replica in its + # place), so we should no longer consider it for requests. + # We do not catch RayActorError here because that error can be + # raised even when a replica is temporarily unavailable. + # See https://github.com/ray-project/ray/issues/44185 for details. + if isinstance(t.exception(), ActorDiedError): + self.on_replica_actor_died(replica.replica_id) + msg += " This replica will no longer be considered for requests." + # Replica is temporarily unavailable because of network issues, or + # replica has died but GCS is down so ActorUnavailableError will + # be raised until the GCS recovers. For the time being, invalidate + # the cache entry so that we don't try to send requests to this + # replica without actively probing. + elif isinstance(t.exception(), ActorUnavailableError): + self.on_replica_actor_unavailable(replica.replica_id) + msg = ( + "Failed to fetch queue length for " + f"{replica.replica_id}. Replica is temporarily " + "unavailable." + ) + + logger.warning(msg) + else: + queue_len = t.result() + result.append((replica, queue_len)) + self._replica_queue_len_cache.update(replica.replica_id, queue_len) + + assert len(result) == len(replicas) + return result + + async def _select_from_candidate_replicas( + self, + candidates: List[RunningReplica], + backoff_index: int, + ) -> Optional[RunningReplica]: + """Chooses the best replica from the list of candidates. + + If none of the replicas can be routed, returns `None`. + + The queue length for each replica is first looked up in the local cache. If not + present in the cache, the replica will be actively probed and the cache updated. + + Among replicas that respond within the deadline and don't have full queues, the + one with the lowest queue length is chosen. + """ + lowest_queue_len = math.inf + chosen_replica_id: Optional[str] = None + not_in_cache: List[RunningReplica] = [] + if self._use_replica_queue_len_cache: + # Populate available queue lens from the cache. + for r in candidates: + queue_len = self._replica_queue_len_cache.get(r.replica_id) + # Include replicas whose queues are full as not in the cache so we will + # actively probe them. Otherwise we may end up in "deadlock" until their + # cache entries expire. + if queue_len is None or queue_len >= r.max_ongoing_requests: + not_in_cache.append(r) + elif queue_len < lowest_queue_len: + lowest_queue_len = queue_len + chosen_replica_id = r.replica_id + else: + not_in_cache = candidates + + # If there is a valid replica to route based on the information in the + # cache, route it. Else fall back to actively probing. + if chosen_replica_id is None: + for r, queue_len in await self._probe_queue_lens( + not_in_cache, + backoff_index, + ): + if queue_len is None: + # None is returned if we failed to get the queue len. + continue + + if queue_len < r.max_ongoing_requests and queue_len < lowest_queue_len: + lowest_queue_len = queue_len + chosen_replica_id = r.replica_id + elif len(not_in_cache) > 0: + # If there are replicas without a valid cache entry, probe them in the + # background to populate the cache. + self._event_loop.create_task( + self._probe_queue_lens(not_in_cache, backoff_index) + ) + + # `self._replicas` may have been updated since the candidates were chosen. + # In that case, return `None` so a new one is selected. + return self._replicas.get(chosen_replica_id, None) + + def _get_pending_request_matching_internal_request_id( + self, + request_metadata: Optional[RequestMetadata] = None, + ) -> Optional[PendingRequest]: + """Get the pending request that matches on the internal request id. + + If no request metadata is provided or no request is found that matches + the internal request ID, return None. + """ + if request_metadata is None: + return None + + for pr in self._pending_requests_to_fulfill: + if ( + not pr.future.done() + and pr.metadata.internal_request_id + == request_metadata.internal_request_id + ): + return pr + + return None + + def _fulfill_next_pending_request( + self, + replica: RunningReplica, + request_metadata: Optional[RequestMetadata] = None, + ): + """Assign the replica to the next pending request, potentially not in + order of when the request arrived. + + If a pending request has been cancelled, it will be popped from the queue + and not assigned. + """ + # Find the pending request that matches exactly. + matched_pending_request = ( + self._get_pending_request_matching_internal_request_id(request_metadata) + ) + if matched_pending_request is not None: + matched_pending_request.future.set_result(replica) + self._pending_requests_to_fulfill.remove(matched_pending_request) + return + + def _get_next_pending_request_to_route( + self, + ) -> Optional[PendingRequest]: + while len(self._pending_requests_to_route) > 0: + pr = self._pending_requests_to_route.popleft() + if not pr.future.done(): + return pr + + return None + + async def _choose_replicas_with_backoff( + self, + pending_request: Optional[PendingRequest] = None, + ) -> AsyncGenerator[List[RunningReplica], None]: + """Generator that repeatedly chooses available replicas. + In the first iteration, only replicas colocated on the same node as this router + will be considered. If those are occupied, the full set of replicas will be + considered on subsequent iterations. + After each iteration, there will be an increasing backoff sleep time (dictated + by `self.backoff_sequence_s`). The caller should exit the generator to reset the + backoff sleep time. + """ + entered_backoff = False + try: + backoff_index = 0 + + while True: + # If no replicas are available, wait until `update_replicas` is called. + while len(self._replicas) == 0: + logger.info( + "No replicas are currently available for " + f"{self._deployment_id}.", + extra={"log_to_stderr": False}, + ) + self._replicas_updated_event.clear() + await self._replicas_updated_event.wait() + logger.info( + f"New replicas are available for {self._deployment_id}, " + "attempting to route queued requests.", + extra={"log_to_stderr": False}, + ) + + replica_ranks = list(self._replicas.values()) + chosen_replicas: List[ + List[RunningReplica] + ] = await self.choose_replicas( + candidate_replicas=replica_ranks, + pending_request=pending_request, + ) + for replicas in chosen_replicas: + if replicas: + yield replicas + + # We have a slight unintended behavior when enabled locality routing + # for both node and AZ. The intention is to try same node first, + # then try same AZ if node fails, then try everything else until a + # replica is found. These sequence should only help to reduce the + # latency of the request. No backoff and sleep should be applied, until + # we have fall into the case trying on all available replicas. + if not pending_request.routing_context.should_backoff: + continue + + if not entered_backoff: + entered_backoff = True + self.num_routing_tasks_in_backoff += 1 + self.num_routing_tasks_in_backoff_gauge.set( + self.num_routing_tasks_in_backoff + ) + + await asyncio.sleep(self.backoff_sequence_s[backoff_index]) + backoff_index = min(backoff_index + 1, len(self.backoff_sequence_s) - 1) + finally: + if entered_backoff: + self.num_routing_tasks_in_backoff -= 1 + self.num_routing_tasks_in_backoff_gauge.set( + self.num_routing_tasks_in_backoff + ) + + async def _fulfill_pending_requests(self): + """Repeatedly tries to fulfill a pending request with an available replica. + + This is expected to be run inside a task in self._routing_tasks. + + When a replica is found, this method will exit if the number of routing tasks + has exceeded the target number. Else it will loop again to route another + replica. + """ + try: + while len(self._routing_tasks) <= self.target_num_routing_tasks: + start_time = time.time() + backoff_index = 0 + pending_request = self._get_next_pending_request_to_route() + request_metadata = pending_request.metadata if pending_request else None + async for candidates in self._choose_replicas_with_backoff( + pending_request + ): + # Clear out pending requests at the front of the + # queue that have been cancelled, then reevaluate + # if we need to continue this routing task. + while ( + len(self._pending_requests_to_fulfill) > 0 + and self._pending_requests_to_fulfill[0].future.done() + ): + self._pending_requests_to_fulfill.popleft() + + if len(self._routing_tasks) > self.target_num_routing_tasks: + break + + replica = await self._select_from_candidate_replicas( + candidates, backoff_index + ) + if replica is not None: + self._fulfill_next_pending_request(replica, request_metadata) + break + + backoff_index += 1 + if backoff_index >= 50 and backoff_index % 50 == 0: + routing_time_elapsed = time.time() - start_time + warning_log = ( + "Failed to route request after " + f"{backoff_index} attempts over " + f"{routing_time_elapsed:.2f}s. Retrying." + ) + if request_metadata is not None: + warning_log += ( + f" Request ID: {request_metadata.request_id}." + ) + if request_metadata.multiplexed_model_id: + warning_log += ( + " Multiplexed model ID: " + f"{request_metadata.multiplexed_model_id}." + ) + logger.warning(warning_log) + + except Exception: + logger.exception("Unexpected error in _fulfill_pending_requests.") + finally: + self._routing_tasks.remove(asyncio.current_task(loop=self._event_loop)) + self.num_routing_tasks_gauge.set(self.curr_num_routing_tasks) + + def _maybe_start_routing_tasks(self): + """Start routing tasks to fulfill pending requests if necessary. + + Starts tasks so that there is at least one task per pending request + (respecting the max number of routing tasks). + + In the common case, this will start a single task when a new request comes + in for routing. However, in cases where the number of available replicas + is updated or a task exits unexpectedly, we may need to start multiple. + """ + tasks_to_start = self.target_num_routing_tasks - self.curr_num_routing_tasks + for _ in range(tasks_to_start): + self._routing_tasks.add( + self._event_loop.create_task(self._fulfill_pending_requests()) + ) + if tasks_to_start > 0: + self.num_routing_tasks_gauge.set(self.curr_num_routing_tasks) + + async def _choose_replica_for_request( + self, pending_request: PendingRequest, *, is_retry: bool = False + ) -> RunningReplica: + """Chooses a replica to send the provided request to. + + Upon cancellation (by the caller), the future is cancelled and will be passed + over when a replica becomes available. + """ + try: + if not is_retry: + self._pending_requests_to_fulfill.append(pending_request) + self._pending_requests_to_route.append(pending_request) + else: + pending_request.reset_future() + index = 0 + for pr in self._pending_requests_to_fulfill: + if pending_request.created_at < pr.created_at: + break + + index += 1 + + self._pending_requests_to_fulfill.insert(index, pending_request) + + index = 0 + for pr in self._pending_requests_to_route: + if pending_request.created_at < pr.created_at: + break + + index += 1 + + self._pending_requests_to_route.insert(index, pending_request) + + self._maybe_start_routing_tasks() + replica = await pending_request.future + except asyncio.CancelledError as e: + pending_request.future.cancel() + + raise e from None + + return replica + + def _update_running_replicas(self, running_replicas: List[RunningReplicaInfo]): + """Compatibility shim for RunningReplicaInfo datatype.""" + return self.update_replicas( + [self.create_replica_wrapper(r) for r in running_replicas] + ) + + def select_available_replicas( + self, candidates: Optional[List[RunningReplica]] = None + ) -> List[RunningReplica]: + """Select available replicas from the list of candidates. + + This method is used to select replicas that are available to take more + requests based on the queue length cache. If the queue length is not + available in the cache, the replica is considered available. It does + not actively probe the replicas for their queue length. + + If input candidates is `None`, all replicas are considered. + """ + if candidates is None: + candidates = list(self._replicas.values()) + + available_replicas = [] + for r in candidates: + queue_len = self._replica_queue_len_cache.get(r.replica_id) + if queue_len is None or queue_len < r.max_ongoing_requests: + available_replicas.append(r) + + return available_replicas + + @abstractmethod + async def choose_replicas( + self, + candidate_replicas: List[RunningReplica], + pending_request: Optional[PendingRequest] = None, + ) -> List[List[RunningReplica]]: + """Chooses a subset of candidate replicas from available replicas. + + This is the main function each request router should implement to + decide which replica to send the request to. This is one iteration of + replica selection. + + Args: + candidate_replicas: A list of candidate replicas to be considered in the + policy. + pending_request: The request to be routed. This is used to + determine which replicas are eligible for routing. + + Returns: + A list of lists of replicas, where each inner list represents a + rank of replicas. The first rank is the most preferred and the last + rank is the least preferred. + """ + pass + + def on_request_routed( + self, + pending_request: PendingRequest, + replica_id: ReplicaID, + result: ReplicaResult, + ): + """Called when a request is routed to a replica. + + This is used as a callback to update the state of the request router + after a response is generated. + """ + pass diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/router.py b/venv/lib/python3.10/site-packages/ray/serve/_private/router.py new file mode 100644 index 0000000000000000000000000000000000000000..032fa9744958a0642bbea8303e2a098dc12f8866 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/router.py @@ -0,0 +1,940 @@ +import asyncio +import concurrent.futures +import logging +import threading +import time +import weakref +from abc import ABC, abstractmethod +from asyncio import AbstractEventLoop +from collections import defaultdict +from collections.abc import MutableMapping +from contextlib import contextmanager +from functools import lru_cache, partial +from typing import ( + Any, + Callable, + Coroutine, + DefaultDict, + Dict, + List, + Optional, + Tuple, + Union, +) + +import ray +from ray.actor import ActorHandle +from ray.exceptions import ActorDiedError, ActorUnavailableError, RayError +from ray.serve._private.common import ( + DeploymentHandleSource, + DeploymentID, + DeploymentTargetInfo, + ReplicaID, + RequestMetadata, + RunningReplicaInfo, +) +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import ( + HANDLE_METRIC_PUSH_INTERVAL_S, + RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE, + RAY_SERVE_HANDLE_AUTOSCALING_METRIC_RECORD_PERIOD_S, + RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING, + SERVE_LOGGER_NAME, +) +from ray.serve._private.long_poll import LongPollClient, LongPollNamespace +from ray.serve._private.metrics_utils import InMemoryMetricsStore, MetricsPusher +from ray.serve._private.replica_result import ReplicaResult +from ray.serve._private.request_router import PendingRequest, RequestRouter +from ray.serve._private.request_router.pow_2_router import ( + PowerOfTwoChoicesRequestRouter, +) +from ray.serve._private.request_router.replica_wrapper import RunningReplica +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + generate_request_id, + resolve_deployment_response, + run_coroutine_or_future_threadsafe, +) +from ray.serve.config import AutoscalingConfig +from ray.serve.exceptions import BackPressureError, DeploymentUnavailableError +from ray.util import metrics + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +QUEUED_REQUESTS_KEY = "queued" + + +class RouterMetricsManager: + """Manages metrics for the router.""" + + PUSH_METRICS_TO_CONTROLLER_TASK_NAME = "push_metrics_to_controller" + RECORD_METRICS_TASK_NAME = "record_metrics" + + def __init__( + self, + deployment_id: DeploymentID, + handle_id: str, + self_actor_id: str, + handle_source: DeploymentHandleSource, + controller_handle: ActorHandle, + router_requests_counter: metrics.Counter, + queued_requests_gauge: metrics.Gauge, + running_requests_gauge: metrics.Gauge, + ): + self._handle_id = handle_id + self._deployment_id = deployment_id + self._self_actor_id = self_actor_id + self._handle_source = handle_source + self._controller_handle = controller_handle + + # Exported metrics + self.num_router_requests = router_requests_counter + self.num_router_requests.set_default_tags( + { + "deployment": deployment_id.name, + "application": deployment_id.app_name, + "handle": self._handle_id, + "actor_id": self._self_actor_id, + } + ) + + self.num_queued_requests = 0 + self.num_queued_requests_gauge = queued_requests_gauge + self.num_queued_requests_gauge.set_default_tags( + { + "deployment": deployment_id.name, + "application": deployment_id.app_name, + "handle": self._handle_id, + "actor_id": self._self_actor_id, + } + ) + self.num_queued_requests_gauge.set(0) + + # Track queries sent to replicas for the autoscaling algorithm. + self.num_requests_sent_to_replicas: DefaultDict[ReplicaID, int] = defaultdict( + int + ) + self.num_running_requests_gauge = running_requests_gauge + self.num_running_requests_gauge.set_default_tags( + { + "deployment": deployment_id.name, + "application": deployment_id.app_name, + "handle": self._handle_id, + "actor_id": self._self_actor_id, + } + ) + # We use Ray object ref callbacks to update state when tracking + # number of requests running on replicas. The callbacks will be + # called from a C++ thread into the router's async event loop, + # so non-atomic read and write operations need to be guarded by + # this thread-safe lock. + self._queries_lock = threading.Lock() + # Regularly aggregate and push autoscaling metrics to controller + self.metrics_pusher = MetricsPusher() + self.metrics_store = InMemoryMetricsStore() + # The config for the deployment this router sends requests to will be broadcast + # by the controller. That means it is not available until we get the first + # update. This includes an optional autoscaling config. + self._deployment_config: Optional[DeploymentConfig] = None + # Track whether the metrics manager has been shutdown + self._shutdown: bool = False + + @contextmanager + def wrap_request_assignment(self, request_meta: RequestMetadata): + max_queued_requests = ( + self._deployment_config.max_queued_requests + if self._deployment_config is not None + else -1 + ) + if ( + max_queued_requests != -1 + and self.num_queued_requests >= max_queued_requests + ): + e = BackPressureError( + num_queued_requests=self.num_queued_requests, + max_queued_requests=max_queued_requests, + ) + logger.warning(e.message) + raise e + + try: + self.inc_num_total_requests(request_meta.route) + self.inc_num_queued_requests() + + yield + finally: + # If the request is disconnected before assignment, this coroutine + # gets cancelled by the caller and an asyncio.CancelledError is + # raised. The finally block ensures that num_queued_requests + # is correctly decremented in this case. + self.dec_num_queued_requests() + + def _update_running_replicas(self, running_replicas: List[RunningReplicaInfo]): + """Prune list of replica ids in self.num_queries_sent_to_replicas. + + We want to avoid self.num_queries_sent_to_replicas from growing + in memory as the deployment upscales and downscales over time. + """ + + running_replica_set = {replica.replica_id for replica in running_replicas} + with self._queries_lock: + self.num_requests_sent_to_replicas = defaultdict( + int, + { + id: self.num_requests_sent_to_replicas[id] + for id, num_queries in self.num_requests_sent_to_replicas.items() + if num_queries or id in running_replica_set + }, + ) + + @property + def autoscaling_config(self) -> Optional[AutoscalingConfig]: + if self._deployment_config is None: + return None + + return self._deployment_config.autoscaling_config + + def update_deployment_config( + self, deployment_config: DeploymentConfig, curr_num_replicas: int + ): + """Update the config for the deployment this router sends requests to.""" + + if self._shutdown: + return + + self._deployment_config = deployment_config + + # Start the metrics pusher if autoscaling is enabled. + autoscaling_config = self.autoscaling_config + if autoscaling_config: + self.metrics_pusher.start() + # Optimization for autoscaling cold start time. If there are + # currently 0 replicas for the deployment, and there is at + # least one queued request on this router, then immediately + # push handle metric to the controller. + if self.should_send_scaled_to_zero_optimized_push(curr_num_replicas): + self.push_autoscaling_metrics_to_controller() + + if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE: + # Record number of queued + ongoing requests at regular + # intervals into the in-memory metrics store + self.metrics_pusher.register_or_update_task( + self.RECORD_METRICS_TASK_NAME, + self._add_autoscaling_metrics_point, + min( + RAY_SERVE_HANDLE_AUTOSCALING_METRIC_RECORD_PERIOD_S, + autoscaling_config.metrics_interval_s, + ), + ) + # Push metrics to the controller periodically. + self.metrics_pusher.register_or_update_task( + self.PUSH_METRICS_TO_CONTROLLER_TASK_NAME, + self.push_autoscaling_metrics_to_controller, + autoscaling_config.metrics_interval_s, + ) + else: + self.metrics_pusher.register_or_update_task( + self.PUSH_METRICS_TO_CONTROLLER_TASK_NAME, + self.push_autoscaling_metrics_to_controller, + HANDLE_METRIC_PUSH_INTERVAL_S, + ) + + else: + if self.metrics_pusher: + self.metrics_pusher.stop_tasks() + + def inc_num_total_requests(self, route: str): + self.num_router_requests.inc(tags={"route": route}) + + def inc_num_queued_requests(self): + self.num_queued_requests += 1 + self.num_queued_requests_gauge.set(self.num_queued_requests) + + def dec_num_queued_requests(self): + self.num_queued_requests -= 1 + self.num_queued_requests_gauge.set(self.num_queued_requests) + + def inc_num_running_requests_for_replica(self, replica_id: ReplicaID): + with self._queries_lock: + self.num_requests_sent_to_replicas[replica_id] += 1 + self.num_running_requests_gauge.set( + sum(self.num_requests_sent_to_replicas.values()) + ) + + def dec_num_running_requests_for_replica(self, replica_id: ReplicaID): + with self._queries_lock: + self.num_requests_sent_to_replicas[replica_id] -= 1 + self.num_running_requests_gauge.set( + sum(self.num_requests_sent_to_replicas.values()) + ) + + def should_send_scaled_to_zero_optimized_push(self, curr_num_replicas: int) -> bool: + return ( + self.autoscaling_config is not None + and curr_num_replicas == 0 + and self.num_queued_requests > 0 + ) + + def push_autoscaling_metrics_to_controller(self): + """Pushes queued and running request metrics to the controller. + + These metrics are used by the controller for autoscaling. + """ + + self._controller_handle.record_handle_metrics.remote( + send_timestamp=time.time(), + deployment_id=self._deployment_id, + handle_id=self._handle_id, + actor_id=self._self_actor_id, + handle_source=self._handle_source, + **self._get_aggregated_requests(), + ) + + def _add_autoscaling_metrics_point(self): + """Adds metrics point for queued and running requests at replicas. + + Also prunes keys in the in memory metrics store with outdated datapoints. + """ + + timestamp = time.time() + self.metrics_store.add_metrics_point( + {QUEUED_REQUESTS_KEY: self.num_queued_requests}, timestamp + ) + if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE: + self.metrics_store.add_metrics_point( + self.num_requests_sent_to_replicas, timestamp + ) + + # Prevent in memory metrics store memory from growing + start_timestamp = time.time() - self.autoscaling_config.look_back_period_s + self.metrics_store.prune_keys_and_compact_data(start_timestamp) + + def _get_aggregated_requests(self): + running_requests = dict() + if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE and self.autoscaling_config: + look_back_period = self.autoscaling_config.look_back_period_s + running_requests = { + replica_id: self.metrics_store.window_average( + replica_id, time.time() - look_back_period + ) + # If data hasn't been recorded yet, return current + # number of queued and ongoing requests. + or num_requests + for replica_id, num_requests in self.num_requests_sent_to_replicas.items() # noqa: E501 + } + + return { + "queued_requests": self.num_queued_requests, + "running_requests": running_requests, + } + + async def shutdown(self): + """Shutdown metrics manager gracefully.""" + + if self.metrics_pusher: + await self.metrics_pusher.graceful_shutdown() + + self._shutdown = True + + +class Router(ABC): + @abstractmethod + def running_replicas_populated(self) -> bool: + pass + + @abstractmethod + def assign_request( + self, + request_meta: RequestMetadata, + *request_args, + **request_kwargs, + ) -> concurrent.futures.Future[ReplicaResult]: + pass + + @abstractmethod + def shutdown(self) -> concurrent.futures.Future: + pass + + +async def create_event() -> asyncio.Event: + """Helper to create an asyncio event in the current event loop.""" + return asyncio.Event() + + +class AsyncioRouter: + def __init__( + self, + controller_handle: ActorHandle, + deployment_id: DeploymentID, + handle_id: str, + self_actor_id: str, + handle_source: DeploymentHandleSource, + event_loop: asyncio.BaseEventLoop, + enable_strict_max_ongoing_requests: bool, + node_id: str, + availability_zone: Optional[str], + prefer_local_node_routing: bool, + resolve_request_arg_func: Coroutine = resolve_deployment_response, + request_router_class: Optional[Callable] = None, + request_router_kwargs: Optional[Dict[str, Any]] = None, + request_router: Optional[RequestRouter] = None, + _request_router_initialized_event: Optional[asyncio.Event] = None, + ): + """Used to assign requests to downstream replicas for a deployment. + + The routing behavior is delegated to a RequestRouter; this is a thin + wrapper that adds metrics and logging. + """ + self._controller_handle = controller_handle + self.deployment_id = deployment_id + self._self_actor_id = self_actor_id + self._handle_source = handle_source + self._event_loop = event_loop + self._request_router_class = request_router_class + self._request_router_kwargs = ( + request_router_kwargs if request_router_kwargs else {} + ) + self._enable_strict_max_ongoing_requests = enable_strict_max_ongoing_requests + self._node_id = node_id + self._availability_zone = availability_zone + self._prefer_local_node_routing = prefer_local_node_routing + # By default, deployment is available unless we receive news + # otherwise through a long poll broadcast from the controller. + self._deployment_available = True + + # The request router will be lazy loaded to decouple form the initialization. + self._request_router: Optional[RequestRouter] = request_router + + if _request_router_initialized_event: + self._request_router_initialized = _request_router_initialized_event + else: + future = asyncio.run_coroutine_threadsafe(create_event(), self._event_loop) + self._request_router_initialized = future.result() + + if self._request_router: + self._request_router_initialized.set() + self._resolve_request_arg_func = resolve_request_arg_func + self._running_replicas: Optional[List[RunningReplicaInfo]] = None + + # Flipped to `True` once the router has received a non-empty + # replica set at least once. + self._running_replicas_populated: bool = False + + # Initializing `self._metrics_manager` before `self.long_poll_client` is + # necessary to avoid race condition where `self.update_deployment_config()` + # might be called before `self._metrics_manager` instance is created. + self._metrics_manager = RouterMetricsManager( + deployment_id, + handle_id, + self_actor_id, + handle_source, + controller_handle, + metrics.Counter( + "serve_num_router_requests", + description="The number of requests processed by the router.", + tag_keys=("deployment", "route", "application", "handle", "actor_id"), + ), + metrics.Gauge( + "serve_deployment_queued_queries", + description=( + "The current number of queries to this deployment waiting" + " to be assigned to a replica." + ), + tag_keys=("deployment", "application", "handle", "actor_id"), + ), + metrics.Gauge( + "serve_num_ongoing_requests_at_replicas", + description=( + "The current number of requests to this deployment that " + "have been submitted to a replica." + ), + tag_keys=("deployment", "application", "handle", "actor_id"), + ), + ) + + # The Router needs to stay informed about changes to the target deployment's + # running replicas and deployment config. We do this via the long poll system. + # However, for efficiency, we don't want to create a LongPollClient for every + # DeploymentHandle, so we use a shared LongPollClient that all Routers + # register themselves with. But first, the router needs to get a fast initial + # update so that it can start serving requests, which we do with a dedicated + # LongPollClient that stops running once the shared client takes over. + + self.long_poll_client = LongPollClient( + controller_handle, + { + ( + LongPollNamespace.DEPLOYMENT_TARGETS, + deployment_id, + ): self.update_deployment_targets, + ( + LongPollNamespace.DEPLOYMENT_CONFIG, + deployment_id, + ): self.update_deployment_config, + }, + call_in_event_loop=self._event_loop, + ) + + shared = SharedRouterLongPollClient.get_or_create( + controller_handle, self._event_loop + ) + shared.register(self) + + @property + def request_router(self) -> Optional[RequestRouter]: + """Get and lazy loading request router. + + If the request_router_class not provided, and the request router is not + yet initialized, then it will return None. Otherwise, if request router + is not yet initialized, it will be initialized and returned. Also, + setting `self._request_router_initialized` to signal that the request + router is initialized. + """ + if not self._request_router and self._request_router_class: + request_router = self._request_router_class( + deployment_id=self.deployment_id, + handle_source=self._handle_source, + self_node_id=self._node_id, + self_actor_id=self._self_actor_id, + self_actor_handle=ray.get_runtime_context().current_actor + if ray.get_runtime_context().get_actor_id() + else None, + # Streaming ObjectRefGenerators are not supported in Ray Client + use_replica_queue_len_cache=self._enable_strict_max_ongoing_requests, + create_replica_wrapper_func=lambda r: RunningReplica(r), + prefer_local_node_routing=self._prefer_local_node_routing, + prefer_local_az_routing=RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING, + self_availability_zone=self._availability_zone, + ) + request_router.initialize_state(**(self._request_router_kwargs)) + + # Populate the running replicas if they are already available. + if self._running_replicas is not None: + request_router._update_running_replicas(self._running_replicas) + + self._request_router = request_router + self._request_router_initialized.set() + + # Log usage telemetry to indicate that custom request router + # feature is being used in this cluster. + if self._request_router_class is not PowerOfTwoChoicesRequestRouter: + ServeUsageTag.CUSTOM_REQUEST_ROUTER_USED.record("1") + return self._request_router + + def running_replicas_populated(self) -> bool: + return self._running_replicas_populated + + def update_deployment_targets(self, deployment_target_info: DeploymentTargetInfo): + self._deployment_available = deployment_target_info.is_available + + running_replicas = deployment_target_info.running_replicas + if self.request_router: + self.request_router._update_running_replicas(running_replicas) + else: + # In this case, the request router hasn't been initialized yet. + # Store the running replicas so that we can update the request + # router once it is initialized. + self._running_replicas = running_replicas + self._metrics_manager._update_running_replicas(running_replicas) + + if running_replicas: + self._running_replicas_populated = True + + def update_deployment_config(self, deployment_config: DeploymentConfig): + self._request_router_class = ( + deployment_config.request_router_config.get_request_router_class() + ) + self._request_router_kwargs = ( + deployment_config.request_router_config.request_router_kwargs + ) + self._metrics_manager.update_deployment_config( + deployment_config, + curr_num_replicas=len(self.request_router.curr_replicas), + ) + + async def _resolve_request_arguments( + self, + request_metadata: RequestMetadata, + request_args: Tuple[Any], + request_kwargs: Dict[str, Any], + ) -> Tuple[Tuple[Any], Dict[str, Any]]: + """Asynchronously resolve and replace top-level request args and kwargs.""" + new_args = list(request_args) + new_kwargs = request_kwargs.copy() + + # Map from index -> task for resolving positional arg + resolve_arg_tasks = {} + for i, obj in enumerate(request_args): + task = await self._resolve_request_arg_func(obj, request_metadata) + if task is not None: + resolve_arg_tasks[i] = task + + # Map from key -> task for resolving key-word arg + resolve_kwarg_tasks = {} + for k, obj in request_kwargs.items(): + task = await self._resolve_request_arg_func(obj, request_metadata) + if task is not None: + resolve_kwarg_tasks[k] = task + + # Gather all argument resolution tasks concurrently. + if resolve_arg_tasks or resolve_kwarg_tasks: + all_tasks = list(resolve_arg_tasks.values()) + list( + resolve_kwarg_tasks.values() + ) + await asyncio.wait(all_tasks) + + # Update new args and new kwargs with resolved arguments + for index, task in resolve_arg_tasks.items(): + new_args[index] = task.result() + for key, task in resolve_kwarg_tasks.items(): + new_kwargs[key] = task.result() + + # Return new args and new kwargs + return new_args, new_kwargs + + def _process_finished_request( + self, + replica_id: ReplicaID, + parent_request_id: str, + response_id: str, + result: Union[Any, RayError], + ): + self._metrics_manager.dec_num_running_requests_for_replica(replica_id) + if isinstance(result, ActorDiedError): + # Replica has died but controller hasn't notified the router yet. + # Don't consider this replica for requests in the future, and retry + # routing request. + if self.request_router: + self.request_router.on_replica_actor_died(replica_id) + logger.warning( + f"{replica_id} will not be considered for future " + "requests because it has died." + ) + elif isinstance(result, ActorUnavailableError): + # There are network issues, or replica has died but GCS is down so + # ActorUnavailableError will be raised until GCS recovers. For the + # time being, invalidate the cache entry so that we don't try to + # send requests to this replica without actively probing, and retry + # routing request. + if self.request_router: + self.request_router.on_replica_actor_unavailable(replica_id) + logger.warning( + f"Request failed because {replica_id} is temporarily unavailable." + ) + + async def route_and_send_request( + self, pr: PendingRequest + ) -> Tuple[ReplicaResult, ReplicaID]: + """Choose a replica for the request and send it. + + This will block indefinitely if no replicas are available to handle the + request, so it's up to the caller to time out or cancel the request. + """ + # Wait for the router to be initialized before sending the request. + await self._request_router_initialized.wait() + + r = await self.request_router._choose_replica_for_request(pr) + + # If the queue len cache is disabled or we're sending a request to Java, + # then directly send the query and hand the response back. The replica will + # never reject requests in this code path. + if not self._enable_strict_max_ongoing_requests or r.is_cross_language: + result, _ = await r.send_request(pr, with_rejection=False) + return result, r.replica_id + + while True: + result = None + try: + result, queue_info = await r.send_request(pr, with_rejection=True) + self.request_router.on_new_queue_len_info(r.replica_id, queue_info) + self.request_router.on_request_routed(pr, r.replica_id, result) + if queue_info.accepted: + return result, r.replica_id + except asyncio.CancelledError: + # NOTE(edoakes): this is not strictly necessary because there are + # currently no `await` statements between getting the ref and returning, + # but I'm adding it defensively. + if result is not None: + result.cancel() + + raise + except ActorDiedError: + # Replica has died but controller hasn't notified the router yet. + # Don't consider this replica for requests in the future, and retry + # routing request. + self.request_router.on_replica_actor_died(r.replica_id) + logger.warning( + f"{r.replica_id} will not be considered for future " + "requests because it has died." + ) + except ActorUnavailableError: + # There are network issues, or replica has died but GCS is down so + # ActorUnavailableError will be raised until GCS recovers. For the + # time being, invalidate the cache entry so that we don't try to + # send requests to this replica without actively probing, and retry + # routing request. + self.request_router.on_replica_actor_unavailable(r.replica_id) + logger.warning(f"{r.replica_id} is temporarily unavailable.") + + # If the replica rejects the request, retry the routing process. The + # request will be placed on the front of the queue to avoid tail latencies. + # TODO(edoakes): this retry procedure is not perfect because it'll reset the + # process of choosing candidates replicas (i.e., for locality-awareness). + r = await self.request_router._choose_replica_for_request(pr, is_retry=True) + + async def assign_request( + self, + request_meta: RequestMetadata, + *request_args, + **request_kwargs, + ) -> ReplicaResult: + """Assign a request to a replica and return the resulting object_ref.""" + + if not self._deployment_available: + raise DeploymentUnavailableError(self.deployment_id) + + response_id = generate_request_id() + assign_request_task = asyncio.current_task() + ray.serve.context._add_request_pending_assignment( + request_meta.internal_request_id, response_id, assign_request_task + ) + assign_request_task.add_done_callback( + lambda _: ray.serve.context._remove_request_pending_assignment( + request_meta.internal_request_id, response_id + ) + ) + + # Wait for the router to be initialized before sending the request. + await self._request_router_initialized.wait() + + with self._metrics_manager.wrap_request_assignment(request_meta): + # Optimization: if there are currently zero replicas for a deployment, + # push handle metric to controller to allow for fast cold start time. + if self._metrics_manager.should_send_scaled_to_zero_optimized_push( + curr_num_replicas=len(self.request_router.curr_replicas) + ): + self._metrics_manager.push_autoscaling_metrics_to_controller() + + replica_result = None + try: + request_args, request_kwargs = await self._resolve_request_arguments( + request_meta, request_args, request_kwargs + ) + replica_result, replica_id = await self.route_and_send_request( + PendingRequest( + args=list(request_args), + kwargs=request_kwargs, + metadata=request_meta, + ), + ) + + # Keep track of requests that have been sent out to replicas + if RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE: + _request_context = ray.serve.context._get_serve_request_context() + request_id: str = _request_context.request_id + self._metrics_manager.inc_num_running_requests_for_replica( + replica_id + ) + callback = partial( + self._process_finished_request, + replica_id, + request_id, + response_id, + ) + replica_result.add_done_callback(callback) + + return replica_result + except asyncio.CancelledError: + # NOTE(edoakes): this is not strictly necessary because + # there are currently no `await` statements between + # getting the ref and returning, but I'm adding it defensively. + if replica_result is not None: + replica_result.cancel() + + raise + + async def shutdown(self): + await self._metrics_manager.shutdown() + + +class SingletonThreadRouter(Router): + """Wrapper class that runs an AsyncioRouter on a separate thread. + + The motivation for this is to avoid user code blocking the event loop and + preventing the router from making progress. + + Maintains a singleton event loop running in a daemon thread that is shared by + all AsyncioRouters. + """ + + _asyncio_loop: Optional[asyncio.AbstractEventLoop] = None + _asyncio_loop_creation_lock = threading.Lock() + + def __init__(self, **passthrough_kwargs): + assert ( + "event_loop" not in passthrough_kwargs + ), "SingletonThreadRouter manages the router event loop." + + self._asyncio_router = AsyncioRouter( + event_loop=self._get_singleton_asyncio_loop(), **passthrough_kwargs + ) + + @classmethod + def _get_singleton_asyncio_loop(cls) -> asyncio.AbstractEventLoop: + """Get singleton asyncio loop running in a daemon thread. + + This method is thread safe. + """ + with cls._asyncio_loop_creation_lock: + if cls._asyncio_loop is None: + cls._asyncio_loop = asyncio.new_event_loop() + thread = threading.Thread( + daemon=True, + target=cls._asyncio_loop.run_forever, + ) + thread.start() + + return cls._asyncio_loop + + def running_replicas_populated(self) -> bool: + return self._asyncio_router.running_replicas_populated() + + def assign_request( + self, + request_meta: RequestMetadata, + *request_args, + **request_kwargs, + ) -> concurrent.futures.Future[ReplicaResult]: + """Routes assign_request call on the internal asyncio loop. + + This method uses `run_coroutine_threadsafe` to execute the actual request + assignment logic (`_asyncio_router.assign_request`) on the dedicated + asyncio event loop thread. It returns a `concurrent.futures.Future` that + can be awaited or queried from the calling thread. + + Returns: + A concurrent.futures.Future resolving to the ReplicaResult representing + the assigned request. + """ + + def asyncio_future_callback( + asyncio_future: asyncio.Future, concurrent_future: concurrent.futures.Future + ): + """Callback attached to the asyncio Task running assign_request. + + This runs when the asyncio Task finishes (completes, fails, or is cancelled). + Its primary goal is to propagate cancellation initiated via the + `concurrent_future` back to the `ReplicaResult` in situations where + asyncio_future didn't see the cancellation event in time. Think of it + like a second line of defense for cancellation of replica results. + """ + # Check if the cancellation originated from the concurrent.futures.Future + if ( + concurrent_future.cancelled() + and not asyncio_future.cancelled() + and asyncio_future.exception() is None + ): + result: ReplicaResult = asyncio_future.result() + logger.info( + "Asyncio task completed despite cancellation attempt. " + "Attempting to cancel the request that was assigned to a replica." + ) + result.cancel() + + task = self._asyncio_loop.create_task( + self._asyncio_router.assign_request( + request_meta, *request_args, **request_kwargs + ) + ) + # Route the actual request assignment coroutine on the asyncio loop thread. + concurrent_future = run_coroutine_or_future_threadsafe( + task, + loop=self._asyncio_loop, + ) + task.add_done_callback(lambda _: asyncio_future_callback(_, concurrent_future)) + return concurrent_future + + def shutdown(self) -> concurrent.futures.Future: + return asyncio.run_coroutine_threadsafe( + self._asyncio_router.shutdown(), loop=self._asyncio_loop + ) + + +class SharedRouterLongPollClient: + def __init__(self, controller_handle: ActorHandle, event_loop: AbstractEventLoop): + self.controller_handler = controller_handle + self.event_loop = event_loop + + # We use a WeakSet to store the Routers so that we don't prevent them + # from being garbage-collected. + self.routers: MutableMapping[ + DeploymentID, weakref.WeakSet[AsyncioRouter] + ] = defaultdict(weakref.WeakSet) + + # Creating the LongPollClient implicitly starts it + self.long_poll_client = LongPollClient( + controller_handle, + key_listeners={}, + call_in_event_loop=self.event_loop, + ) + + @classmethod + @lru_cache(maxsize=None) + def get_or_create( + cls, controller_handle: ActorHandle, event_loop: AbstractEventLoop + ) -> "SharedRouterLongPollClient": + shared = cls(controller_handle=controller_handle, event_loop=event_loop) + logger.info(f"Started {shared}.") + return shared + + def update_deployment_targets( + self, + deployment_target_info: DeploymentTargetInfo, + deployment_id: DeploymentID, + ) -> None: + for router in self.routers[deployment_id]: + router.update_deployment_targets(deployment_target_info) + router.long_poll_client.stop() + + def update_deployment_config( + self, deployment_config: DeploymentConfig, deployment_id: DeploymentID + ) -> None: + for router in self.routers[deployment_id]: + router.update_deployment_config(deployment_config) + router.long_poll_client.stop() + + def register(self, router: AsyncioRouter) -> None: + # We need to run the underlying method in the same event loop that runs + # the long poll loop, because we need to mutate the mapping of routers, + # which are also being iterated over by the key listener callbacks. + # If those happened concurrently in different threads, + # we could get a `RuntimeError: Set changed size during iteration`. + # See https://github.com/ray-project/ray/pull/53613 for more details. + self.event_loop.call_soon_threadsafe(self._register, router) + + def _register(self, router: AsyncioRouter) -> None: + self.routers[router.deployment_id].add(router) + + # Remove the entries for any deployment ids that no longer have any routers. + # The WeakSets will automatically lose track of Routers that get GC'd, + # but the outer dict will keep the key around, so we need to clean up manually. + # Note the list(...) to avoid mutating self.routers while iterating over it. + for deployment_id, routers in list(self.routers.items()): + if not routers: + self.routers.pop(deployment_id) + + # Register the new listeners on the long poll client. + # Some of these listeners may already exist, but it's safe to add them again. + key_listeners = { + (LongPollNamespace.DEPLOYMENT_TARGETS, deployment_id): partial( + self.update_deployment_targets, deployment_id=deployment_id + ) + for deployment_id in self.routers.keys() + } | { + (LongPollNamespace.DEPLOYMENT_CONFIG, deployment_id): partial( + self.update_deployment_config, deployment_id=deployment_id + ) + for deployment_id in self.routers.keys() + } + self.long_poll_client.add_key_listeners(key_listeners) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/storage/__init__.py b/venv/lib/python3.10/site-packages/ray/serve/_private/storage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/storage/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/storage/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adb332447da0d8c03dd9f3c999d7a260dfa7924a Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/storage/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/storage/__pycache__/kv_store.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/storage/__pycache__/kv_store.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b8c7a91cd564d1dd321a4622aa8132048cf3b62 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/storage/__pycache__/kv_store.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/storage/__pycache__/kv_store_base.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/storage/__pycache__/kv_store_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e8cf04acb6f45a1157e09434ab747bde613e41f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/storage/__pycache__/kv_store_base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/storage/kv_store.py b/venv/lib/python3.10/site-packages/ray/serve/_private/storage/kv_store.py new file mode 100644 index 0000000000000000000000000000000000000000..edca67b596af5e2ac40208143f30bcb1174cf6e1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/storage/kv_store.py @@ -0,0 +1,109 @@ +import logging +from typing import Optional + +import ray +import ray.serve._private.constants as serve_constants +from ray._raylet import GcsClient +from ray.serve._private.storage.kv_store_base import KVStoreBase + +logger = logging.getLogger(serve_constants.SERVE_LOGGER_NAME) + +SERVE_INTERNAL_KV_NAMESPACE = b"serve" + + +def get_storage_key(namespace: str, storage_key: str) -> str: + """In case we need to access kvstore""" + return "{ns}-{key}".format(ns=namespace, key=storage_key) + + +class KVStoreError(Exception): + def __init__(self, rpc_code): + self.rpc_code = rpc_code + + +class RayInternalKVStore(KVStoreBase): + """Wraps ray's internal_kv with a namespace to avoid collisions. + + Supports string keys and bytes values, caller must handle serialization. + """ + + def __init__( + self, + namespace: Optional[str] = None, + gcs_client: Optional[GcsClient] = None, + ): + if namespace is not None and not isinstance(namespace, str): + raise TypeError("namespace must a string, got: {}.".format(type(namespace))) + if gcs_client is not None: + self.gcs_client = gcs_client + else: + self.gcs_client = GcsClient(address=ray.get_runtime_context().gcs_address) + self.timeout = serve_constants.RAY_SERVE_KV_TIMEOUT_S + self.namespace = namespace or "" + + def get_storage_key(self, key: str) -> str: + return "{ns}-{key}".format(ns=self.namespace, key=key) + + def put(self, key: str, val: bytes) -> bool: + """Put the key-value pair into the store. + + Args: + key: The key to store. + val: The value to store. + """ + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + if not isinstance(val, bytes): + raise TypeError("val must be bytes, got: {}.".format(type(val))) + + try: + return self.gcs_client.internal_kv_put( + self.get_storage_key(key).encode(), + val, + overwrite=True, + namespace=SERVE_INTERNAL_KV_NAMESPACE, + timeout=self.timeout, + ) + except ray.exceptions.RpcError as e: + raise KVStoreError(e.rpc_code) + + def get(self, key: str) -> Optional[bytes]: + """Get the value associated with the given key from the store. + + Args: + key: The key to retrieve. + + Returns: + Optional[bytes]: The bytes value. If the key wasn't found, returns None. + """ + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + + try: + return self.gcs_client.internal_kv_get( + self.get_storage_key(key).encode(), + namespace=SERVE_INTERNAL_KV_NAMESPACE, + timeout=self.timeout, + ) + except ray.exceptions.RpcError as e: + raise KVStoreError(e.rpc_code) + + def delete(self, key: str): + """Delete the value associated with the given key from the store. + + Args: + key: The key to delete. + """ + + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + + try: + return self.gcs_client.internal_kv_del( + self.get_storage_key(key).encode(), + False, + namespace=SERVE_INTERNAL_KV_NAMESPACE, + timeout=self.timeout, + ) + except ray.exceptions.RpcError as e: + raise KVStoreError(e.rpc_code) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/storage/kv_store_base.py b/venv/lib/python3.10/site-packages/ray/serve/_private/storage/kv_store_base.py new file mode 100644 index 0000000000000000000000000000000000000000..68216e6547d169963f424c726fd2494a774c0039 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/storage/kv_store_base.py @@ -0,0 +1,56 @@ +import abc +from abc import abstractmethod +from typing import Optional + +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class KVStoreBase(metaclass=abc.ABCMeta): + """Abstract class for KVStore defining APIs needed for ray serve + use cases, currently (8/6/2021) controller state checkpointing. + """ + + @abstractmethod + def get_storage_key(self, key: str) -> str: + """Get internal key for storage. + + Args: + key: User provided key + + Returns: + storage_key: Formatted key for storage, usually by + prepending namespace. + """ + raise NotImplementedError("get_storage_key() has to be implemented") + + @abstractmethod + def put(self, key: str, val: bytes) -> bool: + """Put object into kv store, bytes only. + + Args: + key: Key for object to be stored. + val: Byte value of object. + """ + raise NotImplementedError("put() has to be implemented") + + @abstractmethod + def get(self, key: str) -> Optional[bytes]: + """Get object from storage. + + Args: + key: Key for object to be retrieved. + + Returns: + val: Byte value of object from storage. + """ + raise NotImplementedError("get() has to be implemented") + + @abstractmethod + def delete(self, key: str) -> None: + """Delete an object. + + Args: + key: Key for object to be deleted. + """ + raise NotImplementedError("delete() has to be implemented") diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/test_utils.py b/venv/lib/python3.10/site-packages/ray/serve/_private/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..daa8595e5338f04f48e627ad27df34341f56975a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/test_utils.py @@ -0,0 +1,803 @@ +import asyncio +import datetime +import os +import random +import threading +import time +from contextlib import asynccontextmanager +from copy import copy, deepcopy +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import grpc +import requests +from starlette.requests import Request + +import ray +import ray.util.state as state_api +from ray import serve +from ray.actor import ActorHandle +from ray.serve._private.client import ServeControllerClient +from ray.serve._private.common import ( + CreatePlacementGroupRequest, + DeploymentID, + DeploymentStatus, + RequestProtocol, +) +from ray.serve._private.constants import ( + SERVE_DEFAULT_APP_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.deployment_state import ALL_REPLICA_STATES, ReplicaState +from ray.serve._private.proxy import DRAINING_MESSAGE +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import TimerBase +from ray.serve.context import _get_global_client +from ray.serve.generated import serve_pb2, serve_pb2_grpc +from ray.serve.schema import ApplicationStatus, TargetGroup + +TELEMETRY_ROUTE_PREFIX = "/telemetry" +STORAGE_ACTOR_NAME = "storage" + + +class MockTimer(TimerBase): + def __init__(self, start_time: Optional[float] = None): + self._lock = threading.Lock() + self.reset(start_time=start_time) + + def reset(self, start_time: Optional[float] = None): + if start_time is None: + start_time = time.time() + self._curr = start_time + + def time(self) -> float: + return self._curr + + def advance(self, by: float): + with self._lock: + self._curr += by + + def realistic_sleep(self, amt: float): + with self._lock: + self._curr += amt + 0.001 + + +class MockAsyncTimer: + def __init__(self, start_time: Optional[float] = 0): + self.reset(start_time=start_time) + self._num_sleepers = 0 + + def reset(self, start_time: 0): + self._curr = start_time + + def time(self) -> float: + return self._curr + + async def sleep(self, amt: float): + self._num_sleepers += 1 + end = self._curr + amt + + # Give up the event loop + while self._curr < end: + await asyncio.sleep(0) + + self._num_sleepers -= 1 + + def advance(self, amt: float): + self._curr += amt + + def num_sleepers(self): + return self._num_sleepers + + +class MockKVStore: + def __init__(self): + self.store = dict() + + def put(self, key: str, val: Any) -> bool: + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + self.store[key] = val + return True + + def get(self, key: str) -> Any: + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + return self.store.get(key, None) + + def delete(self, key: str) -> bool: + if not isinstance(key, str): + raise TypeError("key must be a string, got: {}.".format(type(key))) + + if key in self.store: + del self.store[key] + return True + + return False + + +class MockClusterNodeInfoCache: + def __init__(self): + self.alive_node_ids = set() + self.total_resources_per_node = dict() + self.available_resources_per_node = dict() + self.draining_nodes = dict() + self.node_labels = dict() + + def get_alive_node_ids(self): + return self.alive_node_ids + + def get_draining_nodes(self): + return self.draining_nodes + + def get_active_node_ids(self): + return self.alive_node_ids - set(self.draining_nodes) + + def get_node_az(self, node_id): + return None + + def get_available_resources_per_node(self): + return self.available_resources_per_node + + def get_total_resources_per_node(self): + return self.total_resources_per_node + + def add_node(self, node_id: str, resources: Dict = None, labels: Dict = None): + self.alive_node_ids.add(node_id) + self.total_resources_per_node[node_id] = deepcopy(resources) or {} + self.available_resources_per_node[node_id] = deepcopy(resources) or {} + self.node_labels[node_id] = labels or {} + + def set_available_resources_per_node(self, node_id: str, resources: Dict): + self.available_resources_per_node[node_id] = deepcopy(resources) + + +class FakeRemoteFunction: + def remote(self): + pass + + +class MockActorHandle: + def __init__(self, **kwargs): + self._options = kwargs + self._actor_id = "fake_id" + self.initialize_and_get_metadata_called = False + self.is_allocated_called = False + + @property + def initialize_and_get_metadata(self): + self.initialize_and_get_metadata_called = True + # return a mock object so that we can call `remote()` on it. + return FakeRemoteFunction() + + @property + def is_allocated(self): + self.is_allocated_called = True + return FakeRemoteFunction() + + +class MockActorClass: + def __init__(self): + self._init_args = () + self._options = dict() + + def options(self, **kwargs): + res = copy(self) + + for k, v in kwargs.items(): + res._options[k] = v + + return res + + def remote(self, *args) -> MockActorHandle: + return MockActorHandle(init_args=args, **self._options) + + +class MockPlacementGroup: + def __init__(self, request: CreatePlacementGroupRequest): + self._bundles = request.bundles + self._strategy = request.strategy + self._soft_target_node_id = request.target_node_id + self._name = request.name + self._lifetime = "detached" + + +class MockDeploymentHandle: + def __init__(self, deployment_name: str, app_name: str = SERVE_DEFAULT_APP_NAME): + self._deployment_name = deployment_name + self._app_name = app_name + self._protocol = RequestProtocol.UNDEFINED + self._running_replicas_populated = False + self._initialized = False + + def is_initialized(self): + return self._initialized + + def _init(self): + if self._initialized: + raise RuntimeError("already initialized") + + self._initialized = True + + def options(self, *args, **kwargs): + return self + + def __eq__(self, dep: Tuple[str]): + other_deployment_name, other_app_name = dep + return ( + self._deployment_name == other_deployment_name + and self._app_name == other_app_name + ) + + def _set_request_protocol(self, protocol: RequestProtocol): + self._protocol = protocol + + def _get_or_create_router(self): + pass + + def running_replicas_populated(self) -> bool: + return self._running_replicas_populated + + def set_running_replicas_populated(self, val: bool): + self._running_replicas_populated = val + + +@serve.deployment +class GetPID: + def __call__(self): + return os.getpid() + + +get_pid_entrypoint = GetPID.bind() + + +def check_ray_stopped(): + try: + requests.get("http://localhost:8265/api/ray/version") + return False + except Exception: + return True + + +def check_ray_started(): + return requests.get("http://localhost:8265/api/ray/version").status_code == 200 + + +def check_deployment_status( + name: str, expected_status: DeploymentStatus, app_name=SERVE_DEFAULT_APP_NAME +) -> bool: + app_status = serve.status().applications[app_name] + assert app_status.deployments[name].status == expected_status + return True + + +def get_num_alive_replicas( + deployment_name: str, app_name: str = SERVE_DEFAULT_APP_NAME +) -> int: + """Get the replicas currently running for the given deployment.""" + + dep_id = DeploymentID(name=deployment_name, app_name=app_name) + actors = state_api.list_actors( + filters=[ + ("class_name", "=", dep_id.to_replica_actor_class_name()), + ("state", "=", "ALIVE"), + ] + ) + return len(actors) + + +def check_num_replicas_gte( + name: str, target: int, app_name: str = SERVE_DEFAULT_APP_NAME +) -> int: + """Check if num replicas is >= target.""" + + assert get_num_alive_replicas(name, app_name) >= target + return True + + +def check_num_replicas_eq( + name: str, + target: int, + app_name: str = SERVE_DEFAULT_APP_NAME, + use_controller: bool = False, +) -> int: + """Check if num replicas is == target.""" + + if use_controller: + dep = serve.status().applications[app_name].deployments[name] + num_running_replicas = dep.replica_states.get(ReplicaState.RUNNING, 0) + assert num_running_replicas == target + else: + assert get_num_alive_replicas(name, app_name) == target + + return True + + +def check_num_replicas_lte( + name: str, target: int, app_name: str = SERVE_DEFAULT_APP_NAME +) -> int: + """Check if num replicas is <= target.""" + + assert get_num_alive_replicas(name, app_name) <= target + return True + + +def check_apps_running(apps: List): + status = serve.status() + + for app_name in apps: + assert status.applications[app_name].status == ApplicationStatus.RUNNING + + return True + + +def check_replica_counts( + controller: ActorHandle, + deployment_id: DeploymentID, + total: Optional[int] = None, + by_state: Optional[List[Tuple[ReplicaState, int, Callable]]] = None, +): + """Uses _dump_replica_states_for_testing to check replica counts. + + Args: + controller: A handle to the Serve controller. + deployment_id: The deployment to check replica counts for. + total: The total number of expected replicas for the deployment. + by_state: A list of tuples of the form + (replica state, number of replicas, filter function). + Used for more fine grained checks. + """ + replicas = ray.get( + controller._dump_replica_states_for_testing.remote(deployment_id) + ) + + if total is not None: + replica_counts = { + state: len(replicas.get([state])) + for state in ALL_REPLICA_STATES + if replicas.get([state]) + } + assert replicas.count() == total, replica_counts + + if by_state is not None: + for state, count, check in by_state: + assert isinstance(state, ReplicaState) + assert isinstance(count, int) and count >= 0 + if check: + filtered = {r for r in replicas.get(states=[state]) if check(r)} + curr_count = len(filtered) + else: + curr_count = replicas.count(states=[state]) + msg = f"Expected {count} for state {state} but got {curr_count}." + assert curr_count == count, msg + + return True + + +@ray.remote(name=STORAGE_ACTOR_NAME, namespace=SERVE_NAMESPACE, num_cpus=0) +class TelemetryStorage: + def __init__(self): + self.reports_received = 0 + self.current_report = dict() + + def store_report(self, report: Dict) -> None: + self.reports_received += 1 + self.current_report = report + + def get_report(self) -> Dict: + return self.current_report + + def get_reports_received(self) -> int: + return self.reports_received + + +@serve.deployment(ray_actor_options={"num_cpus": 0}) +class TelemetryReceiver: + def __init__(self): + self.storage = ray.get_actor(name=STORAGE_ACTOR_NAME, namespace=SERVE_NAMESPACE) + + async def __call__(self, request: Request) -> bool: + report = await request.json() + ray.get(self.storage.store_report.remote(report)) + return True + + +receiver_app = TelemetryReceiver.bind() + + +def start_telemetry_app(): + """Start a telemetry Serve app. + + Ray should be initialized before calling this method. + + NOTE: If you're running the TelemetryReceiver Serve app to check telemetry, + remember that the receiver itself is counted in the telemetry. E.g. if you + deploy a Serve app other than the receiver, the number of apps in the + cluster is 2- not 1– since the receiver is also running. + + Returns a handle to a TelemetryStorage actor. You can use this actor + to access the latest telemetry reports. + """ + + storage = TelemetryStorage.remote() + serve.run(receiver_app, name="telemetry", route_prefix=TELEMETRY_ROUTE_PREFIX) + return storage + + +def check_telemetry( + tag: ServeUsageTag, expected: Any, storage_actor_name: str = STORAGE_ACTOR_NAME +): + storage_handle = ray.get_actor(storage_actor_name, namespace=SERVE_NAMESPACE) + report = ray.get(storage_handle.get_report.remote()) + print(report["extra_usage_tags"]) + assert tag.get_value_from_report(report) == expected + return True + + +def ping_grpc_list_applications(channel, app_names, test_draining=False): + import pytest + + stub = serve_pb2_grpc.RayServeAPIServiceStub(channel) + request = serve_pb2.ListApplicationsRequest() + if test_draining: + with pytest.raises(grpc.RpcError) as exception_info: + _, _ = stub.ListApplications.with_call(request=request) + rpc_error = exception_info.value + assert rpc_error.code() == grpc.StatusCode.UNAVAILABLE + assert rpc_error.details() == DRAINING_MESSAGE + else: + response, call = stub.ListApplications.with_call(request=request) + assert call.code() == grpc.StatusCode.OK + assert response.application_names == app_names + return True + + +def ping_grpc_healthz(channel, test_draining=False): + import pytest + + stub = serve_pb2_grpc.RayServeAPIServiceStub(channel) + request = serve_pb2.HealthzRequest() + if test_draining: + with pytest.raises(grpc.RpcError) as exception_info: + _, _ = stub.Healthz.with_call(request=request) + rpc_error = exception_info.value + assert rpc_error.code() == grpc.StatusCode.UNAVAILABLE + assert rpc_error.details() == DRAINING_MESSAGE + else: + response, call = stub.Healthz.with_call(request=request) + assert call.code() == grpc.StatusCode.OK + assert response.message == "success" + + +def ping_grpc_call_method(channel, app_name, test_not_found=False): + import pytest + + stub = serve_pb2_grpc.UserDefinedServiceStub(channel) + request = serve_pb2.UserDefinedMessage(name="foo", num=30, foo="bar") + metadata = (("application", app_name),) + if test_not_found: + with pytest.raises(grpc.RpcError) as exception_info: + _, _ = stub.__call__.with_call(request=request, metadata=metadata) + rpc_error = exception_info.value + assert rpc_error.code() == grpc.StatusCode.NOT_FOUND, rpc_error.code() + assert f"Application '{app_name}' not found." in rpc_error.details() + else: + response, call = stub.__call__.with_call(request=request, metadata=metadata) + assert call.code() == grpc.StatusCode.OK, call.code() + assert response.greeting == "Hello foo from bar", response.greeting + + +def ping_grpc_another_method(channel, app_name): + stub = serve_pb2_grpc.UserDefinedServiceStub(channel) + request = serve_pb2.UserDefinedMessage(name="foo", num=30, foo="bar") + metadata = (("application", app_name),) + response = stub.Method1(request=request, metadata=metadata) + assert response.greeting == "Hello foo from method1" + + +def ping_grpc_model_multiplexing(channel, app_name): + stub = serve_pb2_grpc.UserDefinedServiceStub(channel) + request = serve_pb2.UserDefinedMessage(name="foo", num=30, foo="bar") + multiplexed_model_id = "999" + metadata = ( + ("application", app_name), + ("multiplexed_model_id", multiplexed_model_id), + ) + response = stub.Method2(request=request, metadata=metadata) + assert ( + response.greeting + == f"Method2 called model, loading model: {multiplexed_model_id}" + ) + + +def ping_grpc_streaming(channel, app_name): + stub = serve_pb2_grpc.UserDefinedServiceStub(channel) + request = serve_pb2.UserDefinedMessage(name="foo", num=30, foo="bar") + metadata = (("application", app_name),) + responses = stub.Streaming(request=request, metadata=metadata) + for idx, response in enumerate(responses): + assert response.greeting == f"{idx}: Hello foo from bar" + + +def ping_fruit_stand(channel, app_name): + stub = serve_pb2_grpc.FruitServiceStub(channel) + request = serve_pb2.FruitAmounts(orange=4, apple=8) + metadata = (("application", app_name),) + response = stub.FruitStand(request=request, metadata=metadata) + assert response.costs == 32 + + +@asynccontextmanager +async def send_signal_on_cancellation(signal_actor: ActorHandle): + cancelled = False + try: + yield + await asyncio.sleep(100) + except asyncio.CancelledError: + cancelled = True + # Clear the context var to avoid Ray recursively cancelling this method call. + ray._raylet.async_task_id.set(None) + await signal_actor.send.remote() + + if not cancelled: + raise RuntimeError( + "CancelledError wasn't raised during `send_signal_on_cancellation` block" + ) + + +class FakeGrpcContext: + def __init__(self): + self._auth_context = {"key": "value"} + self._invocation_metadata = [("key", "value")] + self._peer = "peer" + self._peer_identities = b"peer_identities" + self._peer_identity_key = "peer_identity_key" + self._code = None + self._details = None + self._trailing_metadata = [] + self._invocation_metadata = [] + + def auth_context(self): + return self._auth_context + + def code(self): + return self._code + + def details(self): + return self._details + + def peer(self): + return self._peer + + def peer_identities(self): + return self._peer_identities + + def peer_identity_key(self): + return self._peer_identity_key + + def trailing_metadata(self): + return self._trailing_metadata + + def set_code(self, code): + self._code = code + + def set_details(self, details): + self._details = details + + def set_trailing_metadata(self, trailing_metadata): + self._trailing_metadata = trailing_metadata + + def invocation_metadata(self): + return self._invocation_metadata + + +class FakeGauge: + def __init__(self, name: str = None, tag_keys: Tuple[str] = None): + self.name = name + self.values = dict() + + self.tags = tag_keys or () + self.default_tags = dict() + + def set_default_tags(self, tags: Dict[str, str]): + for key, tag in tags.items(): + assert key in self.tags + self.default_tags[key] = tag + + def set(self, value: Union[int, float], tags: Dict[str, str] = None): + merged_tags = self.default_tags.copy() + merged_tags.update(tags or {}) + assert set(merged_tags.keys()) == set(self.tags) + + d = self.values + for tag in self.tags[:-1]: + tag_value = merged_tags[tag] + if tag_value not in d: + d[tag_value] = dict() + d = d[tag_value] + + d[merged_tags[self.tags[-1]]] = value + + def get_value(self, tags: Dict[str, str]): + value = self.values + for tag in self.tags: + tag_value = tags[tag] + value = value.get(tag_value) + if value is None: + return + + return value + + +class FakeCounter: + def __init__(self, name: str = None, tag_keys: Tuple[str] = None): + self.name = name + self.counts = dict() + + self.tags = tag_keys or () + self.default_tags = dict() + + def set_default_tags(self, tags: Dict[str, str]): + for key, tag in tags.items(): + assert key in self.tags + self.default_tags[key] = tag + + def inc(self, value: Union[int, float] = 1.0, tags: Dict[str, str] = None): + merged_tags = self.default_tags.copy() + merged_tags.update(tags or {}) + assert set(merged_tags.keys()) == set(self.tags) + + d = self.counts + for tag in self.tags[:-1]: + tag_value = merged_tags[tag] + if tag_value not in d: + d[tag_value] = dict() + d = d[tag_value] + + key = merged_tags[self.tags[-1]] + d[key] = d.get(key, 0) + value + + def get_count(self, tags: Dict[str, str]) -> int: + value = self.counts + for tag in self.tags: + tag_value = tags[tag] + value = value.get(tag_value) + if value is None: + return + + return value + + def get_tags(self): + return self.tags + + +@ray.remote +def get_node_id(): + return ray.get_runtime_context().get_node_id() + + +def check_num_alive_nodes(target: int): + alive_nodes = [node for node in ray.nodes() if node["Alive"]] + assert len(alive_nodes) == target + return True + + +def get_deployment_details( + deployment_name: str, + app_name: str = SERVE_DEFAULT_APP_NAME, + _client: ServeControllerClient = None, +): + client = _client or _get_global_client() + details = client.get_serve_details() + return details["applications"][app_name]["deployments"][deployment_name] + + +@ray.remote +class Counter: + def __init__(self, target: int): + self.count = 0 + self.target = target + self.ready_event = asyncio.Event() + + def inc(self): + self.count += 1 + if self.count == self.target: + self.ready_event.set() + + async def wait(self): + await self.ready_event.wait() + + +def tlog(s: str, level: str = "INFO"): + """Convenient logging method for testing.""" + + now = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3] + print(f"[{level}] {now} {s}") + + +def get_application_urls( + protocol: Union[str, RequestProtocol] = RequestProtocol.HTTP, + app_name: str = SERVE_DEFAULT_APP_NAME, + use_localhost: bool = False, + is_websocket: bool = False, + exclude_route_prefix: bool = False, +) -> List[str]: + """Get the URL of the application. + + Args: + protocol: The protocol to use for the application. + app_name: The name of the application. + use_localhost: Whether to use localhost instead of the IP address. + Set to True if Serve deployments are not exposed publicly or + for low latency benchmarking. + is_websocket: Whether the url should be served as a websocket. + exclude_route_prefix: The route prefix to exclude from the application. + Returns: + The URLs of the application. + """ + client = _get_global_client() + serve_details = client.get_serve_details() + if app_name not in serve_details["applications"]: + return [client.root_url] + route_prefix = serve_details["applications"][app_name]["route_prefix"] + if exclude_route_prefix: + route_prefix = "" + if isinstance(protocol, str): + protocol = RequestProtocol(protocol) + target_groups: List[TargetGroup] = ray.get( + client._controller.get_target_groups.remote(app_name) + ) + target_groups = [ + target_group + for target_group in target_groups + if target_group.protocol == protocol + ] + + if len(target_groups) == 0: + raise ValueError( + f"No target group found for app {app_name} with protocol {protocol} and route prefix {route_prefix}" + ) + urls = [] + for target_group in target_groups: + for target in target_group.targets: + ip = "localhost" if use_localhost else target.ip + if protocol == RequestProtocol.HTTP: + scheme = "ws" if is_websocket else "http" + url = f"{scheme}://{ip}:{target.port}{route_prefix}" + elif protocol == RequestProtocol.GRPC: + if is_websocket: + raise ValueError( + "is_websocket=True is not supported with gRPC protocol." + ) + url = f"{ip}:{target.port}" + else: + raise ValueError(f"Unsupported protocol: {protocol}") + url = url.rstrip("/") + urls.append(url) + return urls + + +def get_application_url( + protocol: Union[str, RequestProtocol] = RequestProtocol.HTTP, + app_name: str = SERVE_DEFAULT_APP_NAME, + use_localhost: bool = False, + is_websocket: bool = False, + exclude_route_prefix: bool = False, +) -> str: + """Get the URL of the application. + + Args: + protocol: The protocol to use for the application. + app_name: The name of the application. + use_localhost: Whether to use localhost instead of the IP address. + Set to True if Serve deployments are not exposed publicly or + for low latency benchmarking. + is_websocket: Whether the url should be served as a websocket. + exclude_route_prefix: The route prefix to exclude from the application. + Returns: + The URL of the application. If there are multiple URLs, a random one is returned. + """ + return random.choice( + get_application_urls( + protocol, app_name, use_localhost, is_websocket, exclude_route_prefix + ) + ) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/thirdparty/__init__.py b/venv/lib/python3.10/site-packages/ray/serve/_private/thirdparty/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/thirdparty/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/thirdparty/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12c3341293cc3d095e8a40e76c8326717c2a4a9e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/thirdparty/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/thirdparty/__pycache__/get_asgi_route_name.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/_private/thirdparty/__pycache__/get_asgi_route_name.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..733414965ec49f160ef0d37ac9cbebc90a1bba53 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/_private/thirdparty/__pycache__/get_asgi_route_name.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/thirdparty/get_asgi_route_name.py b/venv/lib/python3.10/site-packages/ray/serve/_private/thirdparty/get_asgi_route_name.py new file mode 100644 index 0000000000000000000000000000000000000000..1fb2466b78b18b8b9d5744b957bfb3390548389b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/thirdparty/get_asgi_route_name.py @@ -0,0 +1,91 @@ +# This code is adapted from: +# https://github.com/elastic/apm-agent-python/blob/f570e8c2b68a8714628acac815aebcc3518b44c7/elasticapm/contrib/starlette/__init__.py +# +# BSD 3-Clause License +# +# Copyright (c) 2012, the Sentry Team, see AUTHORS for more details +# Copyright (c) 2019, Elasticsearch BV +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + +from typing import List, Optional + +from starlette.routing import Match, Mount, Route +from starlette.types import ASGIApp, Scope + + +def _get_route_name( + scope: Scope, routes: List[Route], *, route_name: Optional[str] = None +) -> Optional[str]: + for route in routes: + match, child_scope = route.matches(scope) + if match == Match.FULL: + route_name = route.path + child_scope = {**scope, **child_scope} + if isinstance(route, Mount) and route.routes: + child_route_name = _get_route_name( + child_scope, route.routes, route_name=route_name + ) + if child_route_name is None: + route_name = None + else: + route_name += child_route_name + return route_name + elif match == Match.PARTIAL and route_name is None: + route_name = route.path + + return None + + +def get_asgi_route_name(app: ASGIApp, scope: Scope) -> Optional[str]: + """Gets route name for given request taking mounts into account.""" + + routes = app.routes + route_name = _get_route_name(scope, routes) + + # Starlette magically redirects requests if the path matches a route name + # with a trailing slash appended or removed. To not spam the transaction + # names list, we do the same here and put these redirects all in the + # same "redirect trailing slashes" transaction name. + if not route_name and app.router.redirect_slashes and scope["path"] != "/": + redirect_scope = dict(scope) + if scope["path"].endswith("/"): + redirect_scope["path"] = scope["path"][:-1] + trim = True + else: + redirect_scope["path"] = scope["path"] + "/" + trim = False + + route_name = _get_route_name(redirect_scope, routes) + if route_name is not None: + route_name = route_name + "/" if trim else route_name[:-1] + + if route_name: + root_path = scope.get("root_path", "") + if root_path: + route_name = root_path.rstrip("/") + "/" + route_name.lstrip("/") + + return route_name diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/usage.py b/venv/lib/python3.10/site-packages/ray/serve/_private/usage.py new file mode 100644 index 0000000000000000000000000000000000000000..b0b53f628c2ccabd0785177668f884a240cf6add --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/usage.py @@ -0,0 +1,50 @@ +from enum import Enum +from typing import Dict, Optional + +from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag + + +class ServeUsageTag(Enum): + API_VERSION = TagKey.SERVE_API_VERSION + NUM_DEPLOYMENTS = TagKey.SERVE_NUM_DEPLOYMENTS + GCS_STORAGE = TagKey.GCS_STORAGE + NUM_GPU_DEPLOYMENTS = TagKey.SERVE_NUM_GPU_DEPLOYMENTS + FASTAPI_USED = TagKey.SERVE_FASTAPI_USED + DAG_DRIVER_USED = TagKey.SERVE_DAG_DRIVER_USED + HTTP_ADAPTER_USED = TagKey.SERVE_HTTP_ADAPTER_USED + GRPC_INGRESS_USED = TagKey.SERVE_GRPC_INGRESS_USED + REST_API_VERSION = TagKey.SERVE_REST_API_VERSION + NUM_APPS = TagKey.SERVE_NUM_APPS + NUM_REPLICAS_LIGHTWEIGHT_UPDATED = TagKey.SERVE_NUM_REPLICAS_LIGHTWEIGHT_UPDATED + USER_CONFIG_LIGHTWEIGHT_UPDATED = TagKey.SERVE_USER_CONFIG_LIGHTWEIGHT_UPDATED + AUTOSCALING_CONFIG_LIGHTWEIGHT_UPDATED = ( + TagKey.SERVE_AUTOSCALING_CONFIG_LIGHTWEIGHT_UPDATED + ) + DEPLOYMENT_HANDLE_API_USED = TagKey.SERVE_DEPLOYMENT_HANDLE_API_USED + DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED = ( + TagKey.SERVE_DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED + ) + MULTIPLEXED_API_USED = TagKey.SERVE_MULTIPLEXED_API_USED + HTTP_PROXY_USED = TagKey.SERVE_HTTP_PROXY_USED + GRPC_PROXY_USED = TagKey.SERVE_GRPC_PROXY_USED + SERVE_STATUS_API_USED = TagKey.SERVE_STATUS_API_USED + SERVE_GET_APP_HANDLE_API_USED = TagKey.SERVE_GET_APP_HANDLE_API_USED + SERVE_GET_DEPLOYMENT_HANDLE_API_USED = TagKey.SERVE_GET_DEPLOYMENT_HANDLE_API_USED + APP_CONTAINER_RUNTIME_ENV_USED = TagKey.SERVE_APP_CONTAINER_RUNTIME_ENV_USED + DEPLOYMENT_CONTAINER_RUNTIME_ENV_USED = ( + TagKey.SERVE_DEPLOYMENT_CONTAINER_RUNTIME_ENV_USED + ) + NUM_NODE_COMPACTIONS = TagKey.SERVE_NUM_NODE_COMPACTIONS + AUTO_NUM_REPLICAS_USED = TagKey.SERVE_AUTO_NUM_REPLICAS_USED + CUSTOM_REQUEST_ROUTER_USED = TagKey.SERVE_CUSTOM_REQUEST_ROUTER_USED + + def record(self, value: str): + """Record telemetry value.""" + record_extra_usage_tag(self.value, value) + + def get_value_from_report(self, report: Dict) -> Optional[str]: + """Returns `None` if the tag isn't in the report.""" + if "extra_usage_tags" not in report: + return None + + return report["extra_usage_tags"].get(TagKey.Name(self.value).lower(), None) diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/utils.py b/venv/lib/python3.10/site-packages/ray/serve/_private/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..40499195435c486b600e38d30b5f67be4627db07 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/utils.py @@ -0,0 +1,739 @@ +import asyncio +import collections +import concurrent.futures +import copy +import importlib +import inspect +import logging +import random +import re +import time +import uuid +from abc import ABC, abstractmethod +from asyncio import coroutines, ensure_future, futures +from decimal import ROUND_HALF_UP, Decimal +from enum import Enum +from functools import wraps +from typing import Any, Callable, Dict, List, Optional, TypeVar, Union + +import requests + +import ray +import ray.util.serialization_addons +from ray._common.utils import get_random_alphanumeric_string, import_attr +from ray._private.resource_spec import HEAD_NODE_RESOURCE_NAME +from ray._private.worker import LOCAL_MODE, SCRIPT_MODE +from ray._raylet import MessagePackSerializer +from ray.actor import ActorHandle +from ray.serve._private.common import RequestMetadata, ServeComponentType +from ray.serve._private.constants import HTTP_PROXY_TIMEOUT, SERVE_LOGGER_NAME +from ray.serve.config import gRPCOptions +from ray.types import ObjectRef +from ray.util.serialization import StandaloneSerializationContext + +try: + import pandas as pd +except ImportError: + pd = None + +try: + import numpy as np +except ImportError: + np = None + +FILE_NAME_REGEX = r"[^\x20-\x7E]|[<>:\"/\\|?*]" + +MESSAGE_PACK_OFFSET = 9 +GENERATOR_COMPOSITION_NOT_SUPPORTED_ERROR = RuntimeError( + "Streaming deployment handle results cannot be passed to " + "downstream handle calls. If you have a use case requiring " + "this feature, please file a feature request on GitHub." +) + + +# Use a global singleton enum to emulate default options. We cannot use None +# for those option because None is a valid new value. +class DEFAULT(Enum): + VALUE = 1 + + +class DeploymentOptionUpdateType(str, Enum): + # Nothing needs to be done other than setting the target state. + LightWeight = "LightWeight" + # Each DeploymentReplica instance (tracked in DeploymentState) uses certain options + # from the deployment config. These values need to be updated in DeploymentReplica. + NeedsReconfigure = "NeedsReconfigure" + # Options that are sent to the replica actor. If changed, reconfigure() on the actor + # needs to be called to update these values. + NeedsActorReconfigure = "NeedsActorReconfigure" + # If changed, restart all replicas. + HeavyWeight = "HeavyWeight" + + +# Type alias: objects that can be DEFAULT.VALUE have type Default[T] +T = TypeVar("T") +Default = Union[DEFAULT, T] + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +# Format for component files +FILE_FMT = "{component_name}_{component_id}{suffix}" + + +class _ServeCustomEncoders: + """Group of custom encoders for common types that's not handled by FastAPI.""" + + @staticmethod + def encode_np_array(obj): + assert isinstance(obj, np.ndarray) + if obj.dtype.kind == "f": # floats + obj = obj.astype(float) + if obj.dtype.kind in {"i", "u"}: # signed and unsigned integers. + obj = obj.astype(int) + return obj.tolist() + + @staticmethod + def encode_np_scaler(obj): + assert isinstance(obj, np.generic) + return obj.item() + + @staticmethod + def encode_exception(obj): + assert isinstance(obj, Exception) + return str(obj) + + @staticmethod + def encode_pandas_dataframe(obj): + assert isinstance(obj, pd.DataFrame) + return obj.to_dict(orient="records") + + +serve_encoders = {Exception: _ServeCustomEncoders.encode_exception} + +if np is not None: + serve_encoders[np.ndarray] = _ServeCustomEncoders.encode_np_array + serve_encoders[np.generic] = _ServeCustomEncoders.encode_np_scaler + +if pd is not None: + serve_encoders[pd.DataFrame] = _ServeCustomEncoders.encode_pandas_dataframe + + +@ray.remote(num_cpus=0) +def block_until_http_ready( + http_endpoint, + backoff_time_s=1, + check_ready=None, + timeout=HTTP_PROXY_TIMEOUT, +): + http_is_ready = False + start_time = time.time() + + while not http_is_ready: + try: + resp = requests.get(http_endpoint) + assert resp.status_code == 200 + if check_ready is None: + http_is_ready = True + else: + http_is_ready = check_ready(resp) + except Exception: + pass + + if 0 < timeout < time.time() - start_time: + raise TimeoutError("HTTP proxy not ready after {} seconds.".format(timeout)) + + time.sleep(backoff_time_s) + + +def get_random_string(length: int = 8): + return get_random_alphanumeric_string(length) + + +def format_actor_name(actor_name, *modifiers): + name = actor_name + for modifier in modifiers: + name += "-{}".format(modifier) + + return name + + +def ensure_serialization_context(): + """Ensure the serialization addons on registered, even when Ray has not + been started.""" + ctx = StandaloneSerializationContext() + ray.util.serialization_addons.apply(ctx) + + +def msgpack_serialize(obj): + ctx = ray._private.worker.global_worker.get_serialization_context() + buffer = ctx.serialize(obj) + serialized = buffer.to_bytes() + return serialized + + +def msgpack_deserialize(data): + # todo: Ray does not provide a msgpack deserialization api. + try: + obj = MessagePackSerializer.loads(data[MESSAGE_PACK_OFFSET:], None) + except Exception: + raise + return obj + + +def merge_dict(dict1, dict2): + if dict1 is None and dict2 is None: + return None + if dict1 is None: + dict1 = dict() + if dict2 is None: + dict2 = dict() + result = dict() + for key in dict1.keys() | dict2.keys(): + result[key] = sum([e.get(key, 0) for e in (dict1, dict2)]) + return result + + +def parse_import_path(import_path: str): + """ + Takes in an import_path of form: + + [subdirectory 1].[subdir 2]...[subdir n].[file name].[attribute name] + + Parses this path and returns the module name (everything before the last + dot) and attribute name (everything after the last dot), such that the + attribute can be imported using "from module_name import attr_name". + """ + + nodes = import_path.split(".") + if len(nodes) < 2: + raise ValueError( + f"Got {import_path} as import path. The import path " + f"should at least specify the file name and " + f"attribute name connected by a dot." + ) + + return ".".join(nodes[:-1]), nodes[-1] + + +def override_runtime_envs_except_env_vars(parent_env: Dict, child_env: Dict) -> Dict: + """Creates a runtime_env dict by merging a parent and child environment. + + This method is not destructive. It leaves the parent and child envs + the same. + + The merge is a shallow update where the child environment inherits the + parent environment's settings. If the child environment specifies any + env settings, those settings take precdence over the parent. + - Note: env_vars are a special case. The child's env_vars are combined + with the parent. + + Args: + parent_env: The environment to inherit settings from. + child_env: The environment with override settings. + + Returns: A new dictionary containing the merged runtime_env settings. + + Raises: + TypeError: If a dictionary is not passed in for parent_env or child_env. + """ + + if not isinstance(parent_env, Dict): + raise TypeError( + f'Got unexpected type "{type(parent_env)}" for parent_env. ' + "parent_env must be a dictionary." + ) + if not isinstance(child_env, Dict): + raise TypeError( + f'Got unexpected type "{type(child_env)}" for child_env. ' + "child_env must be a dictionary." + ) + + defaults = copy.deepcopy(parent_env) + overrides = copy.deepcopy(child_env) + + default_env_vars = defaults.get("env_vars", {}) + override_env_vars = overrides.get("env_vars", {}) + + defaults.update(overrides) + default_env_vars.update(override_env_vars) + + defaults["env_vars"] = default_env_vars + + return defaults + + +class JavaActorHandleProxy: + """Wraps actor handle and translate snake_case to camelCase.""" + + def __init__(self, handle: ActorHandle): + self.handle = handle + self._available_attrs = set(dir(self.handle)) + + def __getattr__(self, key: str): + if key in self._available_attrs: + camel_case_key = key + else: + components = key.split("_") + camel_case_key = components[0] + "".join(x.title() for x in components[1:]) + return getattr(self.handle, camel_case_key) + + +def require_packages(packages: List[str]): + """Decorator making sure function run in specified environments + + Examples: + >>> from ray.serve._private.utils import require_packages + >>> @require_packages(["numpy", "package_a"]) # doctest: +SKIP + ... def func(): # doctest: +SKIP + ... import numpy as np # doctest: +SKIP + ... ... # doctest: +SKIP + >>> func() # doctest: +SKIP + ImportError: func requires ["numpy", "package_a"] but + ["package_a"] are not available, please pip install them. + """ + + def decorator(func): + def check_import_once(): + if not hasattr(func, "_require_packages_checked"): + missing_packages = [] + for package in packages: + try: + importlib.import_module(package) + except ModuleNotFoundError: + missing_packages.append(package) + if len(missing_packages) > 0: + raise ImportError( + f"{func} requires packages {packages} to run but " + f"{missing_packages} are missing. Please " + "`pip install` them or add them to " + "`runtime_env`." + ) + func._require_packages_checked = True + + if inspect.iscoroutinefunction(func): + + @wraps(func) + async def wrapped(*args, **kwargs): + check_import_once() + return await func(*args, **kwargs) + + elif inspect.isroutine(func): + + @wraps(func) + def wrapped(*args, **kwargs): + check_import_once() + return func(*args, **kwargs) + + else: + raise ValueError("Decorator expect callable functions.") + + return wrapped + + return decorator + + +def in_interactive_shell(): + # Taken from: + # https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook + import __main__ as main + + return not hasattr(main, "__file__") + + +def snake_to_camel_case(snake_str: str) -> str: + """Convert a snake case string to camel case.""" + + words = snake_str.strip("_").split("_") + return words[0] + "".join(word[:1].upper() + word[1:] for word in words[1:]) + + +def check_obj_ref_ready_nowait(obj_ref: ObjectRef) -> bool: + """Check if ray object reference is ready without waiting for it.""" + finished, _ = ray.wait([obj_ref], timeout=0) + return len(finished) == 1 + + +def extract_self_if_method_call(args: List[Any], func: Callable) -> Optional[object]: + """Check if this is a method rather than a function. + + Does this by checking to see if `func` is the attribute of the first + (`self`) argument under `func.__name__`. Unfortunately, this is the most + robust solution to this I was able to find. It would also be preferable + to do this check when the decorator runs, rather than when the method is. + + Returns the `self` object if it's a method call, else None. + + Arguments: + args: arguments to the function/method call. + func: the unbound function that was called. + """ + if len(args) > 0: + method = getattr(args[0], func.__name__, False) + if method: + wrapped = getattr(method, "__wrapped__", False) + if wrapped and wrapped == func: + return args[0] + + return None + + +def call_function_from_import_path(import_path: str) -> Any: + """Call the function given import path. + + Args: + import_path: The import path of the function to call. + Raises: + ValueError: If the import path is invalid. + TypeError: If the import path is not callable. + RuntimeError: if the function raise exeception during execution. + Returns: + The result of the function call. + """ + try: + callback_func = import_attr(import_path) + except Exception as e: + raise ValueError(f"The import path {import_path} cannot be imported: {e}") + + if not callable(callback_func): + raise TypeError(f"The import path {import_path} is not callable.") + + try: + return callback_func() + except Exception as e: + raise RuntimeError(f"The function {import_path} raised an exception: {e}") + + +def get_head_node_id() -> str: + """Get the head node id. + + Iterate through all nodes in the ray cluster and return the node id of the first + alive node with head node resource. + """ + head_node_id = None + for node in ray.nodes(): + if HEAD_NODE_RESOURCE_NAME in node["Resources"] and node["Alive"]: + head_node_id = node["NodeID"] + break + assert head_node_id is not None, "Cannot find alive head node." + + return head_node_id + + +def calculate_remaining_timeout( + *, + timeout_s: Optional[float], + start_time_s: float, + curr_time_s: float, +) -> Optional[float]: + """Get the timeout remaining given an overall timeout, start time, and curr time. + + If the timeout passed in was `None` or negative, will always return that timeout + directly. + + If the timeout is >= 0, the returned remaining timeout always be >= 0. + """ + if timeout_s is None or timeout_s < 0: + return timeout_s + + time_since_start_s = curr_time_s - start_time_s + return max(0, timeout_s - time_since_start_s) + + +def get_all_live_placement_group_names() -> List[str]: + """Fetch and parse the Ray placement group table for live placement group names. + + Placement groups are filtered based on their `scheduling_state`; any placement + group not in the "REMOVED" state is considered live. + """ + placement_group_table = ray.util.placement_group_table() + + live_pg_names = [] + for entry in placement_group_table.values(): + pg_name = entry.get("name", "") + if ( + pg_name + and entry.get("stats", {}).get("scheduling_state", "UNKNOWN") != "REMOVED" + ): + live_pg_names.append(pg_name) + + return live_pg_names + + +def get_current_actor_id() -> str: + """Gets the ID of the calling actor. + + If this is called in a driver, returns "DRIVER." + + If otherwise called outside of an actor, returns an empty string. + + This function hangs when GCS is down due to the `ray.get_runtime_context()` + call. + """ + + worker_mode = ray.get_runtime_context().worker.mode + if worker_mode in {SCRIPT_MODE, LOCAL_MODE}: + return "DRIVER" + else: + try: + actor_id = ray.get_runtime_context().get_actor_id() + if actor_id is None: + return "" + else: + return actor_id + except Exception: + return "" + + +def is_running_in_asyncio_loop() -> bool: + try: + asyncio.get_running_loop() + return True + except RuntimeError: + return False + + +class TimerBase(ABC): + @abstractmethod + def time(self) -> float: + """Return the current time.""" + raise NotImplementedError + + +class Timer(TimerBase): + def time(self) -> float: + return time.time() + + +def get_capacity_adjusted_num_replicas( + num_replicas: int, target_capacity: Optional[float] +) -> int: + """Return the `num_replicas` adjusted by the `target_capacity`. + + The output will only ever be 0 if `target_capacity` is 0 or `num_replicas` is + 0 (to support autoscaling deployments using scale-to-zero). + + Rather than using the default `round` behavior in Python, which rounds half to + even, uses the `decimal` module to round half up (standard rounding behavior). + """ + if target_capacity is None or target_capacity == 100: + return num_replicas + + if target_capacity == 0 or num_replicas == 0: + return 0 + + adjusted_num_replicas = Decimal(num_replicas * target_capacity) / Decimal(100.0) + rounded_adjusted_num_replicas = adjusted_num_replicas.to_integral_value( + rounding=ROUND_HALF_UP + ) + return max(1, int(rounded_adjusted_num_replicas)) + + +def generate_request_id() -> str: + # NOTE(edoakes): we use random.getrandbits because it reduces CPU overhead + # significantly. This is less cryptographically secure but should be ok for + # request ID generation. + # See https://bugs.python.org/issue45556 for discussion. + return str(uuid.UUID(int=random.getrandbits(128), version=4)) + + +def inside_ray_client_context() -> bool: + return ray.util.client.ray.is_connected() + + +def get_component_file_name( + component_name: str, + component_id: str, + component_type: Optional[ServeComponentType], + suffix: str = "", +) -> str: + """Get the component's file name. Replaces special characters with underscores.""" + component_name = re.sub(FILE_NAME_REGEX, "_", component_name) + + # For DEPLOYMENT component type, we want to log the deployment name + # instead of adding the component type to the component name. + component_log_file_name = component_name + if component_type is not None: + component_log_file_name = f"{component_type.value}_{component_name}" + if component_type != ServeComponentType.REPLICA: + component_name = f"{component_type}_{component_name}" + file_name = FILE_FMT.format( + component_name=component_log_file_name, + component_id=component_id, + suffix=suffix, + ) + return file_name + + +def validate_route_prefix(route_prefix: Union[DEFAULT, None, str]): + if route_prefix is DEFAULT.VALUE or route_prefix is None: + return + + if not route_prefix.startswith("/"): + raise ValueError( + f"Invalid route_prefix '{route_prefix}', " + "must start with a forward slash ('/')." + ) + + if route_prefix != "/" and route_prefix.endswith("/"): + raise ValueError( + f"Invalid route_prefix '{route_prefix}', " + "may not end with a trailing '/'." + ) + + if "{" in route_prefix or "}" in route_prefix: + raise ValueError( + f"Invalid route_prefix '{route_prefix}', may not contain wildcards." + ) + + +async def resolve_deployment_response(obj: Any, request_metadata: RequestMetadata): + """Resolve `DeploymentResponse` objects to underlying object references. + + This enables composition without explicitly calling `_to_object_ref`. + """ + from ray.serve.handle import DeploymentResponse, DeploymentResponseGenerator + + if isinstance(obj, DeploymentResponseGenerator): + raise GENERATOR_COMPOSITION_NOT_SUPPORTED_ERROR + elif isinstance(obj, DeploymentResponse): + # Launch async task to convert DeploymentResponse to an object ref + return asyncio.create_task(obj._to_object_ref()) + + +def wait_for_interrupt() -> None: + try: + while True: + # Block, letting Ray print logs to the terminal. + time.sleep(10) + except KeyboardInterrupt: + logger.warning("Got KeyboardInterrupt, exiting...") + # We need to re-raise KeyboardInterrupt, so serve components can be shutdown + # from the main script. + raise + + +def is_grpc_enabled(grpc_config: gRPCOptions) -> bool: + return grpc_config.port > 0 and len(grpc_config.grpc_servicer_functions) > 0 + + +def run_coroutine_or_future_threadsafe(coro_or_future, loop): + """Submit a coroutine object or future to a given event loop. + + Ref: https://github.com/python/cpython/blob/eef49c359505eaf109d519d39e53dfd3c78d066a/Lib/asyncio/tasks.py#L991 + + Return a concurrent.futures.Future to access the result. + """ + if not coroutines.iscoroutine(coro_or_future) and not futures.isfuture( + coro_or_future + ): + raise TypeError("A coroutine object or future is required") + + if futures.isfuture(coro_or_future): + assert loop == coro_or_future.get_loop() + + future = concurrent.futures.Future() + + def callback(): + try: + futures._chain_future(ensure_future(coro_or_future, loop=loop), future) + except (SystemExit, KeyboardInterrupt): + raise + except BaseException as exc: + if future.set_running_or_notify_cancel(): + future.set_exception(exc) + raise + + loop.call_soon_threadsafe(callback) + return future + + +class Semaphore: + """Based on asyncio.Semaphore. + + This is a semaphore that can be used to limit the number of concurrent requests. + Its maximum value is dynamic and is determined by the `get_value_fn` function. + """ + + def __init__(self, get_value_fn: Callable[[], int]): + self._waiters = None + self._value = 0 + self._get_value_fn = get_value_fn + + def __repr__(self): + res = super().__repr__() + extra = "locked" if self.locked() else f"unlocked, value:{self._value}" + if self._waiters: + extra = f"{extra}, waiters:{len(self._waiters)}" + return f"<{res[1:-1]} [{extra}]>" + + async def __aenter__(self): + await self.acquire() + # We have no use for the "as ..." clause in the with + # statement for locks. + return None + + async def __aexit__(self, exc_type, exc, tb): + self.release() + + def get_max_value(self): + return self._get_value_fn() + + def locked(self): + """Returns True if semaphore cannot be acquired immediately.""" + return self._value >= self.get_max_value() or ( + any(not w.cancelled() for w in (self._waiters or ())) + ) + + async def acquire(self): + """Acquire a semaphore. + If the internal counter is larger than zero on entry, + decrement it by one and return True immediately. If it is + zero on entry, block, waiting until some other coroutine has + called release() to make it larger than 0, and then return + True. + """ + if not self.locked(): + self._value += 1 + return True + + if self._waiters is None: + self._waiters = collections.deque() + fut = asyncio.Future() + self._waiters.append(fut) + + # Finally block should be called before the CancelledError + # handling as we don't want CancelledError to call + # _wake_up_first() and attempt to wake up itself. + try: + try: + await fut + finally: + self._waiters.remove(fut) + except asyncio.CancelledError: + if not fut.cancelled(): + self._value -= 1 + self._wake_up_next() + raise + + if self._value > 0: + self._wake_up_next() + return True + + def release(self): + """Release a semaphore, incrementing the internal counter by one. + When it was zero on entry and another coroutine is waiting for it to + become larger than zero again, wake up that coroutine. + """ + self._value -= 1 + self._wake_up_next() + + def _wake_up_next(self): + """Wake up the first waiter that isn't done.""" + if not self._waiters: + return + + for fut in self._waiters: + if not fut.done(): + self._value += 1 + fut.set_result(True) + return diff --git a/venv/lib/python3.10/site-packages/ray/serve/_private/version.py b/venv/lib/python3.10/site-packages/ray/serve/_private/version.py new file mode 100644 index 0000000000000000000000000000000000000000..9242dfc928e968b0b3ab305e79ae3bc7f7c7556b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/_private/version.py @@ -0,0 +1,207 @@ +import json +import logging +from copy import deepcopy +from typing import Any, Dict, List, Optional +from zlib import crc32 + +from ray._common.pydantic_compat import BaseModel +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.utils import DeploymentOptionUpdateType, get_random_string +from ray.serve.config import AutoscalingConfig +from ray.serve.generated.serve_pb2 import DeploymentVersion as DeploymentVersionProto + +logger = logging.getLogger("ray.serve") + + +class DeploymentVersion: + def __init__( + self, + code_version: Optional[str], + deployment_config: DeploymentConfig, + ray_actor_options: Optional[Dict], + placement_group_bundles: Optional[List[Dict[str, float]]] = None, + placement_group_strategy: Optional[str] = None, + max_replicas_per_node: Optional[int] = None, + ): + if code_version is not None and not isinstance(code_version, str): + raise TypeError(f"code_version must be str, got {type(code_version)}.") + if code_version is None: + self.code_version = get_random_string() + else: + self.code_version = code_version + + # Options for this field may be mutated over time, so any logic that uses this + # should access this field directly. + self.deployment_config = deployment_config + self.ray_actor_options = ray_actor_options + self.placement_group_bundles = placement_group_bundles + self.placement_group_strategy = placement_group_strategy + self.max_replicas_per_node = max_replicas_per_node + self.compute_hashes() + + @classmethod + def from_deployment_version(cls, deployment_version, deployment_config): + version_copy = deepcopy(deployment_version) + version_copy.deployment_config = deployment_config + version_copy.compute_hashes() + return version_copy + + def __hash__(self) -> int: + return self._hash + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DeploymentVersion): + return False + return self._hash == other._hash + + def requires_actor_restart(self, new_version): + """Determines whether the new version requires actors of the current version to + be restarted. + """ + return ( + self.code_version != new_version.code_version + or self.ray_actor_options_hash != new_version.ray_actor_options_hash + or self.placement_group_options_hash + != new_version.placement_group_options_hash + or self.max_replicas_per_node != new_version.max_replicas_per_node + ) + + def requires_actor_reconfigure(self, new_version): + """Determines whether the new version requires calling reconfigure() on the + replica actor. + """ + return self.reconfigure_actor_hash != new_version.reconfigure_actor_hash + + def requires_long_poll_broadcast(self, new_version): + """Determines whether lightweightly updating an existing replica to the new + version requires broadcasting through long poll that the running replicas has + changed. + """ + return ( + self.deployment_config.max_ongoing_requests + != new_version.deployment_config.max_ongoing_requests + ) + + def compute_hashes(self): + # If these change, the controller will rolling upgrade existing replicas. + serialized_ray_actor_options = _serialize(self.ray_actor_options or {}) + self.ray_actor_options_hash = crc32(serialized_ray_actor_options) + combined_placement_group_options = {} + if self.placement_group_bundles is not None: + combined_placement_group_options["bundles"] = self.placement_group_bundles + if self.placement_group_strategy is not None: + combined_placement_group_options["strategy"] = self.placement_group_strategy + serialized_placement_group_options = _serialize( + combined_placement_group_options + ) + self.placement_group_options_hash = crc32(serialized_placement_group_options) + + # If this changes, DeploymentReplica.reconfigure() will call reconfigure on the + # actual replica actor + self.reconfigure_actor_hash = crc32( + self._get_serialized_options( + [DeploymentOptionUpdateType.NeedsActorReconfigure] + ) + ) + + # Used by __eq__ in deployment state to either reconfigure the replicas or + # stop and restart them + self._hash = crc32( + self.code_version.encode("utf-8") + + serialized_ray_actor_options + + serialized_placement_group_options + + str(self.max_replicas_per_node).encode("utf-8") + + self._get_serialized_options( + [ + DeploymentOptionUpdateType.NeedsReconfigure, + DeploymentOptionUpdateType.NeedsActorReconfigure, + ] + ) + ) + + def to_proto(self) -> bytes: + # TODO(simon): enable cross language user config + return DeploymentVersionProto( + code_version=self.code_version, + deployment_config=self.deployment_config.to_proto(), + ray_actor_options=json.dumps(self.ray_actor_options), + placement_group_bundles=json.dumps(self.placement_group_bundles) + if self.placement_group_bundles is not None + else "", + placement_group_strategy=self.placement_group_strategy + if self.placement_group_strategy is not None + else "", + max_replicas_per_node=self.max_replicas_per_node + if self.max_replicas_per_node is not None + else 0, + ) + + @classmethod + def from_proto(cls, proto: DeploymentVersionProto): + return DeploymentVersion( + proto.code_version, + DeploymentConfig.from_proto(proto.deployment_config), + json.loads(proto.ray_actor_options), + placement_group_bundles=( + json.loads(proto.placement_group_bundles) + if proto.placement_group_bundles + else None + ), + placement_group_version=( + proto.placement_group_version if proto.placement_group_version else None + ), + max_replicas_per_node=( + proto.max_replicas_per_node if proto.max_replicas_per_node else None + ), + ) + + def _get_serialized_options( + self, update_types: List[DeploymentOptionUpdateType] + ) -> bytes: + """Returns a serialized dictionary containing fields of a deployment config that + should prompt a deployment version update. + """ + reconfigure_dict = {} + # TODO(aguo): Once we only support pydantic 2, we can remove this if check. + # In pydantic 2.0, `__fields__` has been renamed to `model_fields`. + fields = ( + self.deployment_config.model_fields + if hasattr(self.deployment_config, "model_fields") + else self.deployment_config.__fields__ + ) + for option_name, field in fields.items(): + option_weight = field.field_info.extra.get("update_type") + if option_weight in update_types: + reconfigure_dict[option_name] = getattr( + self.deployment_config, option_name + ) + # If autoscaling config was changed, only broadcast to + # replicas if metrics_interval_s or look_back_period_s + # was changed, because the rest of the fields are only + # used in deployment state manager + if isinstance(reconfigure_dict[option_name], AutoscalingConfig): + reconfigure_dict[option_name] = reconfigure_dict[option_name].dict( + include={"metrics_interval_s", "look_back_period_s"} + ) + elif isinstance(reconfigure_dict[option_name], BaseModel): + reconfigure_dict[option_name] = reconfigure_dict[option_name].dict() + + # Can't serialize bytes. The request router class is already + # included in the serialized config as request_router_class. + if "request_router_config" in reconfigure_dict: + reconfigure_dict["request_router_config"].pop( + "_serialized_request_router_cls", None + ) + + if ( + isinstance(self.deployment_config.user_config, bytes) + and "user_config" in reconfigure_dict + ): + del reconfigure_dict["user_config"] + return self.deployment_config.user_config + _serialize(reconfigure_dict) + + return _serialize(reconfigure_dict) + + +def _serialize(json_object): + return str.encode(json.dumps(json_object, sort_keys=True)) diff --git a/venv/lib/python3.10/site-packages/ray/serve/api.py b/venv/lib/python3.10/site-packages/ray/serve/api.py new file mode 100644 index 0000000000000000000000000000000000000000..865d5cedbba1b5aedce1225a517958ad5c18cbb8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/api.py @@ -0,0 +1,1057 @@ +import collections +import inspect +import logging +from functools import wraps +from typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union + +from attr import dataclass +from fastapi import APIRouter, FastAPI +from starlette.types import ASGIApp + +import ray +from ray import cloudpickle +from ray._private.serialization import pickle_dumps +from ray.serve._private.build_app import build_app +from ray.serve._private.config import ( + DeploymentConfig, + ReplicaConfig, + handle_num_replicas_auto, +) +from ray.serve._private.constants import ( + RAY_SERVE_FORCE_LOCAL_TESTING_MODE, + SERVE_DEFAULT_APP_NAME, + SERVE_LOGGER_NAME, +) +from ray.serve._private.http_util import ( + ASGIAppReplicaWrapper, + make_fastapi_class_based_view, +) +from ray.serve._private.local_testing_mode import make_local_deployment_handle +from ray.serve._private.logging_utils import configure_component_logger +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + DEFAULT, + Default, + ensure_serialization_context, + extract_self_if_method_call, + validate_route_prefix, + wait_for_interrupt, +) +from ray.serve.config import ( + AutoscalingConfig, + DeploymentMode, + HTTPOptions, + ProxyLocation, + RequestRouterConfig, + gRPCOptions, +) +from ray.serve.context import ( + ReplicaContext, + _get_global_client, + _get_internal_replica_context, + _set_global_client, +) +from ray.serve.deployment import Application, Deployment +from ray.serve.exceptions import RayServeException +from ray.serve.handle import DeploymentHandle +from ray.serve.multiplex import _ModelMultiplexWrapper +from ray.serve.schema import LoggingConfig, ServeInstanceDetails, ServeStatus +from ray.util.annotations import DeveloperAPI, PublicAPI + +from ray.serve._private import api as _private_api # isort:skip + + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@PublicAPI(stability="stable") +def start( + proxy_location: Union[None, str, ProxyLocation] = None, + http_options: Union[None, dict, HTTPOptions] = None, + grpc_options: Union[None, dict, gRPCOptions] = None, + logging_config: Union[None, dict, LoggingConfig] = None, + **kwargs, +): + """Start Serve on the cluster. + + Used to set cluster-scoped configurations such as HTTP options. In most cases, this + does not need to be called manually and Serve will be started when an application is + first deployed to the cluster. + + These cluster-scoped options cannot be updated dynamically. To update them, start a + new cluster or shut down Serve on the cluster and start it again. + + These options can also be set in the config file deployed via REST API. + + Args: + proxy_location: Where to run proxies that handle ingress traffic to the + cluster (defaults to every node in the cluster with at least one replica on + it). See `ProxyLocation` for supported options. + http_options: HTTP config options for the proxies. These can be passed as an + unstructured dictionary or the structured `HTTPOptions` class. See + `HTTPOptions` for supported options. + grpc_options: [EXPERIMENTAL] gRPC config options for the proxies. These can + be passed as an unstructured dictionary or the structured `gRPCOptions` + class See `gRPCOptions` for supported options. + logging_config: logging config options for the serve component ( + controller & proxy). + """ + if proxy_location is None: + if http_options is None: + http_options = HTTPOptions(location=DeploymentMode.EveryNode) + else: + if http_options is None: + http_options = HTTPOptions() + elif isinstance(http_options, dict): + http_options = HTTPOptions(**http_options) + + if isinstance(proxy_location, str): + proxy_location = ProxyLocation(proxy_location) + + http_options.location = ProxyLocation._to_deployment_mode(proxy_location) + + _private_api.serve_start( + http_options=http_options, + grpc_options=grpc_options, + global_logging_config=logging_config, + **kwargs, + ) + + +@PublicAPI(stability="stable") +def shutdown(): + """Completely shut down Serve on the cluster. + + Deletes all applications and shuts down Serve system actors. + """ + + try: + client = _get_global_client() + except RayServeException: + logger.info( + "Nothing to shut down. There's no Serve application " + "running on this Ray cluster." + ) + return + + client.shutdown() + _set_global_client(None) + + +@DeveloperAPI +def get_replica_context() -> ReplicaContext: + """Returns the deployment and replica tag from within a replica at runtime. + + A replica tag uniquely identifies a single replica for a Ray Serve + deployment. + + Raises: + RayServeException: if not called from within a Ray Serve deployment. + + Example: + + .. code-block:: python + + from ray import serve + @serve.deployment + class MyDeployment: + def __init__(self): + # Prints "MyDeployment" + print(serve.get_replica_context().deployment) + + """ + internal_replica_context = _get_internal_replica_context() + if internal_replica_context is None: + raise RayServeException( + "`serve.get_replica_context()` " + "may only be called from within a " + "Ray Serve deployment." + ) + return internal_replica_context + + +@PublicAPI(stability="stable") +def ingress(app: Union[ASGIApp, Callable]) -> Callable: + """Wrap a deployment class with an ASGI application for HTTP request parsing. + There are a few different ways to use this functionality. + + Example: + + FastAPI app routes are defined inside the deployment class. + + .. code-block:: python + + from ray import serve + from fastapi import FastAPI + + app = FastAPI() + + @serve.deployment + @serve.ingress(app) + class MyFastAPIDeployment: + @app.get("/hi") + def say_hi(self) -> str: + return "Hello world!" + + app = MyFastAPIDeployment.bind() + + You can also use a standalone FastAPI app without registering + routes inside the deployment. + + .. code-block:: python + + from ray import serve + from fastapi import FastAPI + + app = FastAPI() + + @app.get("/hi") + def say_hi(): + return "Hello world!" + + deployment = serve.deployment(serve.ingress(app)()) + app = deployment.bind() + + You can also pass in a builder function that returns an ASGI app. + The builder function is evaluated when the deployment is initialized on + replicas. This example shows how to use a sub-deployment inside the routes + defined outside the deployment class. + + .. code-block:: python + + from ray import serve + + @serve.deployment + class SubDeployment: + def __call__(self): + return "Hello world!" + + def build_asgi_app(): + from fastapi import FastAPI + + app = FastAPI() + + def get_sub_deployment_handle(): + return serve.get_deployment_handle(SubDeployment.name, app_name="my_app") + + @app.get("/hi") + async def say_hi(handle: Depends(get_sub_deployment_handle)): + return await handle.remote() + + return app + + deployment = serve.deployment(serve.ingress(build_asgi_app)()) + app = deployment.bind(SubDeployment.bind(), name="my_app", route_prefix="/") + + Args: + app: the FastAPI app to wrap this class with. + Can be any ASGI-compatible callable. + You can also pass in a builder function that returns an ASGI app. + """ + + def decorator(cls: Optional[Type[Any]] = None) -> Callable: + if cls is None: + + class ASGIIngressDeployment: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + + cls = ASGIIngressDeployment + + if not inspect.isclass(cls): + raise ValueError("@serve.ingress must be used with a class.") + if issubclass(cls, collections.abc.Callable): + raise ValueError( + "Classes passed to @serve.ingress may not have __call__ method." + ) + + # Sometimes there are decorators on the methods. We want to fix + # the fast api routes here. + if isinstance(app, (FastAPI, APIRouter)): + make_fastapi_class_based_view(app, cls) + + frozen_app_or_func: Union[ASGIApp, Callable] = None + + if inspect.isfunction(app): + frozen_app_or_func = app + else: + # Free the state of the app so subsequent modification won't affect + # this ingress deployment. We don't use copy.copy here to avoid + # recursion issue. + ensure_serialization_context() + frozen_app_or_func = cloudpickle.loads( + pickle_dumps(app, error_msg="Failed to serialize the ASGI app.") + ) + + class ASGIIngressWrapper(cls, ASGIAppReplicaWrapper): + def __init__(self, *args, **kwargs): + # Call user-defined constructor. + cls.__init__(self, *args, **kwargs) + + ServeUsageTag.FASTAPI_USED.record("1") + ASGIAppReplicaWrapper.__init__(self, frozen_app_or_func) + + async def __del__(self): + await ASGIAppReplicaWrapper.__del__(self) + + # Call user-defined destructor if defined. + if hasattr(cls, "__del__"): + if inspect.iscoroutinefunction(cls.__del__): + await cls.__del__(self) + else: + cls.__del__(self) + + ASGIIngressWrapper.__name__ = cls.__name__ + if hasattr(frozen_app_or_func, "docs_url"): + # TODO (abrar): fastapi apps instantiated by builder function will set + # the docs path on application state via the replica. + # This split in logic is not desirable, we should consolidate the two. + ASGIIngressWrapper.__fastapi_docs_path__ = frozen_app_or_func.docs_url + + return ASGIIngressWrapper + + return decorator + + +@PublicAPI(stability="stable") +def deployment( + _func_or_class: Optional[Callable] = None, + name: Default[str] = DEFAULT.VALUE, + version: Default[str] = DEFAULT.VALUE, + num_replicas: Default[Optional[Union[int, str]]] = DEFAULT.VALUE, + route_prefix: Default[Union[str, None]] = DEFAULT.VALUE, + ray_actor_options: Default[Dict] = DEFAULT.VALUE, + placement_group_bundles: Default[List[Dict[str, float]]] = DEFAULT.VALUE, + placement_group_strategy: Default[str] = DEFAULT.VALUE, + max_replicas_per_node: Default[int] = DEFAULT.VALUE, + user_config: Default[Optional[Any]] = DEFAULT.VALUE, + max_ongoing_requests: Default[int] = DEFAULT.VALUE, + max_queued_requests: Default[int] = DEFAULT.VALUE, + autoscaling_config: Default[Union[Dict, AutoscalingConfig, None]] = DEFAULT.VALUE, + graceful_shutdown_wait_loop_s: Default[float] = DEFAULT.VALUE, + graceful_shutdown_timeout_s: Default[float] = DEFAULT.VALUE, + health_check_period_s: Default[float] = DEFAULT.VALUE, + health_check_timeout_s: Default[float] = DEFAULT.VALUE, + logging_config: Default[Union[Dict, LoggingConfig, None]] = DEFAULT.VALUE, + request_router_config: Default[ + Union[Dict, RequestRouterConfig, None] + ] = DEFAULT.VALUE, +) -> Callable[[Callable], Deployment]: + """Decorator that converts a Python class to a `Deployment`. + + Example: + + .. code-block:: python + + from ray import serve + + @serve.deployment(num_replicas=2) + class MyDeployment: + pass + + app = MyDeployment.bind() + + Args: + _func_or_class: The class or function to be decorated. + name: Name uniquely identifying this deployment within the application. + If not provided, the name of the class or function is used. + version: Version of the deployment. Deprecated. + num_replicas: Number of replicas to run that handle requests to + this deployment. Defaults to 1. + route_prefix: Route prefix for HTTP requests. Defaults to '/'. Deprecated. + ray_actor_options: Options to pass to the Ray Actor decorator, such as + resource requirements. Valid options are: `accelerator_type`, `memory`, + `num_cpus`, `num_gpus`, `resources`, and `runtime_env`. + placement_group_bundles: Defines a set of placement group bundles to be + scheduled *for each replica* of this deployment. The replica actor will + be scheduled in the first bundle provided, so the resources specified in + `ray_actor_options` must be a subset of the first bundle's resources. All + actors and tasks created by the replica actor will be scheduled in the + placement group by default (`placement_group_capture_child_tasks` is set + to True). + This cannot be set together with max_replicas_per_node. + placement_group_strategy: Strategy to use for the replica placement group + specified via `placement_group_bundles`. Defaults to `PACK`. + max_replicas_per_node: The max number of replicas of this deployment that can + run on a single node. Valid values are None (default, no limit) + or an integer in the range of [1, 100]. + This cannot be set together with placement_group_bundles. + user_config: Config to pass to the reconfigure method of the deployment. This + can be updated dynamically without restarting the replicas of the + deployment. The user_config must be fully JSON-serializable. + max_ongoing_requests: Maximum number of requests that are sent to a + replica of this deployment without receiving a response. Defaults to 5. + max_queued_requests: [EXPERIMENTAL] Maximum number of requests to this + deployment that will be queued at each *caller* (proxy or DeploymentHandle). + Once this limit is reached, subsequent requests will raise a + BackPressureError (for handles) or return an HTTP 503 status code (for HTTP + requests). Defaults to -1 (no limit). + autoscaling_config: Parameters to configure autoscaling behavior. If this + is set, `num_replicas` should be "auto" or not set. + graceful_shutdown_wait_loop_s: Duration that replicas wait until there is + no more work to be done before shutting down. Defaults to 2s. + graceful_shutdown_timeout_s: Duration to wait for a replica to gracefully + shut down before being forcefully killed. Defaults to 20s. + health_check_period_s: Duration between health check calls for the replica. + Defaults to 10s. The health check is by default a no-op Actor call to the + replica, but you can define your own health check using the "check_health" + method in your deployment that raises an exception when unhealthy. + health_check_timeout_s: Duration in seconds, that replicas wait for a health + check method to return before considering it as failed. Defaults to 30s. + logging_config: Logging config options for the deployment. If provided, + the config will be used to set up the Serve logger on the deployment. + request_router_config: Config for the request router used for this deployment. + Returns: + `Deployment` + """ + if route_prefix is not DEFAULT.VALUE: + raise ValueError( + "`route_prefix` can no longer be specified at the deployment level. " + "Pass it to `serve.run` or in the application config instead." + ) + + if max_ongoing_requests is None: + raise ValueError("`max_ongoing_requests` must be non-null, got None.") + + if num_replicas == "auto": + num_replicas = None + max_ongoing_requests, autoscaling_config = handle_num_replicas_auto( + max_ongoing_requests, autoscaling_config + ) + + ServeUsageTag.AUTO_NUM_REPLICAS_USED.record("1") + + # NOTE: The user_configured_option_names should be the first thing that's + # defined in this function. It depends on the locals() dictionary storing + # only the function args/kwargs. + # Create list of all user-configured options from keyword args + user_configured_option_names = [ + option + for option, value in locals().items() + if option != "_func_or_class" and value is not DEFAULT.VALUE + ] + + # Num of replicas should not be 0. + # TODO(Sihan) separate num_replicas attribute from internal and api + if num_replicas == 0: + raise ValueError("num_replicas is expected to larger than 0") + + if num_replicas not in [DEFAULT.VALUE, None, "auto"] and autoscaling_config not in [ + DEFAULT.VALUE, + None, + ]: + raise ValueError( + "Manually setting num_replicas is not allowed when " + "autoscaling_config is provided." + ) + + if version is not DEFAULT.VALUE: + logger.warning( + "DeprecationWarning: `version` in `@serve.deployment` has been deprecated. " + "Explicitly specifying version will raise an error in the future!" + ) + + if isinstance(logging_config, LoggingConfig): + logging_config = logging_config.dict() + + deployment_config = DeploymentConfig.from_default( + num_replicas=num_replicas if num_replicas is not None else 1, + user_config=user_config, + max_ongoing_requests=max_ongoing_requests, + max_queued_requests=max_queued_requests, + autoscaling_config=autoscaling_config, + graceful_shutdown_wait_loop_s=graceful_shutdown_wait_loop_s, + graceful_shutdown_timeout_s=graceful_shutdown_timeout_s, + health_check_period_s=health_check_period_s, + health_check_timeout_s=health_check_timeout_s, + logging_config=logging_config, + request_router_config=request_router_config, + ) + deployment_config.user_configured_option_names = set(user_configured_option_names) + + def decorator(_func_or_class): + replica_config = ReplicaConfig.create( + _func_or_class, + init_args=None, + init_kwargs=None, + ray_actor_options=( + ray_actor_options if ray_actor_options is not DEFAULT.VALUE else None + ), + placement_group_bundles=( + placement_group_bundles + if placement_group_bundles is not DEFAULT.VALUE + else None + ), + placement_group_strategy=( + placement_group_strategy + if placement_group_strategy is not DEFAULT.VALUE + else None + ), + max_replicas_per_node=( + max_replicas_per_node + if max_replicas_per_node is not DEFAULT.VALUE + else None + ), + ) + + return Deployment( + name if name is not DEFAULT.VALUE else _func_or_class.__name__, + deployment_config, + replica_config, + version=(version if version is not DEFAULT.VALUE else None), + _internal=True, + ) + + # This handles both parametrized and non-parametrized usage of the + # decorator. See the @serve.batch code for more details. + return decorator(_func_or_class) if callable(_func_or_class) else decorator + + +@DeveloperAPI +@dataclass(frozen=True) +class RunTarget: + """Represents a Serve application to run for `serve.run_many`.""" + + target: Application + name: str = SERVE_DEFAULT_APP_NAME + route_prefix: Optional[str] = "/" + logging_config: Optional[Union[Dict, LoggingConfig]] = None + + +@DeveloperAPI +def _run_many( + targets: Sequence[RunTarget], + wait_for_ingress_deployment_creation: bool = True, + wait_for_applications_running: bool = True, + _local_testing_mode: bool = False, +) -> List[DeploymentHandle]: + """Run many applications and return the handles to their ingress deployments. + + This is only used internally with the _blocking not totally blocking the following + code indefinitely until Ctrl-C'd. + """ + if not targets: + raise ValueError("No applications provided.") + + if RAY_SERVE_FORCE_LOCAL_TESTING_MODE: + if not _local_testing_mode: + logger.info("Overriding local_testing_mode=True from environment variable.") + + _local_testing_mode = True + + built_apps = [] + for t in targets: + if len(t.name) == 0: + raise RayServeException("Application name must a non-empty string.") + + if not isinstance(t.target, Application): + raise TypeError( + "`serve.run` expects an `Application` returned by `Deployment.bind()`." + ) + + validate_route_prefix(t.route_prefix) + + built_apps.append( + build_app( + t.target, + name=t.name, + route_prefix=t.route_prefix, + logging_config=t.logging_config, + make_deployment_handle=make_local_deployment_handle + if _local_testing_mode + else None, + default_runtime_env=ray.get_runtime_context().runtime_env + if not _local_testing_mode + else None, + ) + ) + + if _local_testing_mode: + # implicitly use the last target's logging config (if provided) in local testing mode + logging_config = t.logging_config or LoggingConfig() + if not isinstance(logging_config, LoggingConfig): + logging_config = LoggingConfig(**(logging_config or {})) + + configure_component_logger( + component_name="local_test", + component_id="-", + logging_config=logging_config, + stream_handler_only=True, + ) + return [b.deployment_handles[b.ingress_deployment_name] for b in built_apps] + else: + client = _private_api.serve_start( + http_options={"location": "EveryNode"}, + global_logging_config=None, + ) + + # Record after Ray has been started. + ServeUsageTag.API_VERSION.record("v2") + + return client.deploy_applications( + built_apps, + wait_for_ingress_deployment_creation=wait_for_ingress_deployment_creation, + wait_for_applications_running=wait_for_applications_running, + ) + + +@PublicAPI(stability="stable") +def _run( + target: Application, + *, + _blocking: bool = True, + name: str = SERVE_DEFAULT_APP_NAME, + route_prefix: Optional[str] = "/", + logging_config: Optional[Union[Dict, LoggingConfig]] = None, + _local_testing_mode: bool = False, +) -> DeploymentHandle: + """Run an application and return a handle to its ingress deployment. + + This is only used internally with the _blocking not totally blocking the following + code indefinitely until Ctrl-C'd. + """ + return _run_many( + [ + RunTarget( + target=target, + name=name, + route_prefix=route_prefix, + logging_config=logging_config, + ) + ], + wait_for_applications_running=_blocking, + _local_testing_mode=_local_testing_mode, + )[0] + + +@DeveloperAPI +def run_many( + targets: Sequence[RunTarget], + blocking: bool = False, + wait_for_ingress_deployment_creation: bool = True, + wait_for_applications_running: bool = True, + _local_testing_mode: bool = False, +) -> List[DeploymentHandle]: + """Run many applications and return the handles to their ingress deployments. + + Args: + targets: + A sequence of `RunTarget`, + each containing information about an application to deploy. + blocking: Whether this call should be blocking. If True, it + will loop and log status until Ctrl-C'd. + wait_for_ingress_deployment_creation: Whether to wait for the ingress + deployments to be created. + wait_for_applications_running: Whether to wait for the applications to be + running. Note that this effectively implies + `wait_for_ingress_deployment_creation=True`, + because the ingress deployments must be created + before the applications can be running. + + Returns: + List[DeploymentHandle]: A list of handles that can be used + to call the applications. + """ + handles = _run_many( + targets, + wait_for_ingress_deployment_creation=wait_for_ingress_deployment_creation, + wait_for_applications_running=wait_for_applications_running, + _local_testing_mode=_local_testing_mode, + ) + + if blocking: + wait_for_interrupt() + + return handles + + +@PublicAPI(stability="stable") +def run( + target: Application, + blocking: bool = False, + name: str = SERVE_DEFAULT_APP_NAME, + route_prefix: Optional[str] = "/", + logging_config: Optional[Union[Dict, LoggingConfig]] = None, + _local_testing_mode: bool = False, +) -> DeploymentHandle: + """Run an application and return a handle to its ingress deployment. + + The application is returned by `Deployment.bind()`. Example: + + .. code-block:: python + + handle = serve.run(MyDeployment.bind()) + ray.get(handle.remote()) + + Args: + target: + A Serve application returned by `Deployment.bind()`. + blocking: Whether this call should be blocking. If True, it + will loop and log status until Ctrl-C'd. + name: Application name. If not provided, this will be the only + application running on the cluster (it will delete all others). + route_prefix: Route prefix for HTTP requests. Defaults to '/'. + If `None` is passed, the application will not be exposed over HTTP + (this may be useful if you only want the application to be exposed via + gRPC or a `DeploymentHandle`). + logging_config: Application logging config. If provided, the config will + be applied to all deployments which doesn't have logging config. + + Returns: + DeploymentHandle: A handle that can be used to call the application. + """ + handle = _run( + target=target, + name=name, + route_prefix=route_prefix, + logging_config=logging_config, + _local_testing_mode=_local_testing_mode, + ) + + if blocking: + wait_for_interrupt() + + return handle + + +@PublicAPI(stability="stable") +def delete(name: str, _blocking: bool = True): + """Delete an application by its name. + + Deletes the app with all corresponding deployments. + """ + client = _get_global_client() + client.delete_apps([name], blocking=_blocking) + + +@PublicAPI(stability="beta") +def multiplexed( + func: Optional[Callable[..., Any]] = None, max_num_models_per_replica: int = 3 +): + """Wrap a callable or method used to load multiplexed models in a replica. + + The function can be standalone function or a method of a class. The + function must have exactly one argument, the model id of type `str` for the + model to be loaded. + + It is required to define the function with `async def` and the function must be + an async function. It is recommended to define coroutines for long running + IO tasks in the function to avoid blocking the event loop. + + The multiplexed function is called to load a model with the given model ID when + necessary. + + When the number of models in one replica is larger than max_num_models_per_replica, + the models will be unloaded using an LRU policy. + + If you want to release resources after the model is loaded, you can define + a `__del__` method in your model class. The `__del__` method will be called when + the model is unloaded. + + Example: + + .. code-block:: python + + from ray import serve + + @serve.deployment + class MultiplexedDeployment: + + def __init__(self): + # Define s3 base path to load models. + self.s3_base_path = "s3://my_bucket/my_models" + + @serve.multiplexed(max_num_models_per_replica=5) + async def load_model(self, model_id: str) -> Any: + # Load model with the given tag + # You can use any model loading library here + # and return the loaded model. load_from_s3 is + # a placeholder function. + return load_from_s3(model_id) + + async def __call__(self, request): + # Get the model_id from the request context. + model_id = serve.get_multiplexed_model_id() + # Load the model for the requested model_id. + # If the model is already cached locally, + # this will just be a dictionary lookup. + model = await self.load_model(model_id) + return model(request) + + + Args: + max_num_models_per_replica: the maximum number of models + to be loaded on each replica. By default, it is 3, which + means that each replica can cache up to 3 models. You can + set it to a larger number if you have enough memory on + the node resource, in opposite, you can set it to a smaller + number if you want to save memory on the node resource. + """ + + if func is not None: + if not callable(func): + raise TypeError( + "The `multiplexed` decorator must be used with a function or method." + ) + + # TODO(Sihan): Make the API accept the sync function as well. + # https://github.com/ray-project/ray/issues/35356 + if not inspect.iscoroutinefunction(func): + raise TypeError( + "@serve.multiplexed can only be used to decorate async " + "functions or methods." + ) + signature = inspect.signature(func) + if len(signature.parameters) == 0 or len(signature.parameters) > 2: + raise TypeError( + "@serve.multiplexed can only be used to decorate functions or methods " + "with at least one 'model_id: str' argument." + ) + + if not isinstance(max_num_models_per_replica, int): + raise TypeError("max_num_models_per_replica must be an integer.") + + if max_num_models_per_replica != -1 and max_num_models_per_replica <= 0: + raise ValueError("max_num_models_per_replica must be positive.") + + def _multiplex_decorator(func: Callable): + @wraps(func) + async def _multiplex_wrapper(*args): + args_check_error_msg = ( + "Functions decorated with `@serve.multiplexed` must take exactly one" + "the multiplexed model ID (str), but got {}" + ) + if not args: + raise TypeError( + args_check_error_msg.format("no arguments are provided.") + ) + self = extract_self_if_method_call(args, func) + + # User defined multiplexed function can be a standalone function or a + # method of a class. If it is a method of a class, the first argument + # is self. + if self is None: + if len(args) != 1: + raise TypeError( + args_check_error_msg.format("more than one arguments.") + ) + multiplex_object = func + model_id = args[0] + else: + # count self as an argument + if len(args) != 2: + raise TypeError( + args_check_error_msg.format("more than one arguments.") + ) + multiplex_object = self + model_id = args[1] + multiplex_attr = "__serve_multiplex_wrapper" + # If the multiplexed function is called for the first time, + # create a model multiplex wrapper and cache it in the multiplex object. + if not hasattr(multiplex_object, multiplex_attr): + model_multiplex_wrapper = _ModelMultiplexWrapper( + func, self, max_num_models_per_replica + ) + setattr(multiplex_object, multiplex_attr, model_multiplex_wrapper) + else: + model_multiplex_wrapper = getattr(multiplex_object, multiplex_attr) + return await model_multiplex_wrapper.load_model(model_id) + + return _multiplex_wrapper + + return _multiplex_decorator(func) if callable(func) else _multiplex_decorator + + +@PublicAPI(stability="beta") +def get_multiplexed_model_id() -> str: + """Get the multiplexed model ID for the current request. + + This is used with a function decorated with `@serve.multiplexed` + to retrieve the model ID for the current request. + + .. code-block:: python + + import ray + from ray import serve + import requests + + # Set the multiplexed model id with the key + # "ray_serve_multiplexed_model_id" in the request + # headers when sending requests to the http proxy. + requests.get("http://localhost:8000", + headers={"ray_serve_multiplexed_model_id": "model_1"}) + + # This can also be set when using `DeploymentHandle`. + handle.options(multiplexed_model_id="model_1").remote("blablabla") + + # In your deployment code, you can retrieve the model id from + # `get_multiplexed_model_id()`. + @serve.deployment + def my_deployment_function(request): + assert serve.get_multiplexed_model_id() == "model_1" + """ + _request_context = ray.serve.context._get_serve_request_context() + return _request_context.multiplexed_model_id + + +@PublicAPI(stability="alpha") +def status() -> ServeStatus: + """Get the status of Serve on the cluster. + + Includes status of all HTTP Proxies, all active applications, and + their deployments. + + .. code-block:: python + + @serve.deployment(num_replicas=2) + class MyDeployment: + pass + + serve.run(MyDeployment.bind()) + status = serve.status() + assert status.applications["default"].status == "RUNNING" + """ + + client = _get_global_client(raise_if_no_controller_running=False) + if client is None: + # Serve has not started yet + return ServeStatus() + + ServeUsageTag.SERVE_STATUS_API_USED.record("1") + details = ServeInstanceDetails(**client.get_serve_details()) + return details._get_status() + + +@PublicAPI(stability="alpha") +def get_app_handle(name: str) -> DeploymentHandle: + """Get a handle to the application's ingress deployment by name. + + Args: + name: Name of application to get a handle to. + + Raises: + RayServeException: If no Serve controller is running, or if the + application does not exist. + + .. code-block:: python + + import ray + from ray import serve + + @serve.deployment + def f(val: int) -> int: + return val * 2 + + serve.run(f.bind(), name="my_app") + handle = serve.get_app_handle("my_app") + assert handle.remote(3).result() == 6 + """ + + client = _get_global_client() + ingress = ray.get(client._controller.get_ingress_deployment_name.remote(name)) + if ingress is None: + raise RayServeException(f"Application '{name}' does not exist.") + + ServeUsageTag.SERVE_GET_APP_HANDLE_API_USED.record("1") + # There is no need to check if the deployment exists since the + # deployment name was just fetched from the controller + return client.get_handle(ingress, name, check_exists=False) + + +@DeveloperAPI +def get_deployment_handle( + deployment_name: str, + app_name: Optional[str] = None, + _check_exists: bool = True, + _record_telemetry: bool = True, +) -> DeploymentHandle: + """Get a handle to a deployment by name. + + This is a developer API and is for advanced Ray users and library developers. + + Args: + deployment_name: Name of deployment to get a handle to. + app_name: Application in which deployment resides. If calling + from inside a Serve application and `app_name` is not + specified, this will default to the application from which + this API is called. + + Raises: + RayServeException: If no Serve controller is running, or if + calling from outside a Serve application and no application + name is specified. + + The following example gets the handle to the ingress deployment of + an application, which is equivalent to using `serve.get_app_handle`. + + .. testcode:: + + import ray + from ray import serve + + @serve.deployment + def f(val: int) -> int: + return val * 2 + + serve.run(f.bind(), name="my_app") + handle = serve.get_deployment_handle("f", app_name="my_app") + assert handle.remote(3).result() == 6 + + serve.shutdown() + + The following example demonstrates how you can use this API to get + the handle to a non-ingress deployment in an application. + + .. testcode:: + + import ray + from ray import serve + from ray.serve.handle import DeploymentHandle + + @serve.deployment + class Multiplier: + def __init__(self, multiple: int): + self._multiple = multiple + + def __call__(self, val: int) -> int: + return val * self._multiple + + @serve.deployment + class Adder: + def __init__(self, handle: DeploymentHandle, increment: int): + self._handle = handle + self._increment = increment + + async def __call__(self, val: int) -> int: + return await self._handle.remote(val) + self._increment + + + # The app calculates 2 * x + 3 + serve.run(Adder.bind(Multiplier.bind(2), 3), name="math_app") + handle = serve.get_app_handle("math_app") + assert handle.remote(5).result() == 13 + + # Get handle to Multiplier only + handle = serve.get_deployment_handle("Multiplier", app_name="math_app") + assert handle.remote(5).result() == 10 + + serve.shutdown() + """ + + client = _get_global_client() + + internal_replica_context = _get_internal_replica_context() + if app_name is None: + if internal_replica_context is None: + raise RayServeException( + "Please specify an application name when getting a deployment handle " + "outside of a Serve application." + ) + else: + app_name = internal_replica_context.app_name + + if _record_telemetry: + ServeUsageTag.SERVE_GET_DEPLOYMENT_HANDLE_API_USED.record("1") + + return client.get_handle(deployment_name, app_name, check_exists=_check_exists) diff --git a/venv/lib/python3.10/site-packages/ray/serve/autoscaling_policy.py b/venv/lib/python3.10/site-packages/ray/serve/autoscaling_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2cabe736a870ac23244f1fa028342bebf0935079 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/autoscaling_policy.py @@ -0,0 +1,159 @@ +import logging +import math +from typing import Any, Dict, Optional + +from ray.serve._private.constants import CONTROL_LOOP_INTERVAL_S, SERVE_LOGGER_NAME +from ray.serve.config import AutoscalingConfig +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +def _calculate_desired_num_replicas( + autoscaling_config: AutoscalingConfig, + total_num_requests: int, + num_running_replicas: int, + override_min_replicas: Optional[float] = None, + override_max_replicas: Optional[float] = None, +) -> int: + """Returns the number of replicas to scale to based on the given metrics. + + Args: + autoscaling_config: The autoscaling parameters to use for this + calculation. + current_num_ongoing_requests (List[float]): A list of the number of + ongoing requests for each replica. Assumes each entry has already + been time-averaged over the desired lookback window. + override_min_replicas: Overrides min_replicas from the config + when calculating the final number of replicas. + override_max_replicas: Overrides max_replicas from the config + when calculating the final number of replicas. + + Returns: + desired_num_replicas: The desired number of replicas to scale to, based + on the input metrics and the current number of replicas. + + """ + if num_running_replicas == 0: + raise ValueError("Number of replicas cannot be zero") + + # Example: if error_ratio == 2.0, we have two times too many ongoing + # requests per replica, so we desire twice as many replicas. + target_num_requests = ( + autoscaling_config.get_target_ongoing_requests() * num_running_replicas + ) + error_ratio: float = total_num_requests / target_num_requests + + # If error ratio >= 1, then the number of ongoing requests per + # replica exceeds the target and we will make an upscale decision, + # so we apply the upscale smoothing factor. Otherwise, the number of + # ongoing requests per replica is lower than the target and we will + # make a downscale decision, so we apply the downscale smoothing + # factor. + if error_ratio >= 1: + scaling_factor = autoscaling_config.get_upscaling_factor() + else: + scaling_factor = autoscaling_config.get_downscaling_factor() + + # Multiply the distance to 1 by the smoothing ("gain") factor (default=1). + smoothed_error_ratio = 1 + ((error_ratio - 1) * scaling_factor) + desired_num_replicas = math.ceil(num_running_replicas * smoothed_error_ratio) + + # If desired num replicas is "stuck" because of the smoothing factor + # (meaning the traffic is low enough for the replicas to downscale + # without the smoothing factor), decrease desired_num_replicas by 1. + if ( + math.ceil(num_running_replicas * error_ratio) < num_running_replicas + and desired_num_replicas == num_running_replicas + ): + desired_num_replicas -= 1 + + min_replicas = autoscaling_config.min_replicas + max_replicas = autoscaling_config.max_replicas + if override_min_replicas is not None: + min_replicas = override_min_replicas + if override_max_replicas is not None: + max_replicas = override_max_replicas + + # Ensure scaled_min_replicas <= desired_num_replicas <= scaled_max_replicas. + desired_num_replicas = max(min_replicas, min(max_replicas, desired_num_replicas)) + + return desired_num_replicas + + +@PublicAPI(stability="alpha") +def replica_queue_length_autoscaling_policy( + curr_target_num_replicas: int, + total_num_requests: int, + num_running_replicas: int, + config: Optional[AutoscalingConfig], + capacity_adjusted_min_replicas: int, + capacity_adjusted_max_replicas: int, + policy_state: Dict[str, Any], +) -> int: + """The default autoscaling policy based on basic thresholds for scaling. + There is a minimum threshold for the average queue length in the cluster + to scale up and a maximum threshold to scale down. Each period, a 'scale + up' or 'scale down' decision is made. This decision must be made for a + specified number of periods in a row before the number of replicas is + actually scaled. See config options for more details. Assumes + `get_decision_num_replicas` is called once every CONTROL_LOOP_PERIOD_S + seconds. + """ + decision_counter = policy_state.get("decision_counter", 0) + if num_running_replicas == 0: + # When 0 replicas and queries are queued, scale up the replicas + if total_num_requests > 0: + return max( + math.ceil(1 * config.get_upscaling_factor()), + curr_target_num_replicas, + ) + return curr_target_num_replicas + + decision_num_replicas = curr_target_num_replicas + + desired_num_replicas = _calculate_desired_num_replicas( + config, + total_num_requests, + num_running_replicas=num_running_replicas, + override_min_replicas=capacity_adjusted_min_replicas, + override_max_replicas=capacity_adjusted_max_replicas, + ) + # Scale up. + if desired_num_replicas > curr_target_num_replicas: + # If the previous decision was to scale down (the counter was + # negative), we reset it and then increment it (set to 1). + # Otherwise, just increment. + if decision_counter < 0: + decision_counter = 0 + decision_counter += 1 + + # Only actually scale the replicas if we've made this decision for + # 'scale_up_consecutive_periods' in a row. + if decision_counter > int(config.upscale_delay_s / CONTROL_LOOP_INTERVAL_S): + decision_counter = 0 + decision_num_replicas = desired_num_replicas + + # Scale down. + elif desired_num_replicas < curr_target_num_replicas: + # If the previous decision was to scale up (the counter was + # positive), reset it to zero before decrementing. + if decision_counter > 0: + decision_counter = 0 + decision_counter -= 1 + + # Only actually scale the replicas if we've made this decision for + # 'scale_down_consecutive_periods' in a row. + if decision_counter < -int(config.downscale_delay_s / CONTROL_LOOP_INTERVAL_S): + decision_counter = 0 + decision_num_replicas = desired_num_replicas + + # Do nothing. + else: + decision_counter = 0 + + policy_state["decision_counter"] = decision_counter + return decision_num_replicas + + +default_autoscaling_policy = replica_queue_length_autoscaling_policy diff --git a/venv/lib/python3.10/site-packages/ray/serve/batching.py b/venv/lib/python3.10/site-packages/ray/serve/batching.py new file mode 100644 index 0000000000000000000000000000000000000000..8be63765c43ea10d5912a0c6654e1d138a5af48c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/batching.py @@ -0,0 +1,756 @@ +import asyncio +import io +import logging +import time +from collections import deque +from dataclasses import dataclass +from functools import wraps +from inspect import isasyncgenfunction, iscoroutinefunction +from typing import ( + Any, + AsyncGenerator, + Callable, + Coroutine, + Dict, + Generic, + Iterable, + List, + Literal, + Optional, + Protocol, + Set, + Tuple, + TypeVar, + overload, +) + +from ray import serve +from ray._common.signature import extract_signature, flatten_args, recover_args +from ray._common.utils import get_or_create_event_loop +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.utils import extract_self_if_method_call +from ray.serve.exceptions import RayServeException +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +# The user can return these values in their streaming batch handler function to +# indicate that a request is finished, so Serve can terminate the request. +USER_CODE_STREAMING_SENTINELS = [StopIteration, StopAsyncIteration] + + +@dataclass +class _SingleRequest: + self_arg: Any + flattened_args: List[Any] + future: asyncio.Future + + +@dataclass +class _GeneratorResult: + result: Any + next_future: asyncio.Future + + +@dataclass +class _RuntimeSummaryStatistics: + start_times: List[float] + + @property + def min_start_time(self) -> Optional[float]: + return min(self.start_times) if self.start_times else None + + @property + def mean_start_time(self) -> Optional[float]: + return ( + sum(self.start_times) / len(self.start_times) if self.start_times else None + ) + + @property + def max_start_time(self) -> Optional[float]: + return max(self.start_times) if self.start_times else None + + @property + def num_requests(self) -> int: + return len(self.start_times) + + +def _batch_args_kwargs( + list_of_flattened_args: List[List[Any]], +) -> Tuple[Tuple[Any], Dict[Any, Any]]: + """Batch a list of flatten args and returns regular args and kwargs""" + # Ray's flatten arg format is a list with alternating key and values + # e.g. args=(1, 2), kwargs={"key": "val"} got turned into + # [None, 1, None, 2, "key", "val"] + arg_lengths = {len(args) for args in list_of_flattened_args} + assert ( + len(arg_lengths) == 1 + ), "All batch requests should have the same number of parameters." + arg_length = arg_lengths.pop() + + batched_flattened_args = [] + for idx in range(arg_length): + if idx % 2 == 0: + batched_flattened_args.append(list_of_flattened_args[0][idx]) + else: + batched_flattened_args.append( + [item[idx] for item in list_of_flattened_args] + ) + + return recover_args(batched_flattened_args) + + +class _BatchQueue: + def __init__( + self, + max_batch_size: int, + batch_wait_timeout_s: float, + max_concurrent_batches: int, + handle_batch_func: Optional[Callable] = None, + ) -> None: + """Async queue that accepts individual items and returns batches. + + Respects max_batch_size and batch_wait_timeout_s; a batch will be returned when + max_batch_size elements are available or the timeout has passed since + the previous get. + + If handle_batch_func is passed in, a background coroutine will run to + poll from the queue and call handle_batch_func on the results. + + Cannot be pickled. + + Arguments: + max_batch_size: max number of elements to return in a batch. + batch_wait_timeout_s: time to wait before returning an incomplete + batch. + max_concurrent_batches: max number of batches to run concurrently. + handle_batch_func(Optional[Callable]): callback to run in the + background to handle batches if provided. + """ + self.queue: asyncio.Queue[_SingleRequest] = asyncio.Queue() + self.max_batch_size = max_batch_size + self.batch_wait_timeout_s = batch_wait_timeout_s + self.max_concurrent_batches = max_concurrent_batches + self.semaphore = asyncio.Semaphore(max_concurrent_batches) + self.requests_available_event = asyncio.Event() + self.tasks: Set[asyncio.Task] = set() + + # Used for observability. + self.curr_iteration_start_times: Dict[asyncio.Task, float] = {} + + self._handle_batch_task = None + self._loop = get_or_create_event_loop() + if handle_batch_func is not None: + self._handle_batch_task = self._loop.create_task( + self._process_batches(handle_batch_func) + ) + self._warn_if_max_batch_size_exceeds_max_ongoing_requests() + + def _warn_if_max_batch_size_exceeds_max_ongoing_requests(self): + """Helper to check whether the max_batch_size is bounded. + + Log a warning to configure `max_ongoing_requests` if it's bounded. + """ + max_ongoing_requests = ( + serve.get_replica_context()._deployment_config.max_ongoing_requests + ) + if max_ongoing_requests < self.max_batch_size * self.max_concurrent_batches: + logger.warning( + f"`max_batch_size` ({self.max_batch_size}) * `max_concurrent_batches` " + f"({self.max_concurrent_batches}) is larger than `max_ongoing_requests` " + f"({max_ongoing_requests}). This means the replica will never achieve " + "the configured `max_batch_size` concurrently. Please update " + "`max_ongoing_requests` to be >= `max_batch_size` * `max_concurrent_batches`." + ) + + def set_max_batch_size(self, new_max_batch_size: int) -> None: + """Updates queue's max_batch_size.""" + self.max_batch_size = new_max_batch_size + self._warn_if_max_batch_size_exceeds_max_ongoing_requests() + + def put(self, request: Tuple[_SingleRequest, asyncio.Future]) -> None: + self.queue.put_nowait(request) + self.requests_available_event.set() + + async def wait_for_batch(self) -> List[_SingleRequest]: + """Wait for batch respecting self.max_batch_size and self.timeout_s. + + Returns a batch of up to self.max_batch_size items. Waits for up to + to self.timeout_s after receiving the first request that will be in + the next batch. After the timeout, returns as many items as are ready. + + Always returns a batch with at least one item - will block + indefinitely until an item comes in. + """ + + batch = [] + batch.append(await self.queue.get()) + + # Cache current max_batch_size and batch_wait_timeout_s for this batch. + max_batch_size = self.max_batch_size + batch_wait_timeout_s = self.batch_wait_timeout_s + + # Wait self.timeout_s seconds for new queue arrivals. + batch_start_time = time.time() + while True: + remaining_batch_time_s = max( + batch_wait_timeout_s - (time.time() - batch_start_time), 0 + ) + try: + # Wait for new arrivals. + await asyncio.wait_for( + self.requests_available_event.wait(), remaining_batch_time_s + ) + except asyncio.TimeoutError: + pass + + # Add all new arrivals to the batch. + while len(batch) < max_batch_size and not self.queue.empty(): + batch.append(self.queue.get_nowait()) + + # Only clear the put event if the queue is empty. If it's not empty + # we can start constructing a new batch immediately in the next loop. + # The code that puts items into the queue runs on the same event loop + # as this code, so there's no race condition between the time we + # get objects in the queue (and clear the event) and when objects + # get added to the queue. + if self.queue.empty(): + self.requests_available_event.clear() + + if ( + time.time() - batch_start_time >= batch_wait_timeout_s + or len(batch) >= max_batch_size + ): + break + + return batch + + def _validate_results( + self, results: Iterable[Any], input_batch_length: int + ) -> None: + if len(results) != input_batch_length: + raise RayServeException( + "Batched function doesn't preserve batch size. " + f"The input list has length {input_batch_length} but the " + f"returned list has length {len(results)}." + ) + + async def _consume_func_generator( + self, + func_generator: AsyncGenerator, + initial_futures: List[asyncio.Future], + input_batch_length: int, + ) -> None: + """Consumes batch function generator. + + This function only runs if the function decorated with @serve.batch + is a generator. + """ + + FINISHED_TOKEN = None + + try: + futures = deque(initial_futures) + assert len(futures) == input_batch_length + + async for results in func_generator: + self._validate_results(results, input_batch_length) + for idx in range(input_batch_length): + result, future = results[idx], futures[0] + + if future is FINISHED_TOKEN: + # This caller has already terminated. + futures.append(FINISHED_TOKEN) + elif result in USER_CODE_STREAMING_SENTINELS: + # User's code returned sentinel. No values left + # for caller. Terminate iteration for caller. + _set_exception_if_not_done(future, StopAsyncIteration) + futures.append(FINISHED_TOKEN) + else: + next_future = get_or_create_event_loop().create_future() + _set_result_if_not_done( + future, _GeneratorResult(result, next_future) + ) + futures.append(next_future) + + # Remove processed future. We remove the future at the very + # end of the loop to ensure that if an exception occurs, + # all pending futures will get set in the `except` block. + futures.popleft() + + for future in futures: + if future is not FINISHED_TOKEN: + _set_exception_if_not_done(future, StopAsyncIteration) + except Exception as e: + for future in futures: + if future is not FINISHED_TOKEN: + _set_exception_if_not_done(future, e) + + async def _assign_func_results( + self, + func_future: asyncio.Future, + futures: List[asyncio.Future], + input_batch_length: int, + ): + """Assigns func's results to the list of futures.""" + + try: + results = await func_future + self._validate_results(results, input_batch_length) + for result, future in zip(results, futures): + _set_result_if_not_done(future, result) + except Exception as e: + for future in futures: + _set_exception_if_not_done(future, e) + + async def _process_batches(self, func: Callable) -> None: + """Loops infinitely and processes queued request batches.""" + while not self._loop.is_closed(): + batch = await self.wait_for_batch() + promise = self._process_batch(func, batch) + task = asyncio.create_task(promise) + self.tasks.add(task) + self.curr_iteration_start_times[task] = time.time() + task.add_done_callback(self._handle_completed_task) + + async def _process_batch(self, func: Callable, batch: List[_SingleRequest]) -> None: + """Processes queued request batch.""" + # NOTE: this semaphore caps the number of concurrent batches specified by `max_concurrent_batches` + async with self.semaphore: + # Remove requests that have been cancelled from the batch. If + # all requests have been cancelled, simply return and wait for + # the next batch. + batch = [req for req in batch if not req.future.cancelled()] + if len(batch) == 0: + return + + futures = [item.future for item in batch] + + # Most of the logic in the function should be wrapped in this try- + # except block, so the futures' exceptions can be set if an exception + # occurs. Otherwise, the futures' requests may hang indefinitely. + try: + self_arg = batch[0].self_arg + args, kwargs = _batch_args_kwargs( + [item.flattened_args for item in batch] + ) + + # Method call. + if self_arg is not None: + func_future_or_generator = func(self_arg, *args, **kwargs) + # Normal function call. + else: + func_future_or_generator = func(*args, **kwargs) + + if isasyncgenfunction(func): + func_generator = func_future_or_generator + await self._consume_func_generator( + func_generator, futures, len(batch) + ) + else: + func_future = func_future_or_generator + await self._assign_func_results(func_future, futures, len(batch)) + + except Exception as e: + logger.exception("_process_batch ran into an unexpected exception.") + + for future in futures: + _set_exception_if_not_done(future, e) + + def _handle_completed_task(self, task: asyncio.Task) -> None: + self.tasks.remove(task) + del self.curr_iteration_start_times[task] + self._log_if_exception(task.exception()) + + @staticmethod + def _log_if_exception(exception_maybe: Optional[BaseException]) -> None: + if exception_maybe is not None: + if isinstance(exception_maybe, asyncio.CancelledError): + logger.debug("Task was cancelled") + else: + logger.exception("Task failed unexpectedly") + + def __del__(self): + if ( + self._handle_batch_task is None + or not get_or_create_event_loop().is_running() + ): + return + + # TODO(edoakes): although we try to gracefully shutdown here, it still + # causes some errors when the process exits due to the asyncio loop + # already being destroyed. + self._handle_batch_task.cancel() + + +class _LazyBatchQueueWrapper: + """Stores a _BatchQueue and updates its settings. + + _BatchQueue cannot be pickled, you must construct it lazily + at runtime inside a replica. This class initializes a queue only upon + first access. + """ + + def __init__( + self, + max_batch_size: int = 10, + batch_wait_timeout_s: float = 0.0, + max_concurrent_batches: int = 1, + handle_batch_func: Optional[Callable] = None, + ): + self._queue: Optional[_BatchQueue] = None + self.max_batch_size = max_batch_size + self.batch_wait_timeout_s = batch_wait_timeout_s + self.max_concurrent_batches = max_concurrent_batches + self.handle_batch_func = handle_batch_func + + @property + def queue(self) -> _BatchQueue: + """Returns _BatchQueue. + + Initializes queue when called for the first time. + """ + if self._queue is None: + self._queue = _BatchQueue( + self.max_batch_size, + self.batch_wait_timeout_s, + self.max_concurrent_batches, + self.handle_batch_func, + ) + return self._queue + + def set_max_batch_size(self, new_max_batch_size: int) -> None: + """Updates queue's max_batch_size.""" + + self.max_batch_size = new_max_batch_size + + if self._queue is not None: + self._queue.set_max_batch_size(new_max_batch_size) + + def set_batch_wait_timeout_s(self, new_batch_wait_timeout_s: float) -> None: + self.batch_wait_timeout_s = new_batch_wait_timeout_s + + if self._queue is not None: + self._queue.batch_wait_timeout_s = new_batch_wait_timeout_s + + def get_max_batch_size(self) -> int: + return self.max_batch_size + + def get_batch_wait_timeout_s(self) -> float: + return self.batch_wait_timeout_s + + def _get_curr_iteration_start_times(self) -> _RuntimeSummaryStatistics: + """Gets summary statistics of current iteration's start times.""" + return _RuntimeSummaryStatistics( + list(self.queue.curr_iteration_start_times.values()) + ) + + async def _is_batching_task_alive(self) -> bool: + """Gets whether default _BatchQueue's background task is alive. + + Returns False if the batch handler doesn't use a default _BatchQueue. + """ + + if hasattr(self.queue, "_handle_batch_task"): + return not self.queue._handle_batch_task.done() + else: + return False + + async def _get_handling_task_stack(self) -> Optional[str]: + """Gets the stack for the default _BatchQueue's background task. + + Returns empty string if the batch handler doesn't use a default _BatchQueue. + """ + + if hasattr(self.queue, "_handle_batch_task"): + str_buffer = io.StringIO() + self.queue._handle_batch_task.print_stack(file=str_buffer) + return str_buffer.getvalue() + else: + return None + + +def _validate_max_batch_size(max_batch_size): + if not isinstance(max_batch_size, int): + if isinstance(max_batch_size, float) and max_batch_size.is_integer(): + max_batch_size = int(max_batch_size) + else: + raise TypeError( + f"max_batch_size must be integer >= 1, got {max_batch_size}" + ) + + if max_batch_size < 1: + raise ValueError( + f"max_batch_size must be an integer >= 1, got {max_batch_size}" + ) + + +def _validate_batch_wait_timeout_s(batch_wait_timeout_s): + if not isinstance(batch_wait_timeout_s, (float, int)): + raise TypeError( + f"batch_wait_timeout_s must be a float >= 0, got {batch_wait_timeout_s}" + ) + + if batch_wait_timeout_s < 0: + raise ValueError( + f"batch_wait_timeout_s must be a float >= 0, got {batch_wait_timeout_s}" + ) + + +def _validate_max_concurrent_batches(max_concurrent_batches: int) -> None: + if not isinstance(max_concurrent_batches, int) or max_concurrent_batches < 1: + raise TypeError( + f"max_concurrent_batches must be an integer >= 1, got {max_concurrent_batches}" + ) + + +SelfType = TypeVar("SelfType", contravariant=True) +T = TypeVar("T") +R = TypeVar("R") + + +class _SyncBatchingMethod(Protocol, Generic[SelfType, T, R]): + def __call__(self, self_: SelfType, __batch: List[T], /) -> List[R]: + ... + + +class _AsyncBatchingMethod(Protocol, Generic[SelfType, T, R]): + async def __call__(self, self_: SelfType, __batch: List[T], /) -> List[R]: + ... + + +@overload # Sync function for `batch` called WITHOUT arguments +def batch(_sync_func: Callable[[List[T]], List[R]], /) -> Callable[[T], R]: + ... + + +@overload # Async function for `batch` called WITHOUT arguments +def batch( + _async_func: Callable[[List[T]], Coroutine[Any, Any, List[R]]], / +) -> Callable[[T], Coroutine[Any, Any, R]]: + ... + + +@overload # Sync method for `batch` called WITHOUT arguments +def batch( + _sync_meth: _SyncBatchingMethod[SelfType, T, R], / +) -> Callable[[SelfType, T], R]: + ... + + +@overload # Async method for `batch` called WITHOUT arguments +def batch( + _async_meth: _AsyncBatchingMethod[SelfType, T, R], / +) -> Callable[[SelfType, T], Coroutine[Any, Any, R]]: + ... + + +@overload # `batch` called WITH arguments +def batch( + _: Literal[None] = None, + /, + max_batch_size: int = 10, + batch_wait_timeout_s: float = 0.0, + max_concurrent_batches: int = 1, +) -> "_BatchDecorator": + ... + + +class _BatchDecorator(Protocol): + """Descibes behaviour of decorator produced by calling `batch` with arguments""" + + @overload # Sync function + def __call__(self, _sync_func: Callable[[List[T]], List[R]], /) -> Callable[[T], R]: + ... + + @overload # Async function + def __call__( + self, _async_func: Callable[[List[T]], Coroutine[Any, Any, List[R]]], / + ) -> Callable[[T], Coroutine[Any, Any, R]]: + ... + + @overload # Sync method + def __call__( + self, _sync_meth: _SyncBatchingMethod[SelfType, T, R], / + ) -> Callable[[SelfType, T], R]: + ... + + @overload # Async method + def __call__( + self, _async_meth: _AsyncBatchingMethod[SelfType, T, R], / + ) -> Callable[[SelfType, T], Coroutine[Any, Any, R]]: + ... + + +@PublicAPI(stability="stable") +def batch( + _func: Optional[Callable] = None, + /, + max_batch_size: int = 10, + batch_wait_timeout_s: float = 0.0, + max_concurrent_batches: int = 1, +) -> Callable: + """Converts a function to asynchronously handle batches. + + The function can be a standalone function or a class method. In both + cases, the function must be `async def` and take a list of objects as + its sole argument and return a list of the same length as a result. + + When invoked, the caller passes a single object. These will be batched + and executed asynchronously once there is a batch of `max_batch_size` + or `batch_wait_timeout_s` has elapsed, whichever occurs first. + + `max_batch_size` and `batch_wait_timeout_s` can be updated using setter + methods from the batch_handler (`set_max_batch_size` and + `set_batch_wait_timeout_s`). + + Example: + + .. code-block:: python + + from ray import serve + from starlette.requests import Request + + @serve.deployment + class BatchedDeployment: + @serve.batch(max_batch_size=10, batch_wait_timeout_s=0.1) + async def batch_handler(self, requests: List[Request]) -> List[str]: + response_batch = [] + for r in requests: + name = (await requests.json())["name"] + response_batch.append(f"Hello {name}!") + + return response_batch + + def update_batch_params(self, max_batch_size, batch_wait_timeout_s): + self.batch_handler.set_max_batch_size(max_batch_size) + self.batch_handler.set_batch_wait_timeout_s(batch_wait_timeout_s) + + async def __call__(self, request: Request): + return await self.batch_handler(request) + + app = BatchedDeployment.bind() + + Arguments: + max_batch_size: the maximum batch size that will be executed in + one call to the underlying function. + batch_wait_timeout_s: the maximum duration to wait for + `max_batch_size` elements before running the current batch. + max_concurrent_batches: the maximum number of batches that can be + executed concurrently. If the number of concurrent batches exceeds + this limit, the batch handler will wait for a batch to complete + before sending the next batch to the underlying function. + """ + # `_func` will be None in the case when the decorator is parametrized. + # See the comment at the end of this function for a detailed explanation. + if _func is not None: + if not callable(_func): + raise TypeError( + "@serve.batch can only be used to decorate functions or methods." + ) + + if not iscoroutinefunction(_func): + raise TypeError("Functions decorated with @serve.batch must be 'async def'") + + _validate_max_batch_size(max_batch_size) + _validate_batch_wait_timeout_s(batch_wait_timeout_s) + _validate_max_concurrent_batches(max_concurrent_batches) + + def _batch_decorator(_func): + lazy_batch_queue_wrapper = _LazyBatchQueueWrapper( + max_batch_size, + batch_wait_timeout_s, + max_concurrent_batches, + _func, + ) + + async def batch_handler_generator( + first_future: asyncio.Future, + ) -> AsyncGenerator: + """Generator that handles generator batch functions.""" + + future = first_future + while True: + try: + async_response: _GeneratorResult = await future + future = async_response.next_future + yield async_response.result + except StopAsyncIteration: + break + + def enqueue_request(args, kwargs) -> asyncio.Future: + flattened_args: List = flatten_args(extract_signature(_func), args, kwargs) + + # If the function is a method, remove self as an argument. + self = extract_self_if_method_call(args, _func) + if self is not None: + flattened_args = flattened_args[2:] + + batch_queue = lazy_batch_queue_wrapper.queue + + future = get_or_create_event_loop().create_future() + batch_queue.put(_SingleRequest(self, flattened_args, future)) + return future + + @wraps(_func) + def generator_batch_wrapper(*args, **kwargs): + first_future = enqueue_request(args, kwargs) + return batch_handler_generator(first_future) + + @wraps(_func) + async def batch_wrapper(*args, **kwargs): + # This will raise if the underlying call raised an exception. + return await enqueue_request(args, kwargs) + + if isasyncgenfunction(_func): + wrapper = generator_batch_wrapper + else: + wrapper = batch_wrapper + + # We store the lazy_batch_queue_wrapper's getters and setters as + # batch_wrapper attributes, so they can be accessed in user code. + wrapper._get_max_batch_size = lazy_batch_queue_wrapper.get_max_batch_size + wrapper._get_batch_wait_timeout_s = ( + lazy_batch_queue_wrapper.get_batch_wait_timeout_s + ) + wrapper.set_max_batch_size = lazy_batch_queue_wrapper.set_max_batch_size + wrapper.set_batch_wait_timeout_s = ( + lazy_batch_queue_wrapper.set_batch_wait_timeout_s + ) + + # Store debugging methods in the lazy_batch_queue wrapper + wrapper._get_curr_iteration_start_times = ( + lazy_batch_queue_wrapper._get_curr_iteration_start_times + ) + wrapper._is_batching_task_alive = ( + lazy_batch_queue_wrapper._is_batching_task_alive + ) + wrapper._get_handling_task_stack = ( + lazy_batch_queue_wrapper._get_handling_task_stack + ) + + return wrapper + + # Unfortunately, this is required to handle both non-parametrized + # (@serve.batch) and parametrized (@serve.batch(**kwargs)) usage. + # In the former case, `serve.batch` will be called with the underlying + # function as the sole argument. In the latter case, it will first be + # called with **kwargs, then the result of that call will be called + # with the underlying function as the sole argument (i.e., it must be a + # "decorator factory."). + return _batch_decorator(_func) if callable(_func) else _batch_decorator + + +def _set_result_if_not_done(future: asyncio.Future, result: Any): + """Sets the future's result if the future is not done.""" + + if not future.done(): + future.set_result(result) + + +def _set_exception_if_not_done(future: asyncio.Future, exception: Any): + """Sets the future's exception if the future is not done.""" + + if not future.done(): + future.set_exception(exception) diff --git a/venv/lib/python3.10/site-packages/ray/serve/config.py b/venv/lib/python3.10/site-packages/ray/serve/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1386a99b48f4edb670bc17c79be9cad840d42504 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/config.py @@ -0,0 +1,482 @@ +import json +import logging +import warnings +from enum import Enum +from typing import Any, Callable, Dict, List, Optional, Union + +from ray import cloudpickle +from ray._common.pydantic_compat import ( + BaseModel, + Field, + NonNegativeFloat, + NonNegativeInt, + PositiveFloat, + PositiveInt, + PrivateAttr, + validator, +) +from ray._common.utils import import_attr +from ray.serve._private.constants import ( + DEFAULT_AUTOSCALING_POLICY, + DEFAULT_GRPC_PORT, + DEFAULT_HTTP_HOST, + DEFAULT_HTTP_PORT, + DEFAULT_REQUEST_ROUTER_PATH, + DEFAULT_REQUEST_ROUTING_STATS_PERIOD_S, + DEFAULT_REQUEST_ROUTING_STATS_TIMEOUT_S, + DEFAULT_TARGET_ONGOING_REQUESTS, + DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S, + SERVE_LOGGER_NAME, +) +from ray.util.annotations import Deprecated, PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@PublicAPI(stability="alpha") +class RequestRouterConfig(BaseModel): + """Config for the Serve request router. + + This class configures how Ray Serve routes requests to deployment replicas. The router is + responsible for selecting which replica should handle each incoming request based on the + configured routing policy. You can customize the routing behavior by specifying a custom + request router class and providing configuration parameters. + + The router also manages periodic health checks and scheduling statistics collection from + replicas to make informed routing decisions. + + Example: + .. code-block:: python + + from ray.serve.config import RequestRouterConfig, DeploymentConfig + from ray import serve + + # Use default router with custom stats collection interval + request_router_config = RequestRouterConfig( + request_routing_stats_period_s=5.0, + request_routing_stats_timeout_s=15.0 + ) + + # Use custom router class + request_router_config = RequestRouterConfig( + request_router_class="ray.llm._internal.serve.request_router.prefix_aware.prefix_aware_router.PrefixAwarePow2ReplicaRouter", + request_router_kwargs={"imbalanced_threshold": 20} + ) + deployment_config = DeploymentConfig( + request_router_config=request_router_config + ) + deployment = serve.deploy( + "my_deployment", + deployment_config=deployment_config + ) + """ + + _serialized_request_router_cls: bytes = PrivateAttr(default=b"") + + request_router_class: Union[str, Callable] = Field( + default=DEFAULT_REQUEST_ROUTER_PATH, + description=( + "The class of the request router that Ray Serve uses for this deployment. This value can be " + "a string or a class. All the deployment handles that you create for this " + "deployment use the routing policy defined by the request router. " + "Default to Serve's PowerOfTwoChoicesRequestRouter." + ), + ) + request_router_kwargs: Dict[str, Any] = Field( + default_factory=dict, + description=( + "Keyword arguments that Ray Serve passes to the request router class " + "initialize_state method." + ), + ) + + request_routing_stats_period_s: PositiveFloat = Field( + default=DEFAULT_REQUEST_ROUTING_STATS_PERIOD_S, + description=( + "Duration between record scheduling stats calls for the replica. " + "Defaults to 10s. The health check is by default a no-op Actor call " + "to the replica, but you can define your own request scheduling stats " + "using the 'record_scheduling_stats' method in your deployment." + ), + ) + + request_routing_stats_timeout_s: PositiveFloat = Field( + default=DEFAULT_REQUEST_ROUTING_STATS_TIMEOUT_S, + description=( + "Duration in seconds, that replicas wait for a request scheduling " + "stats method to return before considering it as failed. Defaults to 30s." + ), + ) + + @validator("request_router_kwargs", always=True) + def request_router_kwargs_json_serializable(cls, v): + if isinstance(v, bytes): + return v + if v is not None: + try: + json.dumps(v) + except TypeError as e: + raise ValueError( + f"request_router_kwargs is not JSON-serializable: {str(e)}." + ) + + return v + + def __init__(self, **kwargs: dict[str, Any]): + """Initialize RequestRouterConfig with the given parameters. + + Needed to serialize the request router class since validators are not called + for attributes that begin with an underscore. + + Args: + **kwargs: Keyword arguments to pass to BaseModel. + """ + super().__init__(**kwargs) + self._serialize_request_router_cls() + + def _serialize_request_router_cls(self) -> None: + """Import and serialize request router class with cloudpickle. + + Import the request router if you pass it in as a string import path. + Then cloudpickle the request router and set to + `_serialized_request_router_cls`. + """ + request_router_class = self.request_router_class + if isinstance(request_router_class, Callable): + request_router_class = ( + f"{request_router_class.__module__}.{request_router_class.__name__}" + ) + + request_router_path = request_router_class or DEFAULT_REQUEST_ROUTER_PATH + request_router_class = import_attr(request_router_path) + + self._serialized_request_router_cls = cloudpickle.dumps(request_router_class) + # Update the request_router_class field to be the string path + self.request_router_class = request_router_path + + def get_request_router_class(self) -> Callable: + """Deserialize the request router from cloudpickled bytes.""" + return cloudpickle.loads(self._serialized_request_router_cls) + + +@PublicAPI(stability="stable") +class AutoscalingConfig(BaseModel): + """Config for the Serve Autoscaler.""" + + # Please keep these options in sync with those in + # `src/ray/protobuf/serve.proto`. + + # Publicly exposed options + min_replicas: NonNegativeInt = 1 + initial_replicas: Optional[NonNegativeInt] = None + max_replicas: PositiveInt = 1 + + target_ongoing_requests: PositiveFloat = DEFAULT_TARGET_ONGOING_REQUESTS + + metrics_interval_s: PositiveFloat = Field( + default=10.0, description="How often to scrape for metrics." + ) + look_back_period_s: PositiveFloat = Field( + default=30.0, description="Time window to average over for metrics." + ) + + smoothing_factor: PositiveFloat = Field( + default=1.0, + description="[DEPRECATED] Smoothing factor for autoscaling decisions.", + ) + # DEPRECATED: replaced by `downscaling_factor` + upscale_smoothing_factor: Optional[PositiveFloat] = Field( + default=None, description="[DEPRECATED] Please use `upscaling_factor` instead." + ) + # DEPRECATED: replaced by `upscaling_factor` + downscale_smoothing_factor: Optional[PositiveFloat] = Field( + default=None, + description="[DEPRECATED] Please use `downscaling_factor` instead.", + ) + + upscaling_factor: Optional[PositiveFloat] = Field( + default=None, + description='Multiplicative "gain" factor to limit upscaling decisions.', + ) + downscaling_factor: Optional[PositiveFloat] = Field( + default=None, + description='Multiplicative "gain" factor to limit downscaling decisions.', + ) + + # How frequently to make autoscaling decisions + # loop_period_s: float = CONTROL_LOOP_PERIOD_S + downscale_delay_s: NonNegativeFloat = Field( + default=600.0, description="How long to wait before scaling down replicas." + ) + upscale_delay_s: NonNegativeFloat = Field( + default=30.0, description="How long to wait before scaling up replicas." + ) + + # Cloudpickled policy definition. + _serialized_policy_def: bytes = PrivateAttr(default=b"") + + # Custom autoscaling config. Defaults to the request-based autoscaler. + _policy: Union[str, Callable] = PrivateAttr(default=DEFAULT_AUTOSCALING_POLICY) + + @validator("max_replicas", always=True) + def replicas_settings_valid(cls, max_replicas, values): + min_replicas = values.get("min_replicas") + initial_replicas = values.get("initial_replicas") + if min_replicas is not None and max_replicas < min_replicas: + raise ValueError( + f"max_replicas ({max_replicas}) must be greater than " + f"or equal to min_replicas ({min_replicas})!" + ) + + if initial_replicas is not None: + if initial_replicas < min_replicas: + raise ValueError( + f"min_replicas ({min_replicas}) must be less than " + f"or equal to initial_replicas ({initial_replicas})!" + ) + elif initial_replicas > max_replicas: + raise ValueError( + f"max_replicas ({max_replicas}) must be greater than " + f"or equal to initial_replicas ({initial_replicas})!" + ) + + return max_replicas + + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.serialize_policy() + + def serialize_policy(self) -> None: + """Serialize policy with cloudpickle. + + Import the policy if it's passed in as a string import path. Then cloudpickle + the policy and set `serialized_policy_def` if it's empty. + """ + values = self.dict() + policy = values.get("_policy") + if isinstance(policy, Callable): + policy = f"{policy.__module__}.{policy.__name__}" + + if not policy: + policy = DEFAULT_AUTOSCALING_POLICY + + policy_path = policy + policy = import_attr(policy) + + if not values.get("_serialized_policy_def"): + self._serialized_policy_def = cloudpickle.dumps(policy) + self._policy = policy_path + + @classmethod + def default(cls): + return cls( + target_ongoing_requests=DEFAULT_TARGET_ONGOING_REQUESTS, + min_replicas=1, + max_replicas=100, + ) + + def get_policy(self) -> Callable: + """Deserialize policy from cloudpickled bytes.""" + return cloudpickle.loads(self._serialized_policy_def) + + def get_upscaling_factor(self) -> PositiveFloat: + if self.upscaling_factor: + return self.upscaling_factor + + return self.upscale_smoothing_factor or self.smoothing_factor + + def get_downscaling_factor(self) -> PositiveFloat: + if self.downscaling_factor: + return self.downscaling_factor + + return self.downscale_smoothing_factor or self.smoothing_factor + + def get_target_ongoing_requests(self) -> PositiveFloat: + return self.target_ongoing_requests + + +# Keep in sync with ServeDeploymentMode in dashboard/client/src/type/serve.ts +@Deprecated +class DeploymentMode(str, Enum): + NoServer = "NoServer" + HeadOnly = "HeadOnly" + EveryNode = "EveryNode" + + +@PublicAPI(stability="stable") +class ProxyLocation(str, Enum): + """Config for where to run proxies to receive ingress traffic to the cluster. + + Options: + + - Disabled: don't run proxies at all. This should be used if you are only + making calls to your applications via deployment handles. + - HeadOnly: only run a single proxy on the head node. + - EveryNode: run a proxy on every node in the cluster that has at least one + replica actor. This is the default. + """ + + Disabled = "Disabled" + HeadOnly = "HeadOnly" + EveryNode = "EveryNode" + + @classmethod + def _to_deployment_mode( + cls, proxy_location: Union["ProxyLocation", str] + ) -> DeploymentMode: + if isinstance(proxy_location, str): + proxy_location = ProxyLocation(proxy_location) + elif not isinstance(proxy_location, ProxyLocation): + raise TypeError( + f"Must be a `ProxyLocation` or str, got: {type(proxy_location)}." + ) + + if proxy_location == ProxyLocation.Disabled: + return DeploymentMode.NoServer + else: + return DeploymentMode(proxy_location.value) + + @classmethod + def _from_deployment_mode( + cls, deployment_mode: Optional[Union[DeploymentMode, str]] + ) -> Optional["ProxyLocation"]: + """Converts DeploymentMode enum into ProxyLocation enum. + + DeploymentMode is a deprecated version of ProxyLocation that's still + used internally throughout Serve. + """ + + if deployment_mode is None: + return None + elif isinstance(deployment_mode, str): + deployment_mode = DeploymentMode(deployment_mode) + elif not isinstance(deployment_mode, DeploymentMode): + raise TypeError( + f"Must be a `DeploymentMode` or str, got: {type(deployment_mode)}." + ) + + if deployment_mode == DeploymentMode.NoServer: + return ProxyLocation.Disabled + else: + return ProxyLocation(deployment_mode.value) + + +@PublicAPI(stability="stable") +class HTTPOptions(BaseModel): + """HTTP options for the proxies. Supported fields: + + - host: Host that the proxies listens for HTTP on. Defaults to + "127.0.0.1". To expose Serve publicly, you probably want to set + this to "0.0.0.0". + - port: Port that the proxies listen for HTTP on. Defaults to 8000. + - root_path: An optional root path to mount the serve application + (for example, "/prefix"). All deployment routes are prefixed + with this path. + - request_timeout_s: End-to-end timeout for HTTP requests. + - keep_alive_timeout_s: Duration to keep idle connections alive when no + requests are ongoing. + + - location: [DEPRECATED: use `proxy_location` field instead] The deployment + location of HTTP servers: + + - "HeadOnly": start one HTTP server on the head node. Serve + assumes the head node is the node you executed serve.start + on. This is the default. + - "EveryNode": start one HTTP server per node. + - "NoServer": disable HTTP server. + + - num_cpus: [DEPRECATED] The number of CPU cores to reserve for each + internal Serve HTTP proxy actor. + """ + + host: Optional[str] = DEFAULT_HTTP_HOST + port: int = DEFAULT_HTTP_PORT + middlewares: List[Any] = [] + location: Optional[DeploymentMode] = DeploymentMode.HeadOnly + num_cpus: int = 0 + root_url: str = "" + root_path: str = "" + request_timeout_s: Optional[float] = None + keep_alive_timeout_s: int = DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S + + @validator("location", always=True) + def location_backfill_no_server(cls, v, values): + if values["host"] is None or v is None: + return DeploymentMode.NoServer + + return v + + @validator("middlewares", always=True) + def warn_for_middlewares(cls, v, values): + if v: + warnings.warn( + "Passing `middlewares` to HTTPOptions is deprecated and will be " + "removed in a future version. Consider using the FastAPI integration " + "to configure middlewares on your deployments: " + "https://docs.ray.io/en/latest/serve/http-guide.html#fastapi-http-deployments" # noqa 501 + ) + return v + + @validator("num_cpus", always=True) + def warn_for_num_cpus(cls, v, values): + if v: + warnings.warn( + "Passing `num_cpus` to HTTPOptions is deprecated and will be " + "removed in a future version." + ) + return v + + class Config: + validate_assignment = True + arbitrary_types_allowed = True + + +@PublicAPI(stability="alpha") +class gRPCOptions(BaseModel): + """gRPC options for the proxies. Supported fields: + + Args: + port (int): + Port for gRPC server if started. Default to 9000. Cannot be + updated once Serve has started running. Serve must be shut down and + restarted with the new port instead. + grpc_servicer_functions (List[str]): + List of import paths for gRPC `add_servicer_to_server` functions to add to + Serve's gRPC proxy. Default to empty list, which means no gRPC methods will + be added and no gRPC server will be started. The servicer functions need to + be importable from the context of where Serve is running. + request_timeout_s: End-to-end timeout for gRPC requests. + """ + + port: int = DEFAULT_GRPC_PORT + grpc_servicer_functions: List[str] = [] + request_timeout_s: Optional[float] = None + + @property + def grpc_servicer_func_callable(self) -> List[Callable]: + """Return a list of callable functions from the grpc_servicer_functions. + + If the function is not callable or not found, it will be ignored and a warning + will be logged. + """ + callables = [] + for func in self.grpc_servicer_functions: + try: + imported_func = import_attr(func) + if callable(imported_func): + callables.append(imported_func) + else: + message = ( + f"{func} is not a callable function! Please make sure " + "the function is imported correctly." + ) + raise ValueError(message) + except ModuleNotFoundError as e: + message = ( + f"{func} can't be imported! Please make sure there are no typo " + "in those functions. Or you might want to rebuild service " + "definitions if .proto file is changed." + ) + raise ModuleNotFoundError(message) from e + + return callables diff --git a/venv/lib/python3.10/site-packages/ray/serve/context.py b/venv/lib/python3.10/site-packages/ray/serve/context.py new file mode 100644 index 0000000000000000000000000000000000000000..ecb412aab37b4379428d6efcdd95d2e683ad3d73 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/context.py @@ -0,0 +1,298 @@ +""" +This file stores global state for a Serve application. Deployment replicas +can use this state to access metadata or the Serve controller. +""" + +import asyncio +import contextvars +import logging +from collections import defaultdict +from dataclasses import dataclass +from typing import Callable, Dict, Optional + +import ray +from ray.exceptions import RayActorError +from ray.serve._private.client import ServeControllerClient +from ray.serve._private.common import ReplicaID +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import ( + SERVE_CONTROLLER_NAME, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.replica_result import ReplicaResult +from ray.serve.exceptions import RayServeException +from ray.serve.grpc_util import RayServegRPCContext +from ray.util.annotations import DeveloperAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +_INTERNAL_REPLICA_CONTEXT: "ReplicaContext" = None +_global_client: ServeControllerClient = None + + +@DeveloperAPI +@dataclass +class ReplicaContext: + """Stores runtime context info for replicas. + + Fields: + - app_name: name of the application the replica is a part of. + - deployment: name of the deployment the replica is a part of. + - replica_tag: unique ID for the replica. + - servable_object: instance of the user class/function this replica is running. + """ + + replica_id: ReplicaID + servable_object: Callable + _deployment_config: DeploymentConfig + + @property + def app_name(self) -> str: + return self.replica_id.deployment_id.app_name + + @property + def deployment(self) -> str: + return self.replica_id.deployment_id.name + + @property + def replica_tag(self) -> str: + return self.replica_id.unique_id + + +def _get_global_client( + _health_check_controller: bool = False, raise_if_no_controller_running: bool = True +) -> Optional[ServeControllerClient]: + """Gets the global client, which stores the controller's handle. + + Args: + _health_check_controller: If True, run a health check on the + cached controller if it exists. If the check fails, try reconnecting + to the controller. + raise_if_no_controller_running: Whether to raise an exception if + there is no currently running Serve controller. + + Returns: + ServeControllerClient to the running Serve controller. If there + is no running controller and raise_if_no_controller_running is + set to False, returns None. + + Raises: + RayServeException: If there is no running Serve controller actor + and raise_if_no_controller_running is set to True. + """ + + try: + if _global_client is not None: + if _health_check_controller: + ray.get(_global_client._controller.check_alive.remote()) + return _global_client + except RayActorError: + logger.info("The cached controller has died. Reconnecting.") + _set_global_client(None) + + return _connect(raise_if_no_controller_running) + + +def _set_global_client(client): + global _global_client + _global_client = client + + +def _get_internal_replica_context(): + return _INTERNAL_REPLICA_CONTEXT + + +def _set_internal_replica_context( + *, + replica_id: ReplicaID, + servable_object: Callable, + _deployment_config: DeploymentConfig, +): + global _INTERNAL_REPLICA_CONTEXT + _INTERNAL_REPLICA_CONTEXT = ReplicaContext( + replica_id=replica_id, + servable_object=servable_object, + _deployment_config=_deployment_config, + ) + + +def _connect(raise_if_no_controller_running: bool = True) -> ServeControllerClient: + """Connect to an existing Serve application on this Ray cluster. + + If called from within a replica, this will connect to the same Serve + app that the replica is running in. + + Returns: + ServeControllerClient that encapsulates a Ray actor handle to the + existing Serve application's Serve Controller. None if there is + no running Serve controller actor and raise_if_no_controller_running + is set to False. + + Raises: + RayServeException: If there is no running Serve controller actor + and raise_if_no_controller_running is set to True. + """ + + # Initialize ray if needed. + ray._private.worker.global_worker._filter_logs_by_job = False + if not ray.is_initialized(): + ray.init(namespace=SERVE_NAMESPACE) + + # Try to get serve controller if it exists + try: + controller = ray.get_actor(SERVE_CONTROLLER_NAME, namespace=SERVE_NAMESPACE) + except ValueError: + if raise_if_no_controller_running: + raise RayServeException( + "There is no Serve instance running on this Ray cluster." + ) + return + + client = ServeControllerClient( + controller, + ) + _set_global_client(client) + return client + + +# Serve request context var which is used for storing the internal +# request context information. +# route_prefix: http url route path, e.g. http://127.0.0.1:/app +# the route is "/app". When you send requests by handle, +# the route is empty. +# request_id: the request id is generated from http proxy, the value +# shouldn't be changed when the variable is set. +# This can be from the client and is used for logging. +# _internal_request_id: the request id is generated from the proxy. Used to track the +# request objects in the system. +# note: +# The request context is readonly to avoid potential +# async task conflicts when using it concurrently. + + +@dataclass(frozen=True) +class _RequestContext: + route: str = "" + request_id: str = "" + _internal_request_id: str = "" + app_name: str = "" + multiplexed_model_id: str = "" + grpc_context: Optional[RayServegRPCContext] = None + is_http_request: bool = False + cancel_on_parent_request_cancel: bool = False + + +_serve_request_context = contextvars.ContextVar( + "Serve internal request context variable", default=None +) + + +def _get_serve_request_context(): + """Get the current request context. + + Returns: + The current request context + """ + + if _serve_request_context.get() is None: + _serve_request_context.set(_RequestContext()) + return _serve_request_context.get() + + +def _set_request_context( + route: str = "", + request_id: str = "", + _internal_request_id: str = "", + app_name: str = "", + multiplexed_model_id: str = "", +): + """Set the request context. If the value is not set, + the current context value will be used.""" + + current_request_context = _get_serve_request_context() + + _serve_request_context.set( + _RequestContext( + route=route or current_request_context.route, + request_id=request_id or current_request_context.request_id, + _internal_request_id=_internal_request_id + or current_request_context._internal_request_id, + app_name=app_name or current_request_context.app_name, + multiplexed_model_id=multiplexed_model_id + or current_request_context.multiplexed_model_id, + ) + ) + + +# `_requests_pending_assignment` is a map from request ID to a +# dictionary of asyncio tasks. +# The request ID points to an ongoing request that is executing on the +# current replica, and the asyncio tasks are ongoing tasks started on +# the router to assign child requests to downstream replicas. + +# A dictionary is used over a set to track the asyncio tasks for more +# efficient addition and deletion time complexity. A uniquely generated +# `response_id` is used to identify each task. + +_requests_pending_assignment: Dict[str, Dict[str, asyncio.Task]] = defaultdict(dict) + + +# Note that the functions below that manipulate +# `_requests_pending_assignment` are NOT thread-safe. They are only +# expected to be called from the same thread/asyncio event-loop. + + +def _get_requests_pending_assignment(parent_request_id: str) -> Dict[str, asyncio.Task]: + if parent_request_id in _requests_pending_assignment: + return _requests_pending_assignment[parent_request_id] + + return {} + + +def _add_request_pending_assignment(parent_request_id: str, response_id: str, task): + # NOTE: `parent_request_id` is the `internal_request_id` corresponding + # to an ongoing Serve request, so it is always non-empty. + _requests_pending_assignment[parent_request_id][response_id] = task + + +def _remove_request_pending_assignment(parent_request_id: str, response_id: str): + if response_id in _requests_pending_assignment[parent_request_id]: + del _requests_pending_assignment[parent_request_id][response_id] + + if len(_requests_pending_assignment[parent_request_id]) == 0: + del _requests_pending_assignment[parent_request_id] + + +# `_in_flight_requests` is a map from request ID to a dictionary of replica results. +# The request ID points to an ongoing Serve request, and the replica results are +# in-flight child requests that have been assigned to a downstream replica. + +# A dictionary is used over a set to track the replica results for more +# efficient addition and deletion time complexity. A uniquely generated +# `response_id` is used to identify each replica result. + +_in_flight_requests: Dict[str, Dict[str, ReplicaResult]] = defaultdict(dict) + +# Note that the functions below that manipulate `_in_flight_requests` +# are NOT thread-safe. They are only expected to be called from the +# same thread/asyncio event-loop. + + +def _get_in_flight_requests(parent_request_id): + if parent_request_id in _in_flight_requests: + return _in_flight_requests[parent_request_id] + + return {} + + +def _add_in_flight_request(parent_request_id, response_id, replica_result): + _in_flight_requests[parent_request_id][response_id] = replica_result + + +def _remove_in_flight_request(parent_request_id, response_id): + if response_id in _in_flight_requests[parent_request_id]: + del _in_flight_requests[parent_request_id][response_id] + + if len(_in_flight_requests[parent_request_id]) == 0: + del _in_flight_requests[parent_request_id] diff --git a/venv/lib/python3.10/site-packages/ray/serve/dag.py b/venv/lib/python3.10/site-packages/ray/serve/dag.py new file mode 100644 index 0000000000000000000000000000000000000000..aee604744557d18c88245fff723480562dbfae67 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/dag.py @@ -0,0 +1,5 @@ +from ray.dag.input_node import InputNode + +__all__ = [ + "InputNode", +] diff --git a/venv/lib/python3.10/site-packages/ray/serve/deployment.py b/venv/lib/python3.10/site-packages/ray/serve/deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..5487ad4d0afccd44c9d4b44f4225ab091634a389 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/deployment.py @@ -0,0 +1,528 @@ +import inspect +import logging +import warnings +from copy import deepcopy +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +from ray.serve._private.config import ( + DeploymentConfig, + ReplicaConfig, + RequestRouterConfig, + handle_num_replicas_auto, +) +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import DEFAULT, Default +from ray.serve.config import AutoscalingConfig +from ray.serve.schema import DeploymentSchema, LoggingConfig, RayActorOptionsSchema +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@PublicAPI(stability="stable") +class Application: + """One or more deployments bound with arguments that can be deployed together. + + Can be passed into another `Deployment.bind()` to compose multiple deployments in a + single application, passed to `serve.run`, or deployed via a Serve config file. + + For example, to define an Application and run it in Python: + + .. code-block:: python + + from ray import serve + from ray.serve import Application + + @serve.deployment + class MyDeployment: + pass + + app: Application = MyDeployment.bind(OtherDeployment.bind()) + serve.run(app) + + To run the same app using the command line interface (CLI): + + .. code-block:: bash + + serve run python_file:app + + To deploy the same app via a config file: + + .. code-block:: yaml + + applications: + my_app: + import_path: python_file:app + + """ + + def __init__(self, bound_deployment: "Deployment"): + # This is used by `build_app`, but made private so users don't use it. + self._bound_deployment = bound_deployment + + +@PublicAPI(stability="stable") +class Deployment: + """Class (or function) decorated with the `@serve.deployment` decorator. + + This is run on a number of replica actors. Requests to those replicas call + this class. + + One or more deployments can be composed together into an `Application` which is + then run via `serve.run` or a config file. + + Example: + + .. code-block:: python + + @serve.deployment + class MyDeployment: + def __init__(self, name: str): + self._name = name + + def __call__(self, request): + return "Hello world!" + + app = MyDeployment.bind() + # Run via `serve.run` or the `serve run` CLI command. + serve.run(app) + + """ + + def __init__( + self, + name: str, + deployment_config: DeploymentConfig, + replica_config: ReplicaConfig, + version: Optional[str] = None, + _internal=False, + ) -> None: + if not _internal: + raise RuntimeError( + "The Deployment constructor should not be called " + "directly. Use `@serve.deployment` instead." + ) + self._validate_name(name) + if not (version is None or isinstance(version, str)): + raise TypeError("version must be a string.") + docs_path = None + if ( + inspect.isclass(replica_config.deployment_def) + and hasattr(replica_config.deployment_def, "__module__") + and replica_config.deployment_def.__module__ == "ray.serve.api" + and hasattr(replica_config.deployment_def, "__fastapi_docs_path__") + ): + docs_path = replica_config.deployment_def.__fastapi_docs_path__ + + self._name = name + self._version = version + self._deployment_config = deployment_config + self._replica_config = replica_config + self._docs_path = docs_path + + def _validate_name(self, name: str): + if not isinstance(name, str): + raise TypeError("name must be a string.") + + # name does not contain # + if "#" in name: + warnings.warn( + f"Deployment names should not contain the '#' character, this will raise an error starting in Ray 2.46.0. " + f"Current name: {name}." + ) + + @property + def name(self) -> str: + """Unique name of this deployment.""" + return self._name + + @property + def version(self) -> Optional[str]: + return self._version + + @property + def func_or_class(self) -> Union[Callable, str]: + """Underlying class or function that this deployment wraps.""" + return self._replica_config.deployment_def + + @property + def num_replicas(self) -> int: + """Target number of replicas.""" + return self._deployment_config.num_replicas + + @property + def user_config(self) -> Any: + """Dynamic user-provided config options.""" + return self._deployment_config.user_config + + @property + def max_ongoing_requests(self) -> int: + """Max number of requests a replica can handle at once.""" + return self._deployment_config.max_ongoing_requests + + @property + def max_queued_requests(self) -> int: + """Max number of requests that can be queued in each deployment handle.""" + return self._deployment_config.max_queued_requests + + @property + def route_prefix(self): + raise ValueError( + "`route_prefix` can no longer be specified at the deployment level. " + "Pass it to `serve.run` or in the application config instead." + ) + + @property + def ray_actor_options(self) -> Optional[Dict]: + """Actor options such as resources required for each replica.""" + return self._replica_config.ray_actor_options + + @property + def init_args(self) -> Tuple[Any]: + return self._replica_config.init_args + + @property + def init_kwargs(self) -> Tuple[Any]: + return self._replica_config.init_kwargs + + @property + def url(self) -> Optional[str]: + logger.warning( + "DeprecationWarning: `Deployment.url` is deprecated " + "and will be removed in the future." + ) + return None + + @property + def logging_config(self) -> Dict: + return self._deployment_config.logging_config + + def set_logging_config(self, logging_config: Dict): + self._deployment_config.logging_config = logging_config + + def __call__(self): + raise RuntimeError( + "Deployments cannot be constructed directly. " + "Use `deployment.deploy() instead.`" + ) + + def bind(self, *args, **kwargs) -> Application: + """Bind the arguments to the deployment and return an Application. + + The returned Application can be deployed using `serve.run` (or via + config file) or bound to another deployment for composition. + """ + return Application(self.options(_init_args=args, _init_kwargs=kwargs)) + + def options( + self, + func_or_class: Optional[Callable] = None, + name: Default[str] = DEFAULT.VALUE, + version: Default[str] = DEFAULT.VALUE, + num_replicas: Default[Optional[Union[int, str]]] = DEFAULT.VALUE, + route_prefix: Default[Union[str, None]] = DEFAULT.VALUE, + ray_actor_options: Default[Optional[Dict]] = DEFAULT.VALUE, + placement_group_bundles: Default[List[Dict[str, float]]] = DEFAULT.VALUE, + placement_group_strategy: Default[str] = DEFAULT.VALUE, + max_replicas_per_node: Default[int] = DEFAULT.VALUE, + user_config: Default[Optional[Any]] = DEFAULT.VALUE, + max_ongoing_requests: Default[int] = DEFAULT.VALUE, + max_queued_requests: Default[int] = DEFAULT.VALUE, + autoscaling_config: Default[ + Union[Dict, AutoscalingConfig, None] + ] = DEFAULT.VALUE, + graceful_shutdown_wait_loop_s: Default[float] = DEFAULT.VALUE, + graceful_shutdown_timeout_s: Default[float] = DEFAULT.VALUE, + health_check_period_s: Default[float] = DEFAULT.VALUE, + health_check_timeout_s: Default[float] = DEFAULT.VALUE, + logging_config: Default[Union[Dict, LoggingConfig, None]] = DEFAULT.VALUE, + request_router_config: Default[ + Union[Dict, RequestRouterConfig, None] + ] = DEFAULT.VALUE, + _init_args: Default[Tuple[Any]] = DEFAULT.VALUE, + _init_kwargs: Default[Dict[Any, Any]] = DEFAULT.VALUE, + _internal: bool = False, + ) -> "Deployment": + """Return a copy of this deployment with updated options. + + Only those options passed in will be updated, all others will remain + unchanged from the existing deployment. + + Refer to the `@serve.deployment` decorator docs for available arguments. + """ + if route_prefix is not DEFAULT.VALUE: + raise ValueError( + "`route_prefix` can no longer be specified at the deployment level. " + "Pass it to `serve.run` or in the application config instead." + ) + + # Modify max_ongoing_requests and autoscaling_config if + # `num_replicas="auto"` + if max_ongoing_requests is None: + raise ValueError("`max_ongoing_requests` must be non-null, got None.") + if num_replicas == "auto": + num_replicas = None + max_ongoing_requests, autoscaling_config = handle_num_replicas_auto( + max_ongoing_requests, autoscaling_config + ) + + ServeUsageTag.AUTO_NUM_REPLICAS_USED.record("1") + + # NOTE: The user_configured_option_names should be the first thing that's + # defined in this method. It depends on the locals() dictionary storing + # only the function args/kwargs. + # Create list of all user-configured options from keyword args + user_configured_option_names = [ + option + for option, value in locals().items() + if option not in {"self", "func_or_class", "_internal"} + and value is not DEFAULT.VALUE + ] + + new_deployment_config = deepcopy(self._deployment_config) + if not _internal: + new_deployment_config.user_configured_option_names.update( + user_configured_option_names + ) + + if num_replicas not in [ + DEFAULT.VALUE, + None, + "auto", + ] and autoscaling_config not in [ + DEFAULT.VALUE, + None, + ]: + raise ValueError( + "Manually setting num_replicas is not allowed when " + "autoscaling_config is provided." + ) + + if num_replicas == 0: + raise ValueError("num_replicas is expected to larger than 0") + + if not _internal and version is not DEFAULT.VALUE: + logger.warning( + "DeprecationWarning: `version` in `Deployment.options()` has been " + "deprecated. Explicitly specifying version will raise an error in the " + "future!" + ) + + elif num_replicas not in [DEFAULT.VALUE, None]: + new_deployment_config.num_replicas = num_replicas + + if user_config is not DEFAULT.VALUE: + new_deployment_config.user_config = user_config + + if max_ongoing_requests is not DEFAULT.VALUE: + new_deployment_config.max_ongoing_requests = max_ongoing_requests + + if max_queued_requests is not DEFAULT.VALUE: + new_deployment_config.max_queued_requests = max_queued_requests + + if func_or_class is None: + func_or_class = self._replica_config.deployment_def + + if name is DEFAULT.VALUE: + name = self._name + + if version is DEFAULT.VALUE: + version = self._version + + if _init_args is DEFAULT.VALUE: + _init_args = self._replica_config.init_args + + if _init_kwargs is DEFAULT.VALUE: + _init_kwargs = self._replica_config.init_kwargs + + if ray_actor_options is DEFAULT.VALUE: + ray_actor_options = self._replica_config.ray_actor_options + + if placement_group_bundles is DEFAULT.VALUE: + placement_group_bundles = self._replica_config.placement_group_bundles + + if placement_group_strategy is DEFAULT.VALUE: + placement_group_strategy = self._replica_config.placement_group_strategy + + if max_replicas_per_node is DEFAULT.VALUE: + max_replicas_per_node = self._replica_config.max_replicas_per_node + + if autoscaling_config is not DEFAULT.VALUE: + new_deployment_config.autoscaling_config = autoscaling_config + + if request_router_config is not DEFAULT.VALUE: + new_deployment_config.request_router_config = request_router_config + + if graceful_shutdown_wait_loop_s is not DEFAULT.VALUE: + new_deployment_config.graceful_shutdown_wait_loop_s = ( + graceful_shutdown_wait_loop_s + ) + + if graceful_shutdown_timeout_s is not DEFAULT.VALUE: + new_deployment_config.graceful_shutdown_timeout_s = ( + graceful_shutdown_timeout_s + ) + + if health_check_period_s is not DEFAULT.VALUE: + new_deployment_config.health_check_period_s = health_check_period_s + + if health_check_timeout_s is not DEFAULT.VALUE: + new_deployment_config.health_check_timeout_s = health_check_timeout_s + + if logging_config is not DEFAULT.VALUE: + if isinstance(logging_config, LoggingConfig): + logging_config = logging_config.dict() + new_deployment_config.logging_config = logging_config + + new_replica_config = ReplicaConfig.create( + func_or_class, + init_args=_init_args, + init_kwargs=_init_kwargs, + ray_actor_options=ray_actor_options, + placement_group_bundles=placement_group_bundles, + placement_group_strategy=placement_group_strategy, + max_replicas_per_node=max_replicas_per_node, + ) + + return Deployment( + name, + new_deployment_config, + new_replica_config, + version=version, + _internal=True, + ) + + def __eq__(self, other): + return all( + [ + self._name == other._name, + self._version == other._version, + self._deployment_config == other._deployment_config, + self._replica_config.init_args == other._replica_config.init_args, + self._replica_config.init_kwargs == other._replica_config.init_kwargs, + self._replica_config.ray_actor_options + == other._replica_config.ray_actor_options, + ] + ) + + def __str__(self): + return f"Deployment(name={self._name})" + + def __repr__(self): + return str(self) + + +def deployment_to_schema(d: Deployment) -> DeploymentSchema: + """Converts a live deployment object to a corresponding structured schema. + + Args: + d: Deployment object to convert + """ + + if d.ray_actor_options is not None: + ray_actor_options_schema = RayActorOptionsSchema.parse_obj(d.ray_actor_options) + else: + ray_actor_options_schema = None + + deployment_options = { + "name": d.name, + "num_replicas": None + if d._deployment_config.autoscaling_config + else d.num_replicas, + "max_ongoing_requests": d.max_ongoing_requests, + "max_queued_requests": d.max_queued_requests, + "user_config": d.user_config, + "autoscaling_config": d._deployment_config.autoscaling_config, + "graceful_shutdown_wait_loop_s": d._deployment_config.graceful_shutdown_wait_loop_s, # noqa: E501 + "graceful_shutdown_timeout_s": d._deployment_config.graceful_shutdown_timeout_s, + "health_check_period_s": d._deployment_config.health_check_period_s, + "health_check_timeout_s": d._deployment_config.health_check_timeout_s, + "ray_actor_options": ray_actor_options_schema, + "placement_group_strategy": d._replica_config.placement_group_strategy, + "placement_group_bundles": d._replica_config.placement_group_bundles, + "max_replicas_per_node": d._replica_config.max_replicas_per_node, + "logging_config": d._deployment_config.logging_config, + "request_router_config": d._deployment_config.request_router_config, + } + + # Let non-user-configured options be set to defaults. If the schema + # is converted back to a deployment, this lets Serve continue tracking + # which options were set by the user. Name is a required field in the + # schema, so it should be passed in explicitly. + for option in list(deployment_options.keys()): + if ( + option != "name" + and option not in d._deployment_config.user_configured_option_names + ): + del deployment_options[option] + + # TODO(Sihan) DeploymentConfig num_replicas and auto_config can be set together + # because internally we use these two field for autoscale and deploy. + # We can improve the code after we separate the user faced deployment config and + # internal deployment config. + return DeploymentSchema(**deployment_options) + + +def schema_to_deployment(s: DeploymentSchema) -> Deployment: + """Creates a deployment with parameters specified in schema. + + The returned deployment CANNOT be deployed immediately. It's func_or_class + value is an empty string (""), which is not a valid import path. The + func_or_class value must be overwritten with a valid function or class + before the deployment can be deployed. + """ + + if s.ray_actor_options is DEFAULT.VALUE: + ray_actor_options = None + else: + ray_actor_options = s.ray_actor_options.dict(exclude_unset=True) + + if s.placement_group_bundles is DEFAULT.VALUE: + placement_group_bundles = None + else: + placement_group_bundles = s.placement_group_bundles + + if s.placement_group_strategy is DEFAULT.VALUE: + placement_group_strategy = None + else: + placement_group_strategy = s.placement_group_strategy + + if s.max_replicas_per_node is DEFAULT.VALUE: + max_replicas_per_node = None + else: + max_replicas_per_node = s.max_replicas_per_node + + deployment_config = DeploymentConfig.from_default( + num_replicas=s.num_replicas, + user_config=s.user_config, + max_ongoing_requests=s.max_ongoing_requests, + max_queued_requests=s.max_queued_requests, + autoscaling_config=s.autoscaling_config, + graceful_shutdown_wait_loop_s=s.graceful_shutdown_wait_loop_s, + graceful_shutdown_timeout_s=s.graceful_shutdown_timeout_s, + health_check_period_s=s.health_check_period_s, + health_check_timeout_s=s.health_check_timeout_s, + logging_config=s.logging_config, + request_router_config=s.request_router_config, + ) + deployment_config.user_configured_option_names = ( + s._get_user_configured_option_names() + ) + + replica_config = ReplicaConfig.create( + deployment_def="", + init_args=(), + init_kwargs={}, + ray_actor_options=ray_actor_options, + placement_group_bundles=placement_group_bundles, + placement_group_strategy=placement_group_strategy, + max_replicas_per_node=max_replicas_per_node, + ) + + return Deployment( + name=s.name, + deployment_config=deployment_config, + replica_config=replica_config, + _internal=True, + ) diff --git a/venv/lib/python3.10/site-packages/ray/serve/exceptions.py b/venv/lib/python3.10/site-packages/ray/serve/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..10033b28f9cd366fbe27fc78383a46340d71fb34 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/exceptions.py @@ -0,0 +1,59 @@ +from typing import Optional + +from ray.exceptions import TaskCancelledError +from ray.serve._private.common import DeploymentID +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="stable") +class RayServeException(Exception): + pass + + +@PublicAPI(stability="alpha") +class BackPressureError(RayServeException): + """Raised when max_queued_requests is exceeded on a DeploymentHandle.""" + + def __init__(self, num_queued_requests: int, max_queued_requests: int): + super().__init__(num_queued_requests, max_queued_requests) + self._message = ( + f"Request dropped due to backpressure " + f"(num_queued_requests={num_queued_requests}, " + f"max_queued_requests={max_queued_requests})." + ) + + def __str__(self) -> str: + return self._message + + @property + def message(self) -> str: + return self._message + + +@PublicAPI(stability="alpha") +class RequestCancelledError(RayServeException, TaskCancelledError): + """Raise when a Serve request is cancelled.""" + + def __init__(self, request_id: Optional[str] = None): + self._request_id: Optional[str] = request_id + + def __str__(self): + if self._request_id: + return f"Request {self._request_id} was cancelled." + else: + return "Request was cancelled." + + +@PublicAPI(stability="alpha") +class DeploymentUnavailableError(RayServeException): + """Raised when a Serve deployment is unavailable to receive requests. + + Currently this happens because the deployment failed to deploy. + """ + + def __init__(self, deployment_id: DeploymentID): + self._deployment_id = deployment_id + + @property + def message(self) -> str: + return f"{self._deployment_id} is unavailable because it failed to deploy." diff --git a/venv/lib/python3.10/site-packages/ray/serve/generated/__pycache__/serve_pb2.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/generated/__pycache__/serve_pb2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baeb3446b1ff2dee95b33cefdde37233bd5cb8d9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/generated/__pycache__/serve_pb2.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/generated/__pycache__/serve_pb2_grpc.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/generated/__pycache__/serve_pb2_grpc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e63777d75bf0f41b92e5572b6c4bd6025d3ddc0f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/generated/__pycache__/serve_pb2_grpc.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/generated/serve_pb2.py b/venv/lib/python3.10/site-packages/ray/serve/generated/serve_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..5b51e203dfffce48ce6ce78fb42b4203a93642d0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/generated/serve_pb2.py @@ -0,0 +1,516 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: src/ray/protobuf/serve.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1csrc/ray/protobuf/serve.proto\x12\tray.serve\"\xcc\x06\n\x11\x41utoscalingConfig\x12!\n\x0cmin_replicas\x18\x01 \x01(\rR\x0bminReplicas\x12!\n\x0cmax_replicas\x18\x02 \x01(\rR\x0bmaxReplicas\x12,\n\x12metrics_interval_s\x18\x03 \x01(\x01R\x10metricsIntervalS\x12+\n\x12look_back_period_s\x18\x04 \x01(\x01R\x0flookBackPeriodS\x12)\n\x10smoothing_factor\x18\x05 \x01(\x01R\x0fsmoothingFactor\x12*\n\x11\x64ownscale_delay_s\x18\x06 \x01(\x01R\x0f\x64ownscaleDelayS\x12&\n\x0fupscale_delay_s\x18\x07 \x01(\x01R\rupscaleDelayS\x12.\n\x10initial_replicas\x18\x08 \x01(\rH\x00R\x0finitialReplicas\x88\x01\x01\x12=\n\x18upscale_smoothing_factor\x18\t \x01(\x01H\x01R\x16upscaleSmoothingFactor\x88\x01\x01\x12\x41\n\x1a\x64ownscale_smoothing_factor\x18\n \x01(\x01H\x02R\x18\x64ownscaleSmoothingFactor\x88\x01\x01\x12\x33\n\x16_serialized_policy_def\x18\x0b \x01(\x0cR\x13SerializedPolicyDef\x12\x17\n\x07_policy\x18\x0c \x01(\tR\x06Policy\x12\x36\n\x17target_ongoing_requests\x18\r \x01(\x01R\x15targetOngoingRequests\x12.\n\x10upscaling_factor\x18\x0e \x01(\x01H\x03R\x0fupscalingFactor\x88\x01\x01\x12\x32\n\x12\x64ownscaling_factor\x18\x0f \x01(\x01H\x04R\x11\x64ownscalingFactor\x88\x01\x01\x42\x13\n\x11_initial_replicasB\x1b\n\x19_upscale_smoothing_factorB\x1d\n\x1b_downscale_smoothing_factorB\x13\n\x11_upscaling_factorB\x15\n\x13_downscaling_factor\"\xeb\x01\n\rLoggingConfig\x12\x33\n\x08\x65ncoding\x18\x01 \x01(\x0e\x32\x17.ray.serve.EncodingTypeR\x08\x65ncoding\x12\x1b\n\tlog_level\x18\x02 \x01(\tR\x08logLevel\x12\x19\n\x08logs_dir\x18\x03 \x01(\tR\x07logsDir\x12*\n\x11\x65nable_access_log\x18\x04 \x01(\x08R\x0f\x65nableAccessLog\x12\x41\n\x1d\x61\x64\x64itional_log_standard_attrs\x18\x05 \x03(\tR\x1a\x61\x64\x64itionalLogStandardAttrs\"\xc9\x02\n\x13RequestRouterConfig\x12\x42\n\x1e_serialized_request_router_cls\x18\x01 \x01(\x0cR\x1aSerializedRequestRouterCls\x12\x30\n\x14request_router_class\x18\x02 \x01(\tR\x12requestRouterClass\x12\x42\n\x1erequest_routing_stats_period_s\x18\x03 \x01(\x01R\x1arequestRoutingStatsPeriodS\x12\x44\n\x1frequest_routing_stats_timeout_s\x18\x04 \x01(\x01R\x1brequestRoutingStatsTimeoutS\x12\x32\n\x15request_router_kwargs\x18\x05 \x01(\x0cR\x13requestRouterKwargs\"\xda\x06\n\x10\x44\x65ploymentConfig\x12!\n\x0cnum_replicas\x18\x01 \x01(\x05R\x0bnumReplicas\x12\x30\n\x14max_ongoing_requests\x18\x02 \x01(\x05R\x12maxOngoingRequests\x12.\n\x13max_queued_requests\x18\x03 \x01(\x05R\x11maxQueuedRequests\x12\x1f\n\x0buser_config\x18\x04 \x01(\x0cR\nuserConfig\x12@\n\x1dgraceful_shutdown_wait_loop_s\x18\x05 \x01(\x01R\x19gracefulShutdownWaitLoopS\x12=\n\x1bgraceful_shutdown_timeout_s\x18\x06 \x01(\x01R\x18gracefulShutdownTimeoutS\x12\x31\n\x15health_check_period_s\x18\x07 \x01(\x01R\x12healthCheckPeriodS\x12\x33\n\x16health_check_timeout_s\x18\x08 \x01(\x01R\x13healthCheckTimeoutS\x12*\n\x11is_cross_language\x18\t \x01(\x08R\x0fisCrossLanguage\x12N\n\x13\x64\x65ployment_language\x18\n \x01(\x0e\x32\x1d.ray.serve.DeploymentLanguageR\x12\x64\x65ploymentLanguage\x12K\n\x12\x61utoscaling_config\x18\x0b \x01(\x0b\x32\x1c.ray.serve.AutoscalingConfigR\x11\x61utoscalingConfig\x12\x18\n\x07version\x18\x0c \x01(\tR\x07version\x12?\n\x1cuser_configured_option_names\x18\r \x03(\tR\x19userConfiguredOptionNames\x12?\n\x0elogging_config\x18\x0e \x01(\x0b\x32\x18.ray.serve.LoggingConfigR\rloggingConfig\x12R\n\x15request_router_config\x18\x13 \x01(\x0b\x32\x1e.ray.serve.RequestRouterConfigR\x13requestRouterConfig\"\xc8\x02\n\x0fRequestMetadata\x12\x1d\n\nrequest_id\x18\x01 \x01(\tR\trequestId\x12.\n\x13internal_request_id\x18\x02 \x01(\tR\x11internalRequestId\x12\x1f\n\x0b\x63\x61ll_method\x18\x03 \x01(\tR\ncallMethod\x12\x41\n\x07\x63ontext\x18\x04 \x03(\x0b\x32\'.ray.serve.RequestMetadata.ContextEntryR\x07\x63ontext\x12\x30\n\x14multiplexed_model_id\x18\x05 \x01(\tR\x12multiplexedModelId\x12\x14\n\x05route\x18\x06 \x01(\tR\x05route\x1a:\n\x0c\x43ontextEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\"$\n\x0eRequestWrapper\x12\x12\n\x04\x62ody\x18\x01 \x01(\x0cR\x04\x62ody\"Y\n\rUpdatedObject\x12\'\n\x0fobject_snapshot\x18\x01 \x01(\x0cR\x0eobjectSnapshot\x12\x1f\n\x0bsnapshot_id\x18\x02 \x01(\x05R\nsnapshotId\"\xbb\x01\n\x0fLongPollRequest\x12\x62\n\x14keys_to_snapshot_ids\x18\x01 \x03(\x0b\x32\x31.ray.serve.LongPollRequest.KeysToSnapshotIdsEntryR\x11keysToSnapshotIds\x1a\x44\n\x16KeysToSnapshotIdsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\x05R\x05value:\x02\x38\x01\"\xc5\x01\n\x0eLongPollResult\x12V\n\x0fupdated_objects\x18\x01 \x03(\x0b\x32-.ray.serve.LongPollResult.UpdatedObjectsEntryR\x0eupdatedObjects\x1a[\n\x13UpdatedObjectsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12.\n\x05value\x18\x02 \x01(\x0b\x32\x18.ray.serve.UpdatedObjectR\x05value:\x02\x38\x01\"\xc1\x01\n\x0c\x45ndpointInfo\x12#\n\rendpoint_name\x18\x01 \x01(\tR\x0c\x65ndpointName\x12\x14\n\x05route\x18\x02 \x01(\tR\x05route\x12;\n\x06\x63onfig\x18\x03 \x03(\x0b\x32#.ray.serve.EndpointInfo.ConfigEntryR\x06\x63onfig\x1a\x39\n\x0b\x43onfigEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\"\xa9\x01\n\x0b\x45ndpointSet\x12\x43\n\tendpoints\x18\x01 \x03(\x0b\x32%.ray.serve.EndpointSet.EndpointsEntryR\tendpoints\x1aU\n\x0e\x45ndpointsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12-\n\x05value\x18\x02 \x01(\x0b\x32\x17.ray.serve.EndpointInfoR\x05value:\x02\x38\x01\"%\n\rActorNameList\x12\x14\n\x05names\x18\x01 \x03(\tR\x05names\"^\n\x14\x44\x65ploymentTargetInfo\x12#\n\rreplica_names\x18\x01 \x03(\tR\x0creplicaNames\x12!\n\x0cis_available\x18\x02 \x01(\x08R\x0bisAvailable\"\xd1\x02\n\x11\x44\x65ploymentVersion\x12!\n\x0c\x63ode_version\x18\x01 \x01(\tR\x0b\x63odeVersion\x12H\n\x11\x64\x65ployment_config\x18\x02 \x01(\x0b\x32\x1b.ray.serve.DeploymentConfigR\x10\x64\x65ploymentConfig\x12*\n\x11ray_actor_options\x18\x03 \x01(\tR\x0frayActorOptions\x12\x36\n\x17placement_group_bundles\x18\x04 \x01(\tR\x15placementGroupBundles\x12\x38\n\x18placement_group_strategy\x18\x05 \x01(\tR\x16placementGroupStrategy\x12\x31\n\x15max_replicas_per_node\x18\x06 \x01(\x05R\x12maxReplicasPerNode\"\xf5\x02\n\rReplicaConfig\x12.\n\x13\x64\x65ployment_def_name\x18\x01 \x01(\tR\x11\x64\x65ploymentDefName\x12%\n\x0e\x64\x65ployment_def\x18\x02 \x01(\x0cR\rdeploymentDef\x12\x1b\n\tinit_args\x18\x03 \x01(\x0cR\x08initArgs\x12\x1f\n\x0binit_kwargs\x18\x04 \x01(\x0cR\ninitKwargs\x12*\n\x11ray_actor_options\x18\x05 \x01(\tR\x0frayActorOptions\x12\x36\n\x17placement_group_bundles\x18\x06 \x01(\tR\x15placementGroupBundles\x12\x38\n\x18placement_group_strategy\x18\x07 \x01(\tR\x16placementGroupStrategy\x12\x31\n\x15max_replicas_per_node\x18\x08 \x01(\x05R\x12maxReplicasPerNode\"\xb5\x03\n\x0e\x44\x65ploymentInfo\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12H\n\x11\x64\x65ployment_config\x18\x02 \x01(\x0b\x32\x1b.ray.serve.DeploymentConfigR\x10\x64\x65ploymentConfig\x12?\n\x0ereplica_config\x18\x03 \x01(\x0b\x32\x18.ray.serve.ReplicaConfigR\rreplicaConfig\x12\"\n\rstart_time_ms\x18\x04 \x01(\x03R\x0bstartTimeMs\x12\x1d\n\nactor_name\x18\x05 \x01(\tR\tactorName\x12\x18\n\x07version\x18\x06 \x01(\tR\x07version\x12\x1e\n\x0b\x65nd_time_ms\x18\x07 \x01(\x03R\tendTimeMs\x12\'\n\x0ftarget_capacity\x18\x08 \x01(\x01R\x0etargetCapacity\x12^\n\x19target_capacity_direction\x18\t \x01(\x0e\x32\".ray.serve.TargetCapacityDirectionR\x17targetCapacityDirection\"k\n\x0f\x44\x65ploymentRoute\x12\x42\n\x0f\x64\x65ployment_info\x18\x01 \x01(\x0b\x32\x19.ray.serve.DeploymentInfoR\x0e\x64\x65ploymentInfo\x12\x14\n\x05route\x18\x02 \x01(\tR\x05route\"^\n\x13\x44\x65ploymentRouteList\x12G\n\x11\x64\x65ployment_routes\x18\x01 \x03(\x0b\x32\x1a.ray.serve.DeploymentRouteR\x10\x64\x65ploymentRoutes\"\xc4\x01\n\x14\x44\x65ploymentStatusInfo\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x33\n\x06status\x18\x02 \x01(\x0e\x32\x1b.ray.serve.DeploymentStatusR\x06status\x12\x18\n\x07message\x18\x03 \x01(\tR\x07message\x12I\n\x0estatus_trigger\x18\x04 \x01(\x0e\x32\".ray.serve.DeploymentStatusTriggerR\rstatusTrigger\"s\n\x18\x44\x65ploymentStatusInfoList\x12W\n\x17\x64\x65ployment_status_infos\x18\x01 \x03(\x0b\x32\x1f.ray.serve.DeploymentStatusInfoR\x15\x64\x65ploymentStatusInfos\"\x9a\x01\n\x15\x41pplicationStatusInfo\x12\x34\n\x06status\x18\x01 \x01(\x0e\x32\x1c.ray.serve.ApplicationStatusR\x06status\x12\x18\n\x07message\x18\x02 \x01(\tR\x07message\x12\x31\n\x14\x64\x65ployment_timestamp\x18\x03 \x01(\x01R\x13\x64\x65ploymentTimestamp\"\xbb\x01\n\x0eStatusOverview\x12?\n\napp_status\x18\x01 \x01(\x0b\x32 .ray.serve.ApplicationStatusInfoR\tappStatus\x12T\n\x13\x64\x65ployment_statuses\x18\x02 \x01(\x0b\x32#.ray.serve.DeploymentStatusInfoListR\x12\x64\x65ploymentStatuses\x12\x12\n\x04name\x18\x03 \x01(\tR\x04name\"\x19\n\x17ListApplicationsRequest\"G\n\x18ListApplicationsResponse\x12+\n\x11\x61pplication_names\x18\x01 \x03(\tR\x10\x61pplicationNames\"\x10\n\x0eHealthzRequest\"+\n\x0fHealthzResponse\x12\x18\n\x07message\x18\x01 \x01(\tR\x07message\"L\n\x12UserDefinedMessage\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x10\n\x03\x66oo\x18\x02 \x01(\tR\x03\x66oo\x12\x10\n\x03num\x18\x03 \x01(\x03R\x03num\"H\n\x13UserDefinedResponse\x12\x1a\n\x08greeting\x18\x01 \x01(\tR\x08greeting\x12\x15\n\x06num_x2\x18\x02 \x01(\x03R\x05numX2\"\x15\n\x13UserDefinedMessage2\"2\n\x14UserDefinedResponse2\x12\x1a\n\x08greeting\x18\x01 \x01(\tR\x08greeting\"T\n\x0c\x46ruitAmounts\x12\x16\n\x06orange\x18\x01 \x01(\x03R\x06orange\x12\x14\n\x05\x61pple\x18\x02 \x01(\x03R\x05\x61pple\x12\x16\n\x06\x62\x61nana\x18\x03 \x01(\x03R\x06\x62\x61nana\"\"\n\nFruitCosts\x12\x14\n\x05\x63osts\x18\x01 \x01(\x02R\x05\x63osts\"\x1f\n\tArrayData\x12\x12\n\x04nums\x18\x01 \x03(\x02R\x04nums\" \n\nStringData\x12\x12\n\x04\x64\x61ta\x18\x01 \x01(\tR\x04\x64\x61ta\"%\n\x0bModelOutput\x12\x16\n\x06output\x18\x01 \x01(\x02R\x06output\"\xb8\x02\n\x0e\x44\x65ploymentArgs\x12\'\n\x0f\x64\x65ployment_name\x18\x01 \x01(\tR\x0e\x64\x65ploymentName\x12+\n\x11\x64\x65ployment_config\x18\x02 \x01(\x0cR\x10\x64\x65ploymentConfig\x12%\n\x0ereplica_config\x18\x03 \x01(\x0cR\rreplicaConfig\x12&\n\x0f\x64\x65ployer_job_id\x18\x04 \x01(\tR\rdeployerJobId\x12&\n\x0croute_prefix\x18\x05 \x01(\tH\x00R\x0broutePrefix\x88\x01\x01\x12\x18\n\x07ingress\x18\x06 \x01(\x08R\x07ingress\x12 \n\tdocs_path\x18\x07 \x01(\tH\x01R\x08\x64ocsPath\x88\x01\x01\x42\x0f\n\r_route_prefixB\x0c\n\n_docs_path*\"\n\x0c\x45ncodingType\x12\x08\n\x04TEXT\x10\x00\x12\x08\n\x04JSON\x10\x01**\n\x12\x44\x65ploymentLanguage\x12\n\n\x06PYTHON\x10\x00\x12\x08\n\x04JAVA\x10\x01*6\n\x17TargetCapacityDirection\x12\t\n\x05UNSET\x10\x00\x12\x06\n\x02UP\x10\x01\x12\x08\n\x04\x44OWN\x10\x02*\xdb\x01\n\x10\x44\x65ploymentStatus\x12\x1e\n\x1a\x44\x45PLOYMENT_STATUS_UPDATING\x10\x00\x12\x1d\n\x19\x44\x45PLOYMENT_STATUS_HEALTHY\x10\x01\x12\x1f\n\x1b\x44\x45PLOYMENT_STATUS_UNHEALTHY\x10\x02\x12#\n\x1f\x44\x45PLOYMENT_STATUS_DEPLOY_FAILED\x10\x03\x12\x1f\n\x1b\x44\x45PLOYMENT_STATUS_UPSCALING\x10\x04\x12!\n\x1d\x44\x45PLOYMENT_STATUS_DOWNSCALING\x10\x05*\xfe\x03\n\x17\x44\x65ploymentStatusTrigger\x12)\n%DEPLOYMENT_STATUS_TRIGGER_UNSPECIFIED\x10\x00\x12\x33\n/DEPLOYMENT_STATUS_TRIGGER_CONFIG_UPDATE_STARTED\x10\x01\x12\x35\n1DEPLOYMENT_STATUS_TRIGGER_CONFIG_UPDATE_COMPLETED\x10\x02\x12/\n+DEPLOYMENT_STATUS_TRIGGER_UPSCALE_COMPLETED\x10\x03\x12\x31\n-DEPLOYMENT_STATUS_TRIGGER_DOWNSCALE_COMPLETED\x10\x04\x12)\n%DEPLOYMENT_STATUS_TRIGGER_AUTOSCALING\x10\x05\x12\x34\n0DEPLOYMENT_STATUS_TRIGGER_REPLICA_STARTUP_FAILED\x10\x06\x12\x31\n-DEPLOYMENT_STATUS_TRIGGER_HEALTH_CHECK_FAILED\x10\x07\x12,\n(DEPLOYMENT_STATUS_TRIGGER_INTERNAL_ERROR\x10\x08\x12&\n\"DEPLOYMENT_STATUS_TRIGGER_DELETING\x10\t*\xe2\x01\n\x11\x41pplicationStatus\x12 \n\x1c\x41PPLICATION_STATUS_DEPLOYING\x10\x00\x12\x1e\n\x1a\x41PPLICATION_STATUS_RUNNING\x10\x01\x12$\n APPLICATION_STATUS_DEPLOY_FAILED\x10\x02\x12\x1f\n\x1b\x41PPLICATION_STATUS_DELETING\x10\x03\x12\"\n\x1e\x41PPLICATION_STATUS_NOT_STARTED\x10\x05\x12 \n\x1c\x41PPLICATION_STATUS_UNHEALTHY\x10\x06\x32\xb3\x01\n\x12RayServeAPIService\x12[\n\x10ListApplications\x12\".ray.serve.ListApplicationsRequest\x1a#.ray.serve.ListApplicationsResponse\x12@\n\x07Healthz\x12\x19.ray.serve.HealthzRequest\x1a\x1a.ray.serve.HealthzResponse2\xc3\x02\n\x12UserDefinedService\x12I\n\x08__call__\x12\x1d.ray.serve.UserDefinedMessage\x1a\x1e.ray.serve.UserDefinedResponse\x12H\n\x07Method1\x12\x1d.ray.serve.UserDefinedMessage\x1a\x1e.ray.serve.UserDefinedResponse\x12J\n\x07Method2\x12\x1e.ray.serve.UserDefinedMessage2\x1a\x1f.ray.serve.UserDefinedResponse2\x12L\n\tStreaming\x12\x1d.ray.serve.UserDefinedMessage\x1a\x1e.ray.serve.UserDefinedResponse0\x01\x32L\n\x0c\x46ruitService\x12<\n\nFruitStand\x12\x17.ray.serve.FruitAmounts\x1a\x15.ray.serve.FruitCosts2\x98\x01\n\x18RayServeBenchmarkService\x12\x39\n\tgrpc_call\x12\x14.ray.serve.ArrayData\x1a\x16.ray.serve.ModelOutput\x12\x41\n\x10\x63\x61ll_with_string\x12\x15.ray.serve.StringData\x1a\x16.ray.serve.ModelOutputB\'\n\x16io.ray.serve.generatedB\x0bServeProtosP\x01\x62\x06proto3') + +_ENCODINGTYPE = DESCRIPTOR.enum_types_by_name['EncodingType'] +EncodingType = enum_type_wrapper.EnumTypeWrapper(_ENCODINGTYPE) +_DEPLOYMENTLANGUAGE = DESCRIPTOR.enum_types_by_name['DeploymentLanguage'] +DeploymentLanguage = enum_type_wrapper.EnumTypeWrapper(_DEPLOYMENTLANGUAGE) +_TARGETCAPACITYDIRECTION = DESCRIPTOR.enum_types_by_name['TargetCapacityDirection'] +TargetCapacityDirection = enum_type_wrapper.EnumTypeWrapper(_TARGETCAPACITYDIRECTION) +_DEPLOYMENTSTATUS = DESCRIPTOR.enum_types_by_name['DeploymentStatus'] +DeploymentStatus = enum_type_wrapper.EnumTypeWrapper(_DEPLOYMENTSTATUS) +_DEPLOYMENTSTATUSTRIGGER = DESCRIPTOR.enum_types_by_name['DeploymentStatusTrigger'] +DeploymentStatusTrigger = enum_type_wrapper.EnumTypeWrapper(_DEPLOYMENTSTATUSTRIGGER) +_APPLICATIONSTATUS = DESCRIPTOR.enum_types_by_name['ApplicationStatus'] +ApplicationStatus = enum_type_wrapper.EnumTypeWrapper(_APPLICATIONSTATUS) +TEXT = 0 +JSON = 1 +PYTHON = 0 +JAVA = 1 +UNSET = 0 +UP = 1 +DOWN = 2 +DEPLOYMENT_STATUS_UPDATING = 0 +DEPLOYMENT_STATUS_HEALTHY = 1 +DEPLOYMENT_STATUS_UNHEALTHY = 2 +DEPLOYMENT_STATUS_DEPLOY_FAILED = 3 +DEPLOYMENT_STATUS_UPSCALING = 4 +DEPLOYMENT_STATUS_DOWNSCALING = 5 +DEPLOYMENT_STATUS_TRIGGER_UNSPECIFIED = 0 +DEPLOYMENT_STATUS_TRIGGER_CONFIG_UPDATE_STARTED = 1 +DEPLOYMENT_STATUS_TRIGGER_CONFIG_UPDATE_COMPLETED = 2 +DEPLOYMENT_STATUS_TRIGGER_UPSCALE_COMPLETED = 3 +DEPLOYMENT_STATUS_TRIGGER_DOWNSCALE_COMPLETED = 4 +DEPLOYMENT_STATUS_TRIGGER_AUTOSCALING = 5 +DEPLOYMENT_STATUS_TRIGGER_REPLICA_STARTUP_FAILED = 6 +DEPLOYMENT_STATUS_TRIGGER_HEALTH_CHECK_FAILED = 7 +DEPLOYMENT_STATUS_TRIGGER_INTERNAL_ERROR = 8 +DEPLOYMENT_STATUS_TRIGGER_DELETING = 9 +APPLICATION_STATUS_DEPLOYING = 0 +APPLICATION_STATUS_RUNNING = 1 +APPLICATION_STATUS_DEPLOY_FAILED = 2 +APPLICATION_STATUS_DELETING = 3 +APPLICATION_STATUS_NOT_STARTED = 5 +APPLICATION_STATUS_UNHEALTHY = 6 + + +_AUTOSCALINGCONFIG = DESCRIPTOR.message_types_by_name['AutoscalingConfig'] +_LOGGINGCONFIG = DESCRIPTOR.message_types_by_name['LoggingConfig'] +_REQUESTROUTERCONFIG = DESCRIPTOR.message_types_by_name['RequestRouterConfig'] +_DEPLOYMENTCONFIG = DESCRIPTOR.message_types_by_name['DeploymentConfig'] +_REQUESTMETADATA = DESCRIPTOR.message_types_by_name['RequestMetadata'] +_REQUESTMETADATA_CONTEXTENTRY = _REQUESTMETADATA.nested_types_by_name['ContextEntry'] +_REQUESTWRAPPER = DESCRIPTOR.message_types_by_name['RequestWrapper'] +_UPDATEDOBJECT = DESCRIPTOR.message_types_by_name['UpdatedObject'] +_LONGPOLLREQUEST = DESCRIPTOR.message_types_by_name['LongPollRequest'] +_LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY = _LONGPOLLREQUEST.nested_types_by_name['KeysToSnapshotIdsEntry'] +_LONGPOLLRESULT = DESCRIPTOR.message_types_by_name['LongPollResult'] +_LONGPOLLRESULT_UPDATEDOBJECTSENTRY = _LONGPOLLRESULT.nested_types_by_name['UpdatedObjectsEntry'] +_ENDPOINTINFO = DESCRIPTOR.message_types_by_name['EndpointInfo'] +_ENDPOINTINFO_CONFIGENTRY = _ENDPOINTINFO.nested_types_by_name['ConfigEntry'] +_ENDPOINTSET = DESCRIPTOR.message_types_by_name['EndpointSet'] +_ENDPOINTSET_ENDPOINTSENTRY = _ENDPOINTSET.nested_types_by_name['EndpointsEntry'] +_ACTORNAMELIST = DESCRIPTOR.message_types_by_name['ActorNameList'] +_DEPLOYMENTTARGETINFO = DESCRIPTOR.message_types_by_name['DeploymentTargetInfo'] +_DEPLOYMENTVERSION = DESCRIPTOR.message_types_by_name['DeploymentVersion'] +_REPLICACONFIG = DESCRIPTOR.message_types_by_name['ReplicaConfig'] +_DEPLOYMENTINFO = DESCRIPTOR.message_types_by_name['DeploymentInfo'] +_DEPLOYMENTROUTE = DESCRIPTOR.message_types_by_name['DeploymentRoute'] +_DEPLOYMENTROUTELIST = DESCRIPTOR.message_types_by_name['DeploymentRouteList'] +_DEPLOYMENTSTATUSINFO = DESCRIPTOR.message_types_by_name['DeploymentStatusInfo'] +_DEPLOYMENTSTATUSINFOLIST = DESCRIPTOR.message_types_by_name['DeploymentStatusInfoList'] +_APPLICATIONSTATUSINFO = DESCRIPTOR.message_types_by_name['ApplicationStatusInfo'] +_STATUSOVERVIEW = DESCRIPTOR.message_types_by_name['StatusOverview'] +_LISTAPPLICATIONSREQUEST = DESCRIPTOR.message_types_by_name['ListApplicationsRequest'] +_LISTAPPLICATIONSRESPONSE = DESCRIPTOR.message_types_by_name['ListApplicationsResponse'] +_HEALTHZREQUEST = DESCRIPTOR.message_types_by_name['HealthzRequest'] +_HEALTHZRESPONSE = DESCRIPTOR.message_types_by_name['HealthzResponse'] +_USERDEFINEDMESSAGE = DESCRIPTOR.message_types_by_name['UserDefinedMessage'] +_USERDEFINEDRESPONSE = DESCRIPTOR.message_types_by_name['UserDefinedResponse'] +_USERDEFINEDMESSAGE2 = DESCRIPTOR.message_types_by_name['UserDefinedMessage2'] +_USERDEFINEDRESPONSE2 = DESCRIPTOR.message_types_by_name['UserDefinedResponse2'] +_FRUITAMOUNTS = DESCRIPTOR.message_types_by_name['FruitAmounts'] +_FRUITCOSTS = DESCRIPTOR.message_types_by_name['FruitCosts'] +_ARRAYDATA = DESCRIPTOR.message_types_by_name['ArrayData'] +_STRINGDATA = DESCRIPTOR.message_types_by_name['StringData'] +_MODELOUTPUT = DESCRIPTOR.message_types_by_name['ModelOutput'] +_DEPLOYMENTARGS = DESCRIPTOR.message_types_by_name['DeploymentArgs'] +AutoscalingConfig = _reflection.GeneratedProtocolMessageType('AutoscalingConfig', (_message.Message,), { + 'DESCRIPTOR' : _AUTOSCALINGCONFIG, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.AutoscalingConfig) + }) +_sym_db.RegisterMessage(AutoscalingConfig) + +LoggingConfig = _reflection.GeneratedProtocolMessageType('LoggingConfig', (_message.Message,), { + 'DESCRIPTOR' : _LOGGINGCONFIG, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.LoggingConfig) + }) +_sym_db.RegisterMessage(LoggingConfig) + +RequestRouterConfig = _reflection.GeneratedProtocolMessageType('RequestRouterConfig', (_message.Message,), { + 'DESCRIPTOR' : _REQUESTROUTERCONFIG, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.RequestRouterConfig) + }) +_sym_db.RegisterMessage(RequestRouterConfig) + +DeploymentConfig = _reflection.GeneratedProtocolMessageType('DeploymentConfig', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTCONFIG, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentConfig) + }) +_sym_db.RegisterMessage(DeploymentConfig) + +RequestMetadata = _reflection.GeneratedProtocolMessageType('RequestMetadata', (_message.Message,), { + + 'ContextEntry' : _reflection.GeneratedProtocolMessageType('ContextEntry', (_message.Message,), { + 'DESCRIPTOR' : _REQUESTMETADATA_CONTEXTENTRY, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.RequestMetadata.ContextEntry) + }) + , + 'DESCRIPTOR' : _REQUESTMETADATA, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.RequestMetadata) + }) +_sym_db.RegisterMessage(RequestMetadata) +_sym_db.RegisterMessage(RequestMetadata.ContextEntry) + +RequestWrapper = _reflection.GeneratedProtocolMessageType('RequestWrapper', (_message.Message,), { + 'DESCRIPTOR' : _REQUESTWRAPPER, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.RequestWrapper) + }) +_sym_db.RegisterMessage(RequestWrapper) + +UpdatedObject = _reflection.GeneratedProtocolMessageType('UpdatedObject', (_message.Message,), { + 'DESCRIPTOR' : _UPDATEDOBJECT, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.UpdatedObject) + }) +_sym_db.RegisterMessage(UpdatedObject) + +LongPollRequest = _reflection.GeneratedProtocolMessageType('LongPollRequest', (_message.Message,), { + + 'KeysToSnapshotIdsEntry' : _reflection.GeneratedProtocolMessageType('KeysToSnapshotIdsEntry', (_message.Message,), { + 'DESCRIPTOR' : _LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.LongPollRequest.KeysToSnapshotIdsEntry) + }) + , + 'DESCRIPTOR' : _LONGPOLLREQUEST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.LongPollRequest) + }) +_sym_db.RegisterMessage(LongPollRequest) +_sym_db.RegisterMessage(LongPollRequest.KeysToSnapshotIdsEntry) + +LongPollResult = _reflection.GeneratedProtocolMessageType('LongPollResult', (_message.Message,), { + + 'UpdatedObjectsEntry' : _reflection.GeneratedProtocolMessageType('UpdatedObjectsEntry', (_message.Message,), { + 'DESCRIPTOR' : _LONGPOLLRESULT_UPDATEDOBJECTSENTRY, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.LongPollResult.UpdatedObjectsEntry) + }) + , + 'DESCRIPTOR' : _LONGPOLLRESULT, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.LongPollResult) + }) +_sym_db.RegisterMessage(LongPollResult) +_sym_db.RegisterMessage(LongPollResult.UpdatedObjectsEntry) + +EndpointInfo = _reflection.GeneratedProtocolMessageType('EndpointInfo', (_message.Message,), { + + 'ConfigEntry' : _reflection.GeneratedProtocolMessageType('ConfigEntry', (_message.Message,), { + 'DESCRIPTOR' : _ENDPOINTINFO_CONFIGENTRY, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.EndpointInfo.ConfigEntry) + }) + , + 'DESCRIPTOR' : _ENDPOINTINFO, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.EndpointInfo) + }) +_sym_db.RegisterMessage(EndpointInfo) +_sym_db.RegisterMessage(EndpointInfo.ConfigEntry) + +EndpointSet = _reflection.GeneratedProtocolMessageType('EndpointSet', (_message.Message,), { + + 'EndpointsEntry' : _reflection.GeneratedProtocolMessageType('EndpointsEntry', (_message.Message,), { + 'DESCRIPTOR' : _ENDPOINTSET_ENDPOINTSENTRY, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.EndpointSet.EndpointsEntry) + }) + , + 'DESCRIPTOR' : _ENDPOINTSET, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.EndpointSet) + }) +_sym_db.RegisterMessage(EndpointSet) +_sym_db.RegisterMessage(EndpointSet.EndpointsEntry) + +ActorNameList = _reflection.GeneratedProtocolMessageType('ActorNameList', (_message.Message,), { + 'DESCRIPTOR' : _ACTORNAMELIST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ActorNameList) + }) +_sym_db.RegisterMessage(ActorNameList) + +DeploymentTargetInfo = _reflection.GeneratedProtocolMessageType('DeploymentTargetInfo', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTTARGETINFO, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentTargetInfo) + }) +_sym_db.RegisterMessage(DeploymentTargetInfo) + +DeploymentVersion = _reflection.GeneratedProtocolMessageType('DeploymentVersion', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTVERSION, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentVersion) + }) +_sym_db.RegisterMessage(DeploymentVersion) + +ReplicaConfig = _reflection.GeneratedProtocolMessageType('ReplicaConfig', (_message.Message,), { + 'DESCRIPTOR' : _REPLICACONFIG, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ReplicaConfig) + }) +_sym_db.RegisterMessage(ReplicaConfig) + +DeploymentInfo = _reflection.GeneratedProtocolMessageType('DeploymentInfo', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTINFO, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentInfo) + }) +_sym_db.RegisterMessage(DeploymentInfo) + +DeploymentRoute = _reflection.GeneratedProtocolMessageType('DeploymentRoute', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTROUTE, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentRoute) + }) +_sym_db.RegisterMessage(DeploymentRoute) + +DeploymentRouteList = _reflection.GeneratedProtocolMessageType('DeploymentRouteList', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTROUTELIST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentRouteList) + }) +_sym_db.RegisterMessage(DeploymentRouteList) + +DeploymentStatusInfo = _reflection.GeneratedProtocolMessageType('DeploymentStatusInfo', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTSTATUSINFO, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentStatusInfo) + }) +_sym_db.RegisterMessage(DeploymentStatusInfo) + +DeploymentStatusInfoList = _reflection.GeneratedProtocolMessageType('DeploymentStatusInfoList', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTSTATUSINFOLIST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentStatusInfoList) + }) +_sym_db.RegisterMessage(DeploymentStatusInfoList) + +ApplicationStatusInfo = _reflection.GeneratedProtocolMessageType('ApplicationStatusInfo', (_message.Message,), { + 'DESCRIPTOR' : _APPLICATIONSTATUSINFO, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ApplicationStatusInfo) + }) +_sym_db.RegisterMessage(ApplicationStatusInfo) + +StatusOverview = _reflection.GeneratedProtocolMessageType('StatusOverview', (_message.Message,), { + 'DESCRIPTOR' : _STATUSOVERVIEW, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.StatusOverview) + }) +_sym_db.RegisterMessage(StatusOverview) + +ListApplicationsRequest = _reflection.GeneratedProtocolMessageType('ListApplicationsRequest', (_message.Message,), { + 'DESCRIPTOR' : _LISTAPPLICATIONSREQUEST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ListApplicationsRequest) + }) +_sym_db.RegisterMessage(ListApplicationsRequest) + +ListApplicationsResponse = _reflection.GeneratedProtocolMessageType('ListApplicationsResponse', (_message.Message,), { + 'DESCRIPTOR' : _LISTAPPLICATIONSRESPONSE, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ListApplicationsResponse) + }) +_sym_db.RegisterMessage(ListApplicationsResponse) + +HealthzRequest = _reflection.GeneratedProtocolMessageType('HealthzRequest', (_message.Message,), { + 'DESCRIPTOR' : _HEALTHZREQUEST, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.HealthzRequest) + }) +_sym_db.RegisterMessage(HealthzRequest) + +HealthzResponse = _reflection.GeneratedProtocolMessageType('HealthzResponse', (_message.Message,), { + 'DESCRIPTOR' : _HEALTHZRESPONSE, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.HealthzResponse) + }) +_sym_db.RegisterMessage(HealthzResponse) + +UserDefinedMessage = _reflection.GeneratedProtocolMessageType('UserDefinedMessage', (_message.Message,), { + 'DESCRIPTOR' : _USERDEFINEDMESSAGE, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.UserDefinedMessage) + }) +_sym_db.RegisterMessage(UserDefinedMessage) + +UserDefinedResponse = _reflection.GeneratedProtocolMessageType('UserDefinedResponse', (_message.Message,), { + 'DESCRIPTOR' : _USERDEFINEDRESPONSE, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.UserDefinedResponse) + }) +_sym_db.RegisterMessage(UserDefinedResponse) + +UserDefinedMessage2 = _reflection.GeneratedProtocolMessageType('UserDefinedMessage2', (_message.Message,), { + 'DESCRIPTOR' : _USERDEFINEDMESSAGE2, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.UserDefinedMessage2) + }) +_sym_db.RegisterMessage(UserDefinedMessage2) + +UserDefinedResponse2 = _reflection.GeneratedProtocolMessageType('UserDefinedResponse2', (_message.Message,), { + 'DESCRIPTOR' : _USERDEFINEDRESPONSE2, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.UserDefinedResponse2) + }) +_sym_db.RegisterMessage(UserDefinedResponse2) + +FruitAmounts = _reflection.GeneratedProtocolMessageType('FruitAmounts', (_message.Message,), { + 'DESCRIPTOR' : _FRUITAMOUNTS, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.FruitAmounts) + }) +_sym_db.RegisterMessage(FruitAmounts) + +FruitCosts = _reflection.GeneratedProtocolMessageType('FruitCosts', (_message.Message,), { + 'DESCRIPTOR' : _FRUITCOSTS, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.FruitCosts) + }) +_sym_db.RegisterMessage(FruitCosts) + +ArrayData = _reflection.GeneratedProtocolMessageType('ArrayData', (_message.Message,), { + 'DESCRIPTOR' : _ARRAYDATA, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ArrayData) + }) +_sym_db.RegisterMessage(ArrayData) + +StringData = _reflection.GeneratedProtocolMessageType('StringData', (_message.Message,), { + 'DESCRIPTOR' : _STRINGDATA, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.StringData) + }) +_sym_db.RegisterMessage(StringData) + +ModelOutput = _reflection.GeneratedProtocolMessageType('ModelOutput', (_message.Message,), { + 'DESCRIPTOR' : _MODELOUTPUT, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.ModelOutput) + }) +_sym_db.RegisterMessage(ModelOutput) + +DeploymentArgs = _reflection.GeneratedProtocolMessageType('DeploymentArgs', (_message.Message,), { + 'DESCRIPTOR' : _DEPLOYMENTARGS, + '__module__' : 'ray.serve.generated.serve_pb2' + # @@protoc_insertion_point(class_scope:ray.serve.DeploymentArgs) + }) +_sym_db.RegisterMessage(DeploymentArgs) + +_RAYSERVEAPISERVICE = DESCRIPTOR.services_by_name['RayServeAPIService'] +_USERDEFINEDSERVICE = DESCRIPTOR.services_by_name['UserDefinedService'] +_FRUITSERVICE = DESCRIPTOR.services_by_name['FruitService'] +_RAYSERVEBENCHMARKSERVICE = DESCRIPTOR.services_by_name['RayServeBenchmarkService'] +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'\n\026io.ray.serve.generatedB\013ServeProtosP\001' + _REQUESTMETADATA_CONTEXTENTRY._options = None + _REQUESTMETADATA_CONTEXTENTRY._serialized_options = b'8\001' + _LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY._options = None + _LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY._serialized_options = b'8\001' + _LONGPOLLRESULT_UPDATEDOBJECTSENTRY._options = None + _LONGPOLLRESULT_UPDATEDOBJECTSENTRY._serialized_options = b'8\001' + _ENDPOINTINFO_CONFIGENTRY._options = None + _ENDPOINTINFO_CONFIGENTRY._serialized_options = b'8\001' + _ENDPOINTSET_ENDPOINTSENTRY._options = None + _ENDPOINTSET_ENDPOINTSENTRY._serialized_options = b'8\001' + _ENCODINGTYPE._serialized_start=6631 + _ENCODINGTYPE._serialized_end=6665 + _DEPLOYMENTLANGUAGE._serialized_start=6667 + _DEPLOYMENTLANGUAGE._serialized_end=6709 + _TARGETCAPACITYDIRECTION._serialized_start=6711 + _TARGETCAPACITYDIRECTION._serialized_end=6765 + _DEPLOYMENTSTATUS._serialized_start=6768 + _DEPLOYMENTSTATUS._serialized_end=6987 + _DEPLOYMENTSTATUSTRIGGER._serialized_start=6990 + _DEPLOYMENTSTATUSTRIGGER._serialized_end=7500 + _APPLICATIONSTATUS._serialized_start=7503 + _APPLICATIONSTATUS._serialized_end=7729 + _AUTOSCALINGCONFIG._serialized_start=44 + _AUTOSCALINGCONFIG._serialized_end=888 + _LOGGINGCONFIG._serialized_start=891 + _LOGGINGCONFIG._serialized_end=1126 + _REQUESTROUTERCONFIG._serialized_start=1129 + _REQUESTROUTERCONFIG._serialized_end=1458 + _DEPLOYMENTCONFIG._serialized_start=1461 + _DEPLOYMENTCONFIG._serialized_end=2319 + _REQUESTMETADATA._serialized_start=2322 + _REQUESTMETADATA._serialized_end=2650 + _REQUESTMETADATA_CONTEXTENTRY._serialized_start=2592 + _REQUESTMETADATA_CONTEXTENTRY._serialized_end=2650 + _REQUESTWRAPPER._serialized_start=2652 + _REQUESTWRAPPER._serialized_end=2688 + _UPDATEDOBJECT._serialized_start=2690 + _UPDATEDOBJECT._serialized_end=2779 + _LONGPOLLREQUEST._serialized_start=2782 + _LONGPOLLREQUEST._serialized_end=2969 + _LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY._serialized_start=2901 + _LONGPOLLREQUEST_KEYSTOSNAPSHOTIDSENTRY._serialized_end=2969 + _LONGPOLLRESULT._serialized_start=2972 + _LONGPOLLRESULT._serialized_end=3169 + _LONGPOLLRESULT_UPDATEDOBJECTSENTRY._serialized_start=3078 + _LONGPOLLRESULT_UPDATEDOBJECTSENTRY._serialized_end=3169 + _ENDPOINTINFO._serialized_start=3172 + _ENDPOINTINFO._serialized_end=3365 + _ENDPOINTINFO_CONFIGENTRY._serialized_start=3308 + _ENDPOINTINFO_CONFIGENTRY._serialized_end=3365 + _ENDPOINTSET._serialized_start=3368 + _ENDPOINTSET._serialized_end=3537 + _ENDPOINTSET_ENDPOINTSENTRY._serialized_start=3452 + _ENDPOINTSET_ENDPOINTSENTRY._serialized_end=3537 + _ACTORNAMELIST._serialized_start=3539 + _ACTORNAMELIST._serialized_end=3576 + _DEPLOYMENTTARGETINFO._serialized_start=3578 + _DEPLOYMENTTARGETINFO._serialized_end=3672 + _DEPLOYMENTVERSION._serialized_start=3675 + _DEPLOYMENTVERSION._serialized_end=4012 + _REPLICACONFIG._serialized_start=4015 + _REPLICACONFIG._serialized_end=4388 + _DEPLOYMENTINFO._serialized_start=4391 + _DEPLOYMENTINFO._serialized_end=4828 + _DEPLOYMENTROUTE._serialized_start=4830 + _DEPLOYMENTROUTE._serialized_end=4937 + _DEPLOYMENTROUTELIST._serialized_start=4939 + _DEPLOYMENTROUTELIST._serialized_end=5033 + _DEPLOYMENTSTATUSINFO._serialized_start=5036 + _DEPLOYMENTSTATUSINFO._serialized_end=5232 + _DEPLOYMENTSTATUSINFOLIST._serialized_start=5234 + _DEPLOYMENTSTATUSINFOLIST._serialized_end=5349 + _APPLICATIONSTATUSINFO._serialized_start=5352 + _APPLICATIONSTATUSINFO._serialized_end=5506 + _STATUSOVERVIEW._serialized_start=5509 + _STATUSOVERVIEW._serialized_end=5696 + _LISTAPPLICATIONSREQUEST._serialized_start=5698 + _LISTAPPLICATIONSREQUEST._serialized_end=5723 + _LISTAPPLICATIONSRESPONSE._serialized_start=5725 + _LISTAPPLICATIONSRESPONSE._serialized_end=5796 + _HEALTHZREQUEST._serialized_start=5798 + _HEALTHZREQUEST._serialized_end=5814 + _HEALTHZRESPONSE._serialized_start=5816 + _HEALTHZRESPONSE._serialized_end=5859 + _USERDEFINEDMESSAGE._serialized_start=5861 + _USERDEFINEDMESSAGE._serialized_end=5937 + _USERDEFINEDRESPONSE._serialized_start=5939 + _USERDEFINEDRESPONSE._serialized_end=6011 + _USERDEFINEDMESSAGE2._serialized_start=6013 + _USERDEFINEDMESSAGE2._serialized_end=6034 + _USERDEFINEDRESPONSE2._serialized_start=6036 + _USERDEFINEDRESPONSE2._serialized_end=6086 + _FRUITAMOUNTS._serialized_start=6088 + _FRUITAMOUNTS._serialized_end=6172 + _FRUITCOSTS._serialized_start=6174 + _FRUITCOSTS._serialized_end=6208 + _ARRAYDATA._serialized_start=6210 + _ARRAYDATA._serialized_end=6241 + _STRINGDATA._serialized_start=6243 + _STRINGDATA._serialized_end=6275 + _MODELOUTPUT._serialized_start=6277 + _MODELOUTPUT._serialized_end=6314 + _DEPLOYMENTARGS._serialized_start=6317 + _DEPLOYMENTARGS._serialized_end=6629 + _RAYSERVEAPISERVICE._serialized_start=7732 + _RAYSERVEAPISERVICE._serialized_end=7911 + _USERDEFINEDSERVICE._serialized_start=7914 + _USERDEFINEDSERVICE._serialized_end=8237 + _FRUITSERVICE._serialized_start=8239 + _FRUITSERVICE._serialized_end=8315 + _RAYSERVEBENCHMARKSERVICE._serialized_start=8318 + _RAYSERVEBENCHMARKSERVICE._serialized_end=8470 +# @@protoc_insertion_point(module_scope) diff --git a/venv/lib/python3.10/site-packages/ray/serve/generated/serve_pb2_grpc.py b/venv/lib/python3.10/site-packages/ray/serve/generated/serve_pb2_grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a0fbfd5beb60db0b27f1914bb396a55049dfb8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/generated/serve_pb2_grpc.py @@ -0,0 +1,414 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" +import grpc + +from . import serve_pb2 as src_dot_ray_dot_protobuf_dot_serve__pb2 + + +class RayServeAPIServiceStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.ListApplications = channel.unary_unary( + '/ray.serve.RayServeAPIService/ListApplications', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsRequest.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsResponse.FromString, + ) + self.Healthz = channel.unary_unary( + '/ray.serve.RayServeAPIService/Healthz', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzRequest.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzResponse.FromString, + ) + + +class RayServeAPIServiceServicer(object): + """Missing associated documentation comment in .proto file.""" + + def ListApplications(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Healthz(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_RayServeAPIServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + 'ListApplications': grpc.unary_unary_rpc_method_handler( + servicer.ListApplications, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsRequest.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsResponse.SerializeToString, + ), + 'Healthz': grpc.unary_unary_rpc_method_handler( + servicer.Healthz, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzRequest.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'ray.serve.RayServeAPIService', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class RayServeAPIService(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def ListApplications(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.RayServeAPIService/ListApplications', + src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsRequest.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.ListApplicationsResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Healthz(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.RayServeAPIService/Healthz', + src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzRequest.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.HealthzResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + +class UserDefinedServiceStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.__call__ = channel.unary_unary( + '/ray.serve.UserDefinedService/__call__', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + ) + self.Method1 = channel.unary_unary( + '/ray.serve.UserDefinedService/Method1', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + ) + self.Method2 = channel.unary_unary( + '/ray.serve.UserDefinedService/Method2', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage2.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse2.FromString, + ) + self.Streaming = channel.unary_stream( + '/ray.serve.UserDefinedService/Streaming', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + ) + + +class UserDefinedServiceServicer(object): + """Missing associated documentation comment in .proto file.""" + + def __call__(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Method1(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Method2(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Streaming(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_UserDefinedServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + '__call__': grpc.unary_unary_rpc_method_handler( + servicer.__call__, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.SerializeToString, + ), + 'Method1': grpc.unary_unary_rpc_method_handler( + servicer.Method1, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.SerializeToString, + ), + 'Method2': grpc.unary_unary_rpc_method_handler( + servicer.Method2, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage2.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse2.SerializeToString, + ), + 'Streaming': grpc.unary_stream_rpc_method_handler( + servicer.Streaming, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'ray.serve.UserDefinedService', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class UserDefinedService(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def __call__(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.UserDefinedService/__call__', + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Method1(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.UserDefinedService/Method1', + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Method2(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.UserDefinedService/Method2', + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage2.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse2.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def Streaming(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_stream(request, target, '/ray.serve.UserDefinedService/Streaming', + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedMessage.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.UserDefinedResponse.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + +class FruitServiceStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.FruitStand = channel.unary_unary( + '/ray.serve.FruitService/FruitStand', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.FruitAmounts.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.FruitCosts.FromString, + ) + + +class FruitServiceServicer(object): + """Missing associated documentation comment in .proto file.""" + + def FruitStand(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_FruitServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + 'FruitStand': grpc.unary_unary_rpc_method_handler( + servicer.FruitStand, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.FruitAmounts.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.FruitCosts.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'ray.serve.FruitService', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class FruitService(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def FruitStand(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.FruitService/FruitStand', + src_dot_ray_dot_protobuf_dot_serve__pb2.FruitAmounts.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.FruitCosts.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + +class RayServeBenchmarkServiceStub(object): + """Missing associated documentation comment in .proto file.""" + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.grpc_call = channel.unary_unary( + '/ray.serve.RayServeBenchmarkService/grpc_call', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ArrayData.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.FromString, + ) + self.call_with_string = channel.unary_unary( + '/ray.serve.RayServeBenchmarkService/call_with_string', + request_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.StringData.SerializeToString, + response_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.FromString, + ) + + +class RayServeBenchmarkServiceServicer(object): + """Missing associated documentation comment in .proto file.""" + + def grpc_call(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def call_with_string(self, request, context): + """Missing associated documentation comment in .proto file.""" + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_RayServeBenchmarkServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + 'grpc_call': grpc.unary_unary_rpc_method_handler( + servicer.grpc_call, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ArrayData.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.SerializeToString, + ), + 'call_with_string': grpc.unary_unary_rpc_method_handler( + servicer.call_with_string, + request_deserializer=src_dot_ray_dot_protobuf_dot_serve__pb2.StringData.FromString, + response_serializer=src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'ray.serve.RayServeBenchmarkService', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + # This class is part of an EXPERIMENTAL API. +class RayServeBenchmarkService(object): + """Missing associated documentation comment in .proto file.""" + + @staticmethod + def grpc_call(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.RayServeBenchmarkService/grpc_call', + src_dot_ray_dot_protobuf_dot_serve__pb2.ArrayData.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) + + @staticmethod + def call_with_string(request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None): + return grpc.experimental.unary_unary(request, target, '/ray.serve.RayServeBenchmarkService/call_with_string', + src_dot_ray_dot_protobuf_dot_serve__pb2.StringData.SerializeToString, + src_dot_ray_dot_protobuf_dot_serve__pb2.ModelOutput.FromString, + options, channel_credentials, + insecure, call_credentials, compression, wait_for_ready, timeout, metadata) diff --git a/venv/lib/python3.10/site-packages/ray/serve/gradio_integrations.py b/venv/lib/python3.10/site-packages/ray/serve/gradio_integrations.py new file mode 100644 index 0000000000000000000000000000000000000000..dc8960d78c8b41da612a2e35e41310d729e53350 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/gradio_integrations.py @@ -0,0 +1,32 @@ +import logging +from typing import Callable + +from ray import serve +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.http_util import ASGIAppReplicaWrapper +from ray.util.annotations import PublicAPI + +try: + from gradio import Blocks, routes +except ModuleNotFoundError: + print("Gradio isn't installed. Run `pip install gradio` to install Gradio.") + raise + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@PublicAPI(stability="alpha") +class GradioIngress(ASGIAppReplicaWrapper): + """User-facing class that wraps a Gradio App in a Serve Deployment.""" + + def __init__(self, builder: Callable[[], Blocks]): + """Builds and wraps an ASGI app from the provided builder. + + The builder should take no arguments and return a Gradio App (of type Interface + or Blocks). + """ + io: Blocks = builder() + super().__init__(routes.App.create_app(io)) + + +GradioServer = serve.deployment(GradioIngress) diff --git a/venv/lib/python3.10/site-packages/ray/serve/grpc_util.py b/venv/lib/python3.10/site-packages/ray/serve/grpc_util.py new file mode 100644 index 0000000000000000000000000000000000000000..2b258c5a261437041f98afcd2089b51b2e4a48fb --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/grpc_util.py @@ -0,0 +1,169 @@ +from typing import Any, Dict, List, Optional, Tuple + +import grpc + +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="beta") +class RayServegRPCContext: + """Context manager to set and get gRPC context. + + This class implements most of the methods from ServicerContext + (see: https://grpc.github.io/grpc/python/grpc.html#grpc.ServicerContext). It's + serializable and can be passed with the request to be used on the deployment. + """ + + def __init__(self, grpc_context: grpc._cython.cygrpc._ServicerContext): + self._auth_context = grpc_context.auth_context() + self._code = grpc_context.code() + self._details = grpc_context.details() + self._invocation_metadata = [ # noqa: C416 + (key, value) for key, value in grpc_context.invocation_metadata() + ] + self._peer = grpc_context.peer() + self._peer_identities = grpc_context.peer_identities() + self._peer_identity_key = grpc_context.peer_identity_key() + self._trailing_metadata = [ # noqa: C416 + (key, value) for key, value in grpc_context.trailing_metadata() + ] + self._compression = None + + def auth_context(self) -> Dict[str, Any]: + """Gets the auth context for the call. + + Returns: + A map of strings to an iterable of bytes for each auth property. + """ + return self._auth_context + + def code(self) -> grpc.StatusCode: + """Accesses the value to be used as status code upon RPC completion. + + Returns: + The StatusCode value for the RPC. + """ + return self._code + + def details(self) -> str: + """Accesses the value to be used as detail string upon RPC completion. + + Returns: + The details string of the RPC. + """ + return self._details + + def invocation_metadata(self) -> List[Tuple[str, str]]: + """Accesses the metadata sent by the client. + + Returns: + The invocation :term:`metadata`. + """ + return self._invocation_metadata + + def peer(self) -> str: + """Identifies the peer that invoked the RPC being serviced. + + Returns: + A string identifying the peer that invoked the RPC being serviced. + The string format is determined by gRPC runtime. + """ + return self._peer + + def peer_identities(self) -> Optional[bytes]: + """Gets one or more peer identity(s). + + Equivalent to + servicer_context.auth_context().get(servicer_context.peer_identity_key()) + + Returns: + An iterable of the identities, or None if the call is not + authenticated. Each identity is returned as a raw bytes type. + """ + return self._peer_identities + + def peer_identity_key(self) -> Optional[str]: + """The auth property used to identify the peer. + + For example, "x509_common_name" or "x509_subject_alternative_name" are + used to identify an SSL peer. + + Returns: + The auth property (string) that indicates the + peer identity, or None if the call is not authenticated. + """ + return self._peer_identity_key + + def trailing_metadata(self) -> List[Tuple[str, str]]: + return self._trailing_metadata + + def set_code(self, code: grpc.StatusCode): + """Sets the value to be used as status code upon RPC completion. + + This method need not be called by method implementations if they wish + the gRPC runtime to determine the status code of the RPC. + + Args: + code: A StatusCode object to be sent to the client. + """ + self._code = code + + def set_compression(self, compression: grpc.Compression): + """Set the compression algorithm to be used for the entire call. + + Args: + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + """ + self._compression = compression + + def set_details(self, details: str): + """Sets the value to be used as detail string upon RPC completion. + + Calling this method is only needed if method implementations have + details to transmit. + + Args: + details: A UTF-8-encodable string to be sent to the client upon + termination of the RPC. + """ + self._details = details + + def _request_id_metadata(self) -> List[Tuple[str, str]]: + # Request id metadata should be carried over to the trailing metadata and passed + # back to the request client. This function helps pick it out if it exists. + for key, value in self._trailing_metadata: + if key == "request_id": + return [(key, value)] + return [] + + def set_trailing_metadata(self, trailing_metadata: List[Tuple[str, str]]): + """Sets the trailing metadata for the RPC. + + Sets the trailing metadata to be sent upon completion of the RPC. + + If this method is invoked multiple times throughout the lifetime of an + RPC, the value supplied in the final invocation + request id will be the value + sent over the wire. + + This method need not be called by implementations if they have no + metadata to add to what the gRPC runtime will transmit. + + Args: + trailing_metadata: The trailing :term:`metadata`. + """ + self._trailing_metadata = self._request_id_metadata() + trailing_metadata + + def _set_on_grpc_context(self, grpc_context: grpc._cython.cygrpc._ServicerContext): + """Serve's internal method to set attributes on the gRPC context.""" + if self._code: + grpc_context.set_code(self._code) + + if self._compression: + grpc_context.set_compression(self._compression) + + if self._details: + grpc_context.set_details(self._details) + + if self._trailing_metadata: + grpc_context.set_trailing_metadata(self._trailing_metadata) diff --git a/venv/lib/python3.10/site-packages/ray/serve/handle.py b/venv/lib/python3.10/site-packages/ray/serve/handle.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c686553f99cbcb0de75d22ec8ba5accc06e986 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/handle.py @@ -0,0 +1,752 @@ +import asyncio +import concurrent.futures +import logging +import time +import warnings +from typing import Any, AsyncIterator, Dict, Iterator, Optional, Tuple, Union + +import ray +from ray import serve +from ray._raylet import ObjectRefGenerator +from ray.serve._private.common import ( + DeploymentHandleSource, + DeploymentID, + RequestMetadata, +) +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.default_impl import ( + CreateRouterCallable, + create_dynamic_handle_options, + create_init_handle_options, + create_router, +) +from ray.serve._private.handle_options import ( + DynamicHandleOptionsBase, + InitHandleOptionsBase, +) +from ray.serve._private.replica_result import ReplicaResult +from ray.serve._private.router import Router +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + DEFAULT, + calculate_remaining_timeout, + get_random_string, + inside_ray_client_context, + is_running_in_asyncio_loop, +) +from ray.serve.exceptions import RayServeException, RequestCancelledError +from ray.util import metrics +from ray.util.annotations import DeveloperAPI, PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class _DeploymentHandleBase: + def __init__( + self, + deployment_name: str, + app_name: str, + *, + init_options: Optional[InitHandleOptionsBase] = None, + handle_options: Optional[DynamicHandleOptionsBase] = None, + _router: Optional[Router] = None, + _create_router: Optional[CreateRouterCallable] = None, + _request_counter: Optional[metrics.Counter] = None, + _handle_id: Optional[str] = None, + ): + self.deployment_id = DeploymentID(name=deployment_name, app_name=app_name) + self.init_options: Optional[InitHandleOptionsBase] = init_options + self.handle_options: DynamicHandleOptionsBase = ( + handle_options or create_dynamic_handle_options() + ) + + # Handle ID is shared among handles that are returned by + # `handle.options` or `handle.method` + self.handle_id = _handle_id or get_random_string() + self.request_counter = _request_counter or self._create_request_counter( + app_name, deployment_name, self.handle_id + ) + + self._router: Optional[Router] = _router + if _create_router is None: + self._create_router = create_router + else: + self._create_router = _create_router + + @staticmethod + def _gen_handle_tag(app_name: str, deployment_name: str, handle_id: str): + if app_name: + return f"{app_name}#{deployment_name}#{handle_id}" + else: + return f"{deployment_name}#{handle_id}" + + @classmethod + def _create_request_counter( + cls, app_name: str, deployment_name: str, handle_id: str + ): + return metrics.Counter( + "serve_handle_request_counter", + description=( + "The number of handle.remote() calls that have been " + "made on this handle." + ), + tag_keys=("handle", "deployment", "route", "application"), + ).set_default_tags( + { + "handle": cls._gen_handle_tag( + app_name, deployment_name, handle_id=handle_id + ), + "deployment": deployment_name, + "application": app_name, + } + ) + + def running_replicas_populated(self) -> bool: + if self._router is None: + return False + + return self._router.running_replicas_populated() + + @property + def deployment_name(self) -> str: + return self.deployment_id.name + + @property + def app_name(self) -> str: + return self.deployment_id.app_name + + @property + def is_initialized(self) -> bool: + return self._router is not None + + def _init(self, **kwargs): + """Initialize this handle with arguments. + + A handle can only be initialized once. A handle is implicitly + initialized when `.options()` or `.remote()` is called. Therefore + to initialize a handle with custom init options, you must do it + before calling `.options()` or `.remote()`. + """ + if self._router is not None: + raise RuntimeError( + "Handle has already been initialized. Note that a handle is implicitly " + "initialized when you call `.options()` or `.remote()`. You either " + "tried to call `._init()` twice or called `._init()` after calling " + "`.options()` or `.remote()`. If you want to modify the init options, " + "please do so before calling `.options()` or `.remote()`. This handle " + f"was initialized with {self.init_options}." + ) + + init_options = create_init_handle_options(**kwargs) + self._router = self._create_router( + handle_id=self.handle_id, + deployment_id=self.deployment_id, + handle_options=init_options, + ) + self.init_options = init_options + + logger.info( + f"Initialized DeploymentHandle {self.handle_id} for {self.deployment_id}.", + extra={"log_to_stderr": False}, + ) + + # Record handle api telemetry when not in the proxy + if ( + self.init_options._source != DeploymentHandleSource.PROXY + and self.__class__ == DeploymentHandle + ): + ServeUsageTag.DEPLOYMENT_HANDLE_API_USED.record("1") + + def _options(self, _prefer_local_routing=DEFAULT.VALUE, **kwargs): + if kwargs.get("stream") is True and inside_ray_client_context(): + raise RuntimeError( + "Streaming DeploymentHandles are not currently supported when " + "connected to a remote Ray cluster using Ray Client." + ) + + new_handle_options = self.handle_options.copy_and_update(**kwargs) + + # TODO(zcin): remove when _prefer_local_routing is removed from options() path + if _prefer_local_routing != DEFAULT.VALUE: + self._init(_prefer_local_routing=_prefer_local_routing) + + if not self.is_initialized: + self._init() + + return DeploymentHandle( + self.deployment_name, + self.app_name, + init_options=self.init_options, + handle_options=new_handle_options, + _router=self._router, + _create_router=self._create_router, + _request_counter=self.request_counter, + _handle_id=self.handle_id, + ) + + def _remote( + self, + args: Tuple[Any], + kwargs: Dict[str, Any], + ) -> Tuple[concurrent.futures.Future, RequestMetadata]: + if not self.is_initialized: + self._init() + + metadata = serve._private.default_impl.get_request_metadata( + self.init_options, self.handle_options + ) + + self.request_counter.inc( + tags={ + "route": metadata.route, + "application": metadata.app_name, + } + ) + + return self._router.assign_request(metadata, *args, **kwargs), metadata + + def __getattr__(self, name): + return self.options(method_name=name) + + def shutdown(self): + if self._router: + shutdown_future = self._router.shutdown() + shutdown_future.result() + + async def shutdown_async(self): + if self._router: + shutdown_future = self._router.shutdown() + await asyncio.wrap_future(shutdown_future) + + def __repr__(self): + return f"{self.__class__.__name__}" f"(deployment='{self.deployment_name}')" + + @classmethod + def _deserialize(cls, kwargs): + """Required for this class's __reduce__ method to be picklable.""" + return cls(**kwargs) + + def __reduce__(self): + serialized_constructor_args = { + "deployment_name": self.deployment_name, + "app_name": self.app_name, + "handle_options": self.handle_options, + } + return self.__class__._deserialize, (serialized_constructor_args,) + + +class _DeploymentResponseBase: + def __init__( + self, + replica_result_future: concurrent.futures.Future[ReplicaResult], + request_metadata: RequestMetadata, + ): + self._cancelled = False + self._replica_result_future = replica_result_future + self._replica_result: Optional[ReplicaResult] = None + self._request_metadata: RequestMetadata = request_metadata + + @property + def request_id(self) -> str: + return self._request_metadata.request_id + + def _fetch_future_result_sync( + self, _timeout_s: Optional[float] = None + ) -> ReplicaResult: + """Synchronously fetch the replica result. + + The result is cached in `self._replica_result`. + """ + + if self._replica_result is None: + try: + self._replica_result = self._replica_result_future.result( + timeout=_timeout_s + ) + except concurrent.futures.TimeoutError: + raise TimeoutError("Timed out resolving to ObjectRef.") from None + except concurrent.futures.CancelledError: + raise RequestCancelledError(self.request_id) from None + + return self._replica_result + + async def _fetch_future_result_async(self) -> ReplicaResult: + """Asynchronously fetch replica result. + + The result is cached in `self._replica_result`.. + """ + + if self._replica_result is None: + # Use `asyncio.wrap_future` so `self._replica_result_future` can be awaited + # safely from any asyncio loop. + self._replica_result = await asyncio.wrap_future( + self._replica_result_future + ) + + return self._replica_result + + def cancel(self): + """Attempt to cancel the `DeploymentHandle` call. + + This is best effort. + + - If the request hasn't been assigned to a replica, the assignment will be + cancelled. + - If the request has been assigned to a replica, `ray.cancel` will be + called on the object ref, attempting to cancel the request and any downstream + requests it makes. + + If the request is successfully cancelled, subsequent operations on the ref will + raise an exception: + + - If the request was cancelled before assignment, they'll raise + `asyncio.CancelledError` (or a `concurrent.futures.CancelledError` for + synchronous methods like `.result()`.). + - If the request was cancelled after assignment, they'll raise + `ray.exceptions.TaskCancelledError`. + """ + if self._cancelled: + return + + self._cancelled = True + self._replica_result_future.cancel() + try: + # try to fetch the results synchronously. if it succeeds, + # we will explicitly cancel the replica result. if it fails, + # the request is already cancelled and we can return early. + self._fetch_future_result_sync() + except RequestCancelledError: + # request is already cancelled nothing to do here + return + self._replica_result.cancel() + + @DeveloperAPI + def cancelled(self) -> bool: + """Whether or not the request has been cancelled. + + This is `True` if `.cancel()` is called, but the request may actually have run + to completion. + """ + return self._cancelled + + +@PublicAPI(stability="stable") +class DeploymentResponse(_DeploymentResponseBase): + """A future-like object wrapping the result of a unary deployment handle call. + + From inside a deployment, a `DeploymentResponse` can be awaited to retrieve the + output of the call without blocking the asyncio event loop. + + From outside a deployment, `.result()` can be used to retrieve the output in a + blocking manner. + + Example: + + .. code-block:: python + + from ray import serve + from ray.serve.handle import DeploymentHandle + + @serve.deployment + class Downstream: + def say_hi(self, message: str) -> str: + return f"Hello {message}!" + + @serve.deployment + class Caller: + def __init__(self, handle: DeploymentHandle): + self._downstream_handle = handle + + async def __call__(self, message: str) -> str: + # Inside a deployment: `await` the result to enable concurrency. + response = self._downstream_handle.say_hi.remote(message) + return await response + + app = Caller.bind(Downstream.bind()) + handle: DeploymentHandle = serve.run(app) + + # Outside a deployment: call `.result()` to get output. + response = handle.remote("world") + assert response.result() == "Hello world!" + + A `DeploymentResponse` can be passed directly to another `DeploymentHandle` call + without fetching the result to enable composing multiple deployments together. + + Example: + + .. code-block:: python + + from ray import serve + from ray.serve.handle import DeploymentHandle + + @serve.deployment + class Adder: + def add(self, val: int) -> int: + return val + 1 + + @serve.deployment + class Caller: + def __init__(self, handle: DeploymentHandle): + self._adder_handle = handle + + async def __call__(self, start: int) -> int: + return await self._adder_handle.add.remote( + # Pass the response directly to another handle call without awaiting. + self._adder_handle.add.remote(start) + ) + + app = Caller.bind(Adder.bind()) + handle: DeploymentHandle = serve.run(app) + assert handle.remote(0).result() == 2 + """ + + def __await__(self): + """Yields the final result of the deployment handle call.""" + try: + replica_result = yield from self._fetch_future_result_async().__await__() + result = yield from replica_result.get_async().__await__() + return result + except asyncio.CancelledError: + if self._cancelled: + raise RequestCancelledError(self.request_id) from None + else: + raise asyncio.CancelledError from None + + def __reduce__(self): + raise RayServeException( + "`DeploymentResponse` is not serializable. If you are passing the " + "`DeploymentResponse` in a nested object (e.g. a list or dictionary) to a " + "downstream deployment handle call, that is no longer supported. Please " + "only pass `DeploymentResponse` objects as top level arguments." + ) + + def result( + self, + *, + timeout_s: Optional[float] = None, + _skip_asyncio_check: bool = False, + ) -> Any: + """Fetch the result of the handle call synchronously. + + This should *not* be used from within a deployment as it runs in an asyncio + event loop. For model composition, `await` the response instead. + + If `timeout_s` is provided and the result is not available before the timeout, + a `TimeoutError` is raised. + """ + + if not _skip_asyncio_check and is_running_in_asyncio_loop(): + raise RuntimeError( + "Sync methods should not be called from within an `asyncio` event " + "loop. Use `await response` instead." + ) + + start_time_s = time.time() + replica_result = self._fetch_future_result_sync(timeout_s) + + remaining_timeout_s = calculate_remaining_timeout( + timeout_s=timeout_s, start_time_s=start_time_s, curr_time_s=time.time() + ) + return replica_result.get(remaining_timeout_s) + + @DeveloperAPI + async def _to_object_ref(self) -> ray.ObjectRef: + """Advanced API to convert the response to a Ray `ObjectRef`. + + This is used to pass the output of a `DeploymentHandle` call to a Ray task or + actor method call. + + This method is `async def` because it will block until the handle call has been + assigned to a replica. If there are many requests in flight and all + replicas' queues are full, this may be a slow operation. + """ + + ServeUsageTag.DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED.record("1") + + replica_result = await self._fetch_future_result_async() + return await replica_result.to_object_ref_async() + + @DeveloperAPI + def _to_object_ref_sync( + self, + _timeout_s: Optional[float] = None, + _allow_running_in_asyncio_loop: bool = False, + ) -> ray.ObjectRef: + """Advanced API to convert the response to a Ray `ObjectRef`. + + This is used to pass the output of a `DeploymentHandle` call to a Ray task or + actor method call. + + This method is a *blocking* call because it will block until the handle call has + been assigned to a replica. If there are many requests in flight and all + replicas' queues are full, this may be a slow operation. + + From inside a deployment, `_to_object_ref` should be used instead to avoid + blocking the asyncio event loop. + """ + + ServeUsageTag.DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED.record("1") + + if not _allow_running_in_asyncio_loop and is_running_in_asyncio_loop(): + raise RuntimeError( + "Sync methods should not be called from within an `asyncio` event " + "loop. Use `await response._to_object_ref()` instead." + ) + + # First, fetch the result of the future + start_time_s = time.time() + replica_result = self._fetch_future_result_sync(_timeout_s) + + # Then, if necessary, resolve generator to ref + remaining_timeout_s = calculate_remaining_timeout( + timeout_s=_timeout_s, + start_time_s=start_time_s, + curr_time_s=time.time(), + ) + return replica_result.to_object_ref(timeout_s=remaining_timeout_s) + + +@PublicAPI(stability="stable") +class DeploymentResponseGenerator(_DeploymentResponseBase): + """A future-like object wrapping the result of a streaming deployment handle call. + + This is returned when using `handle.options(stream=True)` and calling a generator + deployment method. + + `DeploymentResponseGenerator` is both a synchronous and asynchronous iterator. + + When iterating over results from inside a deployment, `async for` should be used to + avoid blocking the asyncio event loop. + + When iterating over results from outside a deployment, use a standard `for` loop. + + Example: + + .. code-block:: python + + from typing import AsyncGenerator, Generator + + from ray import serve + from ray.serve.handle import DeploymentHandle + + @serve.deployment + class Streamer: + def generate_numbers(self, limit: int) -> Generator[int]: + for i in range(limit): + yield i + + @serve.deployment + class Caller: + def __init__(self, handle: DeploymentHandle): + # Set `stream=True` on the handle to enable streaming calls. + self._streaming_handle = handle.options(stream=True) + + async def __call__(self, limit: int) -> AsyncIterator[int]: + gen: DeploymentResponseGenerator = ( + self._streaming_handle.generate_numbers.remote(limit) + ) + + # Inside a deployment: use `async for` to enable concurrency. + async for i in gen: + yield i + + app = Caller.bind(Streamer.bind()) + handle: DeploymentHandle = serve.run(app) + + # Outside a deployment: use a standard `for` loop. + gen: DeploymentResponseGenerator = handle.options(stream=True).remote(10) + assert [i for i in gen] == list(range(10)) + + A `DeploymentResponseGenerator` *cannot* currently be passed to another + `DeploymentHandle` call. + """ + + def __await__(self): + raise TypeError( + "`DeploymentResponseGenerator` cannot be awaited directly. Use `async for` " + "or `await response.__anext__() instead`." + ) + + def __aiter__(self) -> AsyncIterator[Any]: + return self + + async def __anext__(self) -> Any: + try: + replica_result = await self._fetch_future_result_async() + return await replica_result.__anext__() + except asyncio.CancelledError: + if self._cancelled: + raise RequestCancelledError(self.request_id) from None + else: + raise asyncio.CancelledError from None + + def __iter__(self) -> Iterator[Any]: + return self + + def __next__(self) -> Any: + if is_running_in_asyncio_loop(): + raise RuntimeError( + "Sync methods should not be called from within an `asyncio` event " + "loop. Use `async for` or `await response.__anext__()` instead." + ) + + replica_result = self._fetch_future_result_sync() + return replica_result.__next__() + + @DeveloperAPI + async def _to_object_ref_gen(self) -> ObjectRefGenerator: + """Advanced API to convert the generator to a Ray `ObjectRefGenerator`. + + This method is `async def` because it will block until the handle call has been + assigned to a replica. If there are many requests in flight and all + replicas' queues are full, this may be a slow operation. + """ + + ServeUsageTag.DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED.record("1") + + replica_result = await self._fetch_future_result_async() + return replica_result.to_object_ref_gen() + + @DeveloperAPI + def _to_object_ref_gen_sync( + self, + _timeout_s: Optional[float] = None, + _allow_running_in_asyncio_loop: bool = False, + ) -> ObjectRefGenerator: + """Advanced API to convert the generator to a Ray `ObjectRefGenerator`. + + This method is a *blocking* call because it will block until the handle call has + been assigned to a replica. If there are many requests in flight and all + replicas' queues are full, this may be a slow operation. + + From inside a deployment, `_to_object_ref_gen` should be used instead to avoid + blocking the asyncio event loop. + """ + + ServeUsageTag.DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED.record("1") + + if not _allow_running_in_asyncio_loop and is_running_in_asyncio_loop(): + raise RuntimeError( + "Sync methods should not be called from within an `asyncio` event " + "loop. Use `await response._to_object_ref()` instead." + ) + + replica_result = self._fetch_future_result_sync(_timeout_s) + return replica_result.to_object_ref_gen() + + +@PublicAPI(stability="stable") +class DeploymentHandle(_DeploymentHandleBase): + """A handle used to make requests to a deployment at runtime. + + This is primarily used to compose multiple deployments within a single application. + It can also be used to make calls to the ingress deployment of an application (e.g., + for programmatic testing). + + Example: + + + .. code-block:: python + + import ray + from ray import serve + from ray.serve.handle import DeploymentHandle, DeploymentResponse + + @serve.deployment + class Downstream: + def say_hi(self, message: str): + return f"Hello {message}!" + self._message = message + + @serve.deployment + class Ingress: + def __init__(self, handle: DeploymentHandle): + self._downstream_handle = handle + + async def __call__(self, name: str) -> str: + response = self._downstream_handle.say_hi.remote(name) + return await response + + app = Ingress.bind(Downstream.bind()) + handle: DeploymentHandle = serve.run(app) + response = handle.remote("world") + assert response.result() == "Hello world!" + """ + + def options( + self, + *, + method_name: Union[str, DEFAULT] = DEFAULT.VALUE, + multiplexed_model_id: Union[str, DEFAULT] = DEFAULT.VALUE, + stream: Union[bool, DEFAULT] = DEFAULT.VALUE, + use_new_handle_api: Union[bool, DEFAULT] = DEFAULT.VALUE, + _prefer_local_routing: Union[bool, DEFAULT] = DEFAULT.VALUE, + ) -> "DeploymentHandle": + """Set options for this handle and return an updated copy of it. + + Example: + + .. code-block:: python + + response: DeploymentResponse = handle.options( + method_name="other_method", + multiplexed_model_id="model:v1", + ).remote() + """ + if use_new_handle_api is not DEFAULT.VALUE: + warnings.warn( + "Setting `use_new_handle_api` no longer has any effect. " + "This argument will be removed in a future version." + ) + + if _prefer_local_routing is not DEFAULT.VALUE: + warnings.warn( + "Modifying `_prefer_local_routing` with `options()` is " + "deprecated. Please use `init()` instead." + ) + + return self._options( + method_name=method_name, + multiplexed_model_id=multiplexed_model_id, + stream=stream, + _prefer_local_routing=_prefer_local_routing, + ) + + def remote( + self, *args, **kwargs + ) -> Union[DeploymentResponse, DeploymentResponseGenerator]: + """Issue a remote call to a method of the deployment. + + By default, the result is a `DeploymentResponse` that can be awaited to fetch + the result of the call or passed to another `.remote()` call to compose multiple + deployments. + + If `handle.options(stream=True)` is set and a generator method is called, this + returns a `DeploymentResponseGenerator` instead. + + Example: + + .. code-block:: python + + # Fetch the result directly. + response = handle.remote() + result = await response + + # Pass the result to another handle call. + composed_response = handle2.remote(handle1.remote()) + composed_result = await composed_response + + Args: + *args: Positional arguments to be serialized and passed to the + remote method call. + **kwargs: Keyword arguments to be serialized and passed to the + remote method call. + """ + + future, request_metadata = self._remote(args, kwargs) + if self.handle_options.stream: + response_cls = DeploymentResponseGenerator + else: + response_cls = DeploymentResponse + + return response_cls(future, request_metadata) diff --git a/venv/lib/python3.10/site-packages/ray/serve/llm/__init__.py b/venv/lib/python3.10/site-packages/ray/serve/llm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..48a5fbb230cdeffcd4e81f6b823d16125881d0bf --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/llm/__init__.py @@ -0,0 +1,362 @@ +from typing import TYPE_CHECKING, Optional + +from ray.llm._internal.serve.configs.server_models import ( + CloudMirrorConfig as _CloudMirrorConfig, + LLMConfig as _LLMConfig, + LLMServingArgs as _LLMServingArgs, + LoraConfig as _LoraConfig, + ModelLoadingConfig as _ModelLoadingConfig, +) +from ray.llm._internal.serve.deployments.llm.llm_server import ( + LLMServer as _LLMServer, +) +from ray.llm._internal.serve.deployments.routers.router import ( + LLMRouter as _LLMRouter, +) +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.serve.deployment import Application + + +########## +# Models +########## + + +@PublicAPI(stability="alpha") +class LLMConfig(_LLMConfig): + """The configuration for starting an LLM deployment.""" + + pass + + +@PublicAPI(stability="alpha") +class LLMServingArgs(_LLMServingArgs): + """The configuration for starting an LLM deployment application.""" + + pass + + +@PublicAPI(stability="alpha") +class ModelLoadingConfig(_ModelLoadingConfig): + """The configuration for loading an LLM model.""" + + pass + + +@PublicAPI(stability="alpha") +class CloudMirrorConfig(_CloudMirrorConfig): + """The configuration for mirroring an LLM model from cloud storage.""" + + pass + + +@PublicAPI(stability="alpha") +class LoraConfig(_LoraConfig): + """The configuration for loading an LLM model with LoRA.""" + + pass + + +########## +# Builders +########## + + +@PublicAPI(stability="alpha") +def build_llm_deployment( + llm_config: "LLMConfig", *, name_prefix: Optional[str] = None +) -> "Application": + """Helper to build a single vllm deployment from the given llm config. + + Examples: + .. testcode:: + :skipif: True + + from ray import serve + from ray.serve.llm import LLMConfig, build_llm_deployment + + # Configure the model + llm_config = LLMConfig( + model_loading_config=dict( + model_id="llama-3.1-8b", + model_source="meta-llama/Llama-3.1-8b-instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, + max_replicas=2, + ) + ), + accelerator_type="A10G", + ) + + # Build the deployment + llm_app = build_llm_deployment(llm_config) + + # Deploy the application + model_handle = serve.run(llm_app) + + # Querying the model handle + import asyncio + model_handle = model_handle.options(stream=True) + async def query_model(model_handle): + from ray.serve.llm.openai_api_models import ChatCompletionRequest + + request = ChatCompletionRequest( + model="qwen-0.5b", + messages=[ + { + "role": "user", + "content": "Hello, world!" + } + ] + ) + + resp = model_handle.chat.remote(request) + async for message in resp: + print("message: ", message) + + asyncio.run(query_model(model_handle)) + + Args: + llm_config: The llm config to build vllm deployment. + name_prefix: Optional prefix to be used for the deployment name. + + Returns: + The configured Ray Serve Application for vllm deployment. + """ + from ray.llm._internal.serve.builders import build_llm_deployment + + return build_llm_deployment(llm_config=llm_config, name_prefix=name_prefix) + + +@PublicAPI(stability="alpha") +def build_openai_app(llm_serving_args: "LLMServingArgs") -> "Application": + """Helper to build an OpenAI compatible app with the llm deployment setup from + the given llm serving args. This is the main entry point for users to create a + Serve application serving LLMs. + + + Examples: + .. code-block:: python + :caption: Example usage in code. + + from ray import serve + from ray.serve.llm import LLMConfig, LLMServingArgs, build_openai_app + + llm_config1 = LLMConfig( + model_loading_config=dict( + model_id="qwen-0.5b", + model_source="Qwen/Qwen2.5-0.5B-Instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, max_replicas=2, + ) + ), + accelerator_type="A10G", + ) + + llm_config2 = LLMConfig( + model_loading_config=dict( + model_id="qwen-1.5b", + model_source="Qwen/Qwen2.5-1.5B-Instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, max_replicas=2, + ) + ), + accelerator_type="A10G", + ) + + # Deploy the application + llm_app = build_openai_app( + LLMServingArgs( + llm_configs=[ + llm_config1, + llm_config2, + ] + ) + ) + serve.run(llm_app) + + + # Querying the model via openai client + from openai import OpenAI + + # Initialize client + client = OpenAI(base_url="http://localhost:8000/v1", api_key="fake-key") + + # Basic completion + response = client.chat.completions.create( + model="qwen-0.5b", + messages=[{"role": "user", "content": "Hello!"}] + ) + + .. code-block:: yaml + :caption: Example usage in YAML. + + # config.yaml + applications: + - args: + llm_configs: + - model_loading_config: + model_id: qwen-0.5b + model_source: Qwen/Qwen2.5-0.5B-Instruct + accelerator_type: A10G + deployment_config: + autoscaling_config: + min_replicas: 1 + max_replicas: 2 + - model_loading_config: + model_id: qwen-1.5b + model_source: Qwen/Qwen2.5-1.5B-Instruct + accelerator_type: A10G + deployment_config: + autoscaling_config: + min_replicas: 1 + max_replicas: 2 + import_path: ray.serve.llm:build_openai_app + name: llm_app + route_prefix: "/" + + + Args: + llm_serving_args: The list of llm configs or the paths to the llm config to + build the app. + + Returns: + The configured Ray Serve Application router. + """ + from ray.llm._internal.serve.builders import build_openai_app + + return build_openai_app(llm_serving_args=llm_serving_args) + + +############# +# Deployments +############# + + +@PublicAPI(stability="alpha") +class LLMServer(_LLMServer): + """The implementation of the vLLM engine deployment. + + To build a Deployment object you should use `build_llm_deployment` function. + We also expose a lower level API for more control over the deployment class + through `as_deployment` method. + + Examples: + .. testcode:: + :skipif: True + + from ray import serve + from ray.serve.llm import LLMConfig, LLMServer + + # Configure the model + llm_config = LLMConfig( + model_loading_config=dict( + served_model_name="llama-3.1-8b", + model_source="meta-llama/Llama-3.1-8b-instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, + max_replicas=8, + ) + ), + ) + + # Build the deployment directly + LLMDeployment = LLMServer.as_deployment(llm_config.get_serve_options()) + llm_app = LLMDeployment.bind(llm_config) + + model_handle = serve.run(llm_app) + + # Query the model via `chat` api + from ray.serve.llm.openai_api_models import ChatCompletionRequest + request = ChatCompletionRequest( + model="llama-3.1-8b", + messages=[ + { + "role": "user", + "content": "Hello, world!" + } + ] + ) + response = ray.get(model_handle.chat(request)) + print(response) + """ + + pass + + +@PublicAPI(stability="alpha") +class LLMRouter(_LLMRouter): + + """The implementation of the OpenAI compatiple model router. + + This deployment creates the following endpoints: + - /v1/chat/completions: Chat interface (OpenAI-style) + - /v1/completions: Text completion + - /v1/models: List available models + - /v1/models/{model}: Model information + + + Examples: + .. testcode:: + :skipif: True + + + from ray import serve + from ray.serve.llm import LLMConfig, LLMServer, LLMRouter + from ray.serve.llm.openai_api_models import ChatCompletionRequest + + + llm_config1 = LLMConfig( + model_loading_config=dict( + served_model_name="llama-3.1-8b", # Name shown in /v1/models + model_source="meta-llama/Llama-3.1-8b-instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, max_replicas=8, + ) + ), + ) + llm_config2 = LLMConfig( + model_loading_config=dict( + served_model_name="llama-3.2-3b", # Name shown in /v1/models + model_source="meta-llama/Llama-3.2-3b-instruct", + ), + deployment_config=dict( + autoscaling_config=dict( + min_replicas=1, max_replicas=8, + ) + ), + ) + + # Deploy the application + vllm_deployment1 = LLMServer.as_deployment(llm_config1.get_serve_options()).bind(llm_config1) + vllm_deployment2 = LLMServer.as_deployment(llm_config2.get_serve_options()).bind(llm_config2) + llm_app = LLMRouter.as_deployment().bind([vllm_deployment1, vllm_deployment2]) + serve.run(llm_app) + """ + + pass + + +__all__ = [ + "LLMConfig", + "LLMServingArgs", + "ModelLoadingConfig", + "CloudMirrorConfig", + "LoraConfig", + "build_llm_deployment", + "build_openai_app", + "LLMServer", + "LLMRouter", +] diff --git a/venv/lib/python3.10/site-packages/ray/serve/llm/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/llm/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..306b05887747c972a61e5eb9d2e1c4b750ccc2e5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/llm/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/llm/__pycache__/gen_config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/llm/__pycache__/gen_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d13c291d7f659f181fc9e977fa924102b34be0e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/llm/__pycache__/gen_config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/llm/__pycache__/openai_api_models.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/serve/llm/__pycache__/openai_api_models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae2b337f469f89edae1c1172603e97f12aece115 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/serve/llm/__pycache__/openai_api_models.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/serve/llm/gen_config.py b/venv/lib/python3.10/site-packages/ray/serve/llm/gen_config.py new file mode 100644 index 0000000000000000000000000000000000000000..27d880238f262ec2b56e5aa09eaffbe92311188f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/llm/gen_config.py @@ -0,0 +1,10 @@ +from ray.llm._internal.serve.config_generator.start import gen_config + + +def main(): + """Entry point for the CLI when called as a module.""" + gen_config() + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/ray/serve/llm/openai_api_models.py b/venv/lib/python3.10/site-packages/ray/serve/llm/openai_api_models.py new file mode 100644 index 0000000000000000000000000000000000000000..210984cc1bd0ffda2eaf0d7aefd6abce00866fc1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/llm/openai_api_models.py @@ -0,0 +1,99 @@ +from ray.llm._internal.serve.configs.openai_api_models import ( + ChatCompletionRequest as _ChatCompletionRequest, + ChatCompletionResponse as _ChatCompletionResponse, + ChatCompletionStreamResponse as _ChatCompletionStreamResponse, + CompletionRequest as _CompletionRequest, + CompletionResponse as _CompletionResponse, + CompletionStreamResponse as _CompletionStreamResponse, + EmbeddingRequest as _EmbeddingRequest, + EmbeddingResponse as _EmbeddingResponse, + ErrorResponse as _ErrorResponse, +) +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class ChatCompletionRequest(_ChatCompletionRequest): + """ChatCompletionRequest is the request body for the chat completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class CompletionRequest(_CompletionRequest): + """CompletionRequest is the request body for the completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class ChatCompletionStreamResponse(_ChatCompletionStreamResponse): + """ChatCompletionStreamResponse is the response body for the chat completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class ChatCompletionResponse(_ChatCompletionResponse): + """ChatCompletionResponse is the response body for the chat completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class CompletionStreamResponse(_CompletionStreamResponse): + """CompletionStreamResponse is the response body for the completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class CompletionResponse(_CompletionResponse): + """CompletionResponse is the response body for the completion API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class EmbeddingRequest(_EmbeddingRequest): + """EmbeddingRequest is the request body for the embedding API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class EmbeddingResponse(_EmbeddingResponse): + """EmbeddingResponse is the response body for the embedding API. + + This model is compatible with vLLM's OpenAI API models. + """ + + pass + + +@PublicAPI(stability="alpha") +class ErrorResponse(_ErrorResponse): + """The returned response in case of an error.""" + + pass diff --git a/venv/lib/python3.10/site-packages/ray/serve/metrics.py b/venv/lib/python3.10/site-packages/ray/serve/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..bce6e49440047a77b30199e4938484cdc938f3df --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/metrics.py @@ -0,0 +1,249 @@ +from typing import Dict, List, Optional, Tuple, Union + +import ray +from ray.serve import context +from ray.util import metrics +from ray.util.annotations import PublicAPI + +DEPLOYMENT_TAG = "deployment" +REPLICA_TAG = "replica" +APPLICATION_TAG = "application" +ROUTE_TAG = "route" + + +def _add_serve_metric_tags(tag_keys: Optional[Tuple[str]] = None) -> Tuple[str]: + """Add serve context tags to the tag_keys""" + if tag_keys is None: + tag_keys = tuple() + + # If the context doesn't exist, no serve tag is added. + if context._get_internal_replica_context() is None: + return tag_keys + # Check no collision with customer tag + if DEPLOYMENT_TAG in tag_keys: + raise ValueError(f"'{DEPLOYMENT_TAG}' tag is reserved for Ray Serve metrics") + if REPLICA_TAG in tag_keys: + raise ValueError(f"'{REPLICA_TAG}' tag is reserved for Ray Serve metrics") + if APPLICATION_TAG in tag_keys: + raise ValueError(f"'{APPLICATION_TAG}' tag is reserved for Ray Serve metrics") + + # Get serve tag inserted: + ray_serve_tags = (DEPLOYMENT_TAG, REPLICA_TAG) + if context._get_internal_replica_context().app_name: + ray_serve_tags += (APPLICATION_TAG,) + if tag_keys: + tag_keys = ray_serve_tags + tag_keys + else: + tag_keys = ray_serve_tags + return tag_keys + + +def _add_serve_metric_default_tags(default_tags: Dict[str, str]): + """Add serve context tags and values to the default_tags""" + if context._get_internal_replica_context() is None: + return default_tags + if DEPLOYMENT_TAG in default_tags: + raise ValueError(f"'{DEPLOYMENT_TAG}' tag is reserved for Ray Serve metrics") + if REPLICA_TAG in default_tags: + raise ValueError(f"'{REPLICA_TAG}' tag is reserved for Ray Serve metrics") + if APPLICATION_TAG in default_tags: + raise ValueError(f"'{APPLICATION_TAG}' tag is reserved for Ray Serve metrics") + replica_context = context._get_internal_replica_context() + # TODO(zcin): use replica_context.deployment for deployment tag + default_tags[DEPLOYMENT_TAG] = replica_context.deployment + default_tags[REPLICA_TAG] = replica_context.replica_tag + if replica_context.app_name: + default_tags[APPLICATION_TAG] = replica_context.app_name + return default_tags + + +def _add_serve_context_tag_values(tag_keys: Tuple, tags: Dict[str, str]): + """Add serve context tag values to the metric tags""" + + _request_context = ray.serve.context._get_serve_request_context() + if ROUTE_TAG in tag_keys and ROUTE_TAG not in tags: + tags[ROUTE_TAG] = _request_context.route + + +@PublicAPI(stability="beta") +class Counter(metrics.Counter): + """A serve cumulative metric that is monotonically increasing. + + This corresponds to Prometheus' counter metric: + https://prometheus.io/docs/concepts/metric_types/#counter + + Serve-related tags ("deployment", "replica", "application", "route") + are added automatically if not provided. + + .. code-block:: python + + @serve.deployment + class MyDeployment: + def __init__(self): + self.num_requests = 0 + self.my_counter = metrics.Counter( + "my_counter", + description=("The number of odd-numbered requests " + "to this deployment."), + tag_keys=("model",), + ) + self.my_counter.set_default_tags({"model": "123"}) + + def __call__(self): + self.num_requests += 1 + if self.num_requests % 2 == 1: + self.my_counter.inc() + + .. note:: + + Before Ray 2.10, this exports a Prometheus gauge metric instead of + a counter metric. + Starting in Ray 2.10, this exports both the proper counter metric + (with a suffix "_total") and gauge metric (for compatibility). + The gauge metric will be removed in a future Ray release and you can set + `RAY_EXPORT_COUNTER_AS_GAUGE=0` to disable exporting it in the meantime. + + Args: + name: Name of the metric. + description: Description of the metric. + tag_keys: Tag keys of the metric. + """ + + def __init__( + self, name: str, description: str = "", tag_keys: Optional[Tuple[str]] = None + ): + if tag_keys and not isinstance(tag_keys, tuple): + raise TypeError( + "tag_keys should be a tuple type, got: " f"{type(tag_keys)}" + ) + tag_keys = _add_serve_metric_tags(tag_keys) + super().__init__(name, description, tag_keys) + self.set_default_tags({}) + + def set_default_tags(self, default_tags: Dict[str, str]): + super().set_default_tags(_add_serve_metric_default_tags(default_tags)) + + def inc(self, value: Union[int, float] = 1.0, tags: Dict[str, str] = None): + """Increment the counter by the given value, add serve context + tag values to the tags + """ + _add_serve_context_tag_values(self._tag_keys, tags) + super().inc(value, tags) + + +@PublicAPI(stability="beta") +class Gauge(metrics.Gauge): + """Gauges keep the last recorded value and drop everything before. + + This corresponds to Prometheus' gauge metric: + https://prometheus.io/docs/concepts/metric_types/#gauge + + Serve-related tags ("deployment", "replica", "application", "route") + are added automatically if not provided. + + .. code-block:: python + + @serve.deployment + class MyDeployment: + def __init__(self): + self.num_requests = 0 + self.my_gauge = metrics.Gauge( + "my_gauge", + description=("The current memory usage."), + tag_keys=("model",), + ) + self.my_counter.set_default_tags({"model": "123"}) + + def __call__(self): + process = psutil.Process() + self.gauge.set(process.memory_info().rss) + + Args: + name: Name of the metric. + description: Description of the metric. + tag_keys: Tag keys of the metric. + """ + + def __init__( + self, name: str, description: str = "", tag_keys: Optional[Tuple[str]] = None + ): + if tag_keys and not isinstance(tag_keys, tuple): + raise TypeError( + "tag_keys should be a tuple type, got: " f"{type(tag_keys)}" + ) + tag_keys = _add_serve_metric_tags(tag_keys) + super().__init__(name, description, tag_keys) + self.set_default_tags({}) + + def set_default_tags(self, default_tags: Dict[str, str]): + super().set_default_tags(_add_serve_metric_default_tags(default_tags)) + + def set(self, value: Union[int, float], tags: Dict[str, str] = None): + """Set the gauge to the given value, add serve context + tag values to the tags + """ + _add_serve_context_tag_values(self._tag_keys, tags) + super().set(value, tags) + + +@PublicAPI(stability="beta") +class Histogram(metrics.Histogram): + """Tracks the size and number of events in buckets. + + Histograms allow you to calculate aggregate quantiles + such as 25, 50, 95, 99 percentile latency for an RPC. + + This corresponds to Prometheus' histogram metric: + https://prometheus.io/docs/concepts/metric_types/#histogram + + Serve-related tags ("deployment", "replica", "application", "route") + are added automatically if not provided. + + .. code-block:: python + + @serve.deployment + class MyDeployment: + def __init__(self): + self.my_histogram = Histogram( + "my_histogram", + description=("Histogram of the __call__ method running time."), + boundaries=[1,2,4,8,16,32,64], + tag_keys=("model",), + ) + self.my_histogram.set_default_tags({"model": "123"}) + + def __call__(self): + start = time.time() + self.my_histogram.observe(time.time() - start) + + Args: + name: Name of the metric. + description: Description of the metric. + boundaries: Boundaries of histogram buckets. + tag_keys: Tag keys of the metric. + """ + + def __init__( + self, + name: str, + description: str = "", + boundaries: List[float] = None, + tag_keys: Optional[Tuple[str]] = None, + ): + if tag_keys and not isinstance(tag_keys, tuple): + raise TypeError( + "tag_keys should be a tuple type, got: " f"{type(tag_keys)}" + ) + tag_keys = _add_serve_metric_tags(tag_keys) + super().__init__(name, description, boundaries, tag_keys) + self.set_default_tags({}) + + def set_default_tags(self, default_tags: Dict[str, str]): + super().set_default_tags(_add_serve_metric_default_tags(default_tags)) + + def observe(self, value: Union[int, float], tags: Dict[str, str] = None): + """Observe the given value, add serve context + tag values to the tags + """ + _add_serve_context_tag_values(self._tag_keys, tags) + super().observe(value, tags) diff --git a/venv/lib/python3.10/site-packages/ray/serve/multiplex.py b/venv/lib/python3.10/site-packages/ray/serve/multiplex.py new file mode 100644 index 0000000000000000000000000000000000000000..55d526a9a00e83084503d4c4526d10b98a95e131 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/multiplex.py @@ -0,0 +1,260 @@ +import asyncio +import inspect +import logging +import time +from collections import OrderedDict +from typing import Any, Callable, List, Set + +from ray.serve import metrics +from ray.serve._private.common import ReplicaID, RequestRoutingInfo +from ray.serve._private.constants import ( + MODEL_LOAD_LATENCY_BUCKETS_MS, + PUSH_MULTIPLEXED_MODEL_IDS_INTERVAL_S, + SERVE_LOGGER_NAME, +) +from ray.serve._private.metrics_utils import MetricsPusher +from ray.serve._private.usage import ServeUsageTag +from ray.serve.context import _get_global_client, _get_internal_replica_context + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class _ModelMultiplexWrapper: + """A wrapper class that wraps the model load function and + provides the LRU caching functionality. + + The model multiplexer is a wrapper class that wraps the model load function + and provides the LRU caching functionality, and the model load function should + be a coroutine function that takes the model ID as the first argument and + returns the user-constructed model object. + The model multiplexer will also ensure that the number of models on the current + replica does not exceed the specified limit. + The model will be unloaded in the LRU order, the model multiplexer will call the + model's __del__ attribute if it exists to clean up the model resources eagerly. + + """ + + _PUSH_MULTIPLEXED_MODEL_IDS_TASK_NAME = "push_multiplexed_model_ids" + + def __init__( + self, + model_load_func: Callable[[str], Any], + self_arg: Any, + max_num_models_per_replica: int, + ): + """Initialize the model multiplexer. + Args: + model_load_func: the model load async function. + self_arg: self argument when model_load_func is class method. + max_num_models_per_replica: the maximum number of models to be loaded on the + current replica. If it is -1, there is no limit for the number of models + per replica. + """ + + ServeUsageTag.MULTIPLEXED_API_USED.record("1") + + self.models = OrderedDict() + self._func: Callable = model_load_func + self.self_arg: Any = self_arg + self.max_num_models_per_replica: int = max_num_models_per_replica + + # log MODEL_LOAD_LATENCY_BUCKET_MS + logger.debug(f"MODEL_LOAD_LATENCY_BUCKET_MS: {MODEL_LOAD_LATENCY_BUCKETS_MS}") + self.model_load_latency_ms = metrics.Histogram( + "serve_multiplexed_model_load_latency_ms", + description="The time it takes to load a model.", + boundaries=MODEL_LOAD_LATENCY_BUCKETS_MS, + ) + self.model_unload_latency_ms = metrics.Histogram( + "serve_multiplexed_model_unload_latency_ms", + description="The time it takes to unload a model.", + boundaries=MODEL_LOAD_LATENCY_BUCKETS_MS, + ) + self.num_models_gauge = metrics.Gauge( + "serve_num_multiplexed_models", + description="The number of models loaded on the current replica.", + ) + + self.registered_model_gauge = metrics.Gauge( + "serve_registered_multiplexed_model_id", + description="The model id registered on the current replica.", + tag_keys=("model_id",), + ) + self.get_model_requests_counter = metrics.Counter( + "serve_multiplexed_get_model_requests_counter", + description="The counter for get model requests on the current replica.", + ) + self.models_unload_counter = metrics.Counter( + "serve_multiplexed_models_unload_counter", + description="The counter for unloaded models on the current replica.", + ) + self.models_load_counter = metrics.Counter( + "serve_multiplexed_models_load_counter", + description="The counter for loaded models on the current replica.", + ) + + context = _get_internal_replica_context() + if context is None: + raise RuntimeError( + "`@serve.multiplex` can only be used within a deployment " + "(failed to retrieve Serve replica context)." + ) + + self._app_name: str = context.app_name + self._deployment_name: str = context.deployment + self._replica_id: ReplicaID = context.replica_id + + # Whether to push the multiplexed replica info to the controller. + self._push_multiplexed_replica_info: bool = False + + # Model cache lock to ensure that only one model is loading/unloading at a time. + self._model_cache_lock = asyncio.Lock() + # The set of model IDs that are being loaded. This is used to early push + # model ids info to the controller. The tasks will be added when there is cache + # miss, and will be removed when the model is loaded successfully or + # failed to load. + self._model_load_tasks: Set[str] = set() + + self.metrics_pusher = MetricsPusher() + self.metrics_pusher.register_or_update_task( + self._PUSH_MULTIPLEXED_MODEL_IDS_TASK_NAME, + self._push_model_ids_info, + PUSH_MULTIPLEXED_MODEL_IDS_INTERVAL_S, + ) + self.metrics_pusher.start() + + def _get_loading_and_loaded_model_ids(self) -> List[str]: + """Get the model IDs of the loaded models & loading models in the replica. + This is to push the model id information early to the controller, so that + requests can be routed to the replica. + """ + models_list = set(self.models.keys()) + models_list.update(self._model_load_tasks) + return list(models_list) + + def _push_model_ids_info(self): + """Push the multiplexed replica info to the controller.""" + try: + self.num_models_gauge.set(len(self.models)) + + for model_id in self.models: + self.registered_model_gauge.set(1, tags={"model_id": model_id}) + + if self._push_multiplexed_replica_info: + _get_global_client().record_request_routing_info( + RequestRoutingInfo( + replica_id=self._replica_id, + multiplexed_model_ids=self._get_loading_and_loaded_model_ids(), + ) + ) + self._push_multiplexed_replica_info = False + except Exception as e: + logger.warning( + "Failed to push the multiplexed replica info " + f"to the controller. Error: {e}" + ) + + async def shutdown(self): + """Unload all the models when the model multiplexer is deleted.""" + while len(self.models) > 0: + try: + await self.unload_model_lru() + except Exception as e: + logger.exception( + f"Failed to unload model. Error: {e}", + ) + + async def load_model(self, model_id: str) -> Any: + """Load the model if it is not loaded yet, and return + the user-constructed model object. + + Args: + model_id: the model ID. + + Returns: + The user-constructed model object. + """ + + if type(model_id) is not str: + raise TypeError("The model ID must be a string.") + + if not model_id: + raise ValueError("The model ID cannot be empty.") + + self.get_model_requests_counter.inc() + + if model_id in self.models: + # Move the model to the end of the OrderedDict to ensure LRU caching. + model = self.models.pop(model_id) + self.models[model_id] = model + return self.models[model_id] + else: + # Set the flag to push the multiplexed replica info to the controller + # before loading the model. This is to make sure we can push the model + # id info to the controller/router early, so that requests can be routed to + # the replica. + self._push_multiplexed_replica_info = True + self._model_load_tasks.add(model_id) + async with self._model_cache_lock: + # Check if the model has been loaded by another request. + if model_id in self.models: + return self.models[model_id] + try: + # If the number of models per replica is specified, check + # if the number of models on the current replica has + # reached the limit. + if ( + self.max_num_models_per_replica > 0 + and len(self.models) >= self.max_num_models_per_replica + ): + # Unload the least recently used model. + await self.unload_model_lru() + self._push_multiplexed_replica_info = True + + # Load the model. + logger.info(f"Loading model '{model_id}'.") + self.models_load_counter.inc() + load_start_time = time.time() + if self.self_arg is None: + self.models[model_id] = await self._func(model_id) + else: + self.models[model_id] = await self._func( + self.self_arg, model_id + ) + load_latency_ms = (time.time() - load_start_time) * 1000.0 + logger.info( + f"Successfully loaded model '{model_id}' in " + f"{load_latency_ms:.1f}ms." + ) + self._model_load_tasks.discard(model_id) + self.model_load_latency_ms.observe(load_latency_ms) + return self.models[model_id] + except Exception as e: + logger.error( + f"Failed to load model '{model_id}'. Error: {e}", + ) + self._model_load_tasks.discard(model_id) + raise e + + async def unload_model_lru(self) -> None: + """Unload the least recently used model.""" + + self.models_unload_counter.inc() + unload_start_time = time.time() + model_id, model = self.models.popitem(last=False) + logger.info(f"Unloading model '{model_id}'.") + + # If the model has __del__ attribute, call it. + # This is to clean up the model resources eagerly. + if hasattr(model, "__del__"): + if not inspect.iscoroutinefunction(model.__del__): + await asyncio.get_running_loop().run_in_executor(None, model.__del__) + else: + await model.__del__() + model.__del__ = lambda _: None + unload_latency_ms = (time.time() - unload_start_time) * 1000.0 + self.model_unload_latency_ms.observe(unload_latency_ms) + logger.info( + f"Successfully unloaded model '{model_id}' in {unload_latency_ms:.1f}ms." + ) + self.registered_model_gauge.set(0, tags={"model_id": model_id}) diff --git a/venv/lib/python3.10/site-packages/ray/serve/request_router.py b/venv/lib/python3.10/site-packages/ray/serve/request_router.py new file mode 100644 index 0000000000000000000000000000000000000000..78a42829517519ad9f72a3e7f8939269ef9534ed --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/request_router.py @@ -0,0 +1,14 @@ +from ray.serve._private.common import ReplicaID # noqa: F401 +from ray.serve._private.replica_result import ReplicaResult # noqa: F401 +from ray.serve._private.request_router.common import ( # noqa: F401 + PendingRequest, +) +from ray.serve._private.request_router.replica_wrapper import ( # noqa: F401 + RunningReplica, +) +from ray.serve._private.request_router.request_router import ( # noqa: F401 + FIFOMixin, + LocalityMixin, + MultiplexMixin, + RequestRouter, +) diff --git a/venv/lib/python3.10/site-packages/ray/serve/schema.py b/venv/lib/python3.10/site-packages/ray/serve/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..607097fee8a7328c904e32341e67e7f5126f11d7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/schema.py @@ -0,0 +1,1204 @@ +import logging +from collections import Counter +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union +from zlib import crc32 + +from ray._common.pydantic_compat import ( + BaseModel, + Extra, + Field, + NonNegativeInt, + PositiveInt, + StrictInt, + root_validator, + validator, +) +from ray._private.ray_logging.constants import LOGRECORD_STANDARD_ATTRS +from ray._private.runtime_env.packaging import parse_uri +from ray.serve._private.common import ( + DeploymentStatus, + DeploymentStatusTrigger, + ReplicaState, + RequestProtocol, + ServeDeployMode, +) +from ray.serve._private.constants import ( + DEFAULT_GRPC_PORT, + DEFAULT_MAX_ONGOING_REQUESTS, + DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S, + RAY_SERVE_LOG_ENCODING, + SERVE_DEFAULT_APP_NAME, +) +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.utils import DEFAULT +from ray.serve.config import ProxyLocation, RequestRouterConfig +from ray.util.annotations import PublicAPI + +# Shared amongst multiple schemas. +TARGET_CAPACITY_FIELD = Field( + default=None, + description=( + "[EXPERIMENTAL]: the target capacity percentage for all replicas across the " + "cluster. The `num_replicas`, `min_replicas`, `max_replicas`, and " + "`initial_replicas` for each deployment will be scaled by this percentage." + ), + ge=0, + le=100, +) + + +def _route_prefix_format(cls, v): + """ + The route_prefix + 1. must start with a / character + 2. must not end with a / character (unless the entire prefix is just /) + 3. cannot contain wildcards (must not have "{" or "}") + """ + + if v is None: + return v + + if not v.startswith("/"): + raise ValueError( + f'Got "{v}" for route_prefix. Route prefix must start with "/".' + ) + if len(v) > 1 and v.endswith("/"): + raise ValueError( + f'Got "{v}" for route_prefix. Route prefix ' + 'cannot end with "/" unless the ' + 'entire prefix is just "/".' + ) + if "{" in v or "}" in v: + raise ValueError( + f'Got "{v}" for route_prefix. Route prefix ' + "cannot contain wildcards, so it cannot " + 'contain "{" or "}".' + ) + + return v + + +@PublicAPI(stability="alpha") +class EncodingType(str, Enum): + """Encoding type for the serve logs.""" + + TEXT = "TEXT" + JSON = "JSON" + + +@PublicAPI(stability="alpha") +class LoggingConfig(BaseModel): + """Logging config schema for configuring serve components logs. + + Example: + + .. code-block:: python + + from ray import serve + from ray.serve.schema import LoggingConfig + # Set log level for the deployment. + @serve.deployment(LoggingConfig(log_level="DEBUG")) + class MyDeployment: + def __call__(self) -> str: + return "Hello world!" + # Set log directory for the deployment. + @serve.deployment(LoggingConfig(logs_dir="/my_dir")) + class MyDeployment: + def __call__(self) -> str: + return "Hello world!" + """ + + class Config: + extra = Extra.forbid + + encoding: Union[str, EncodingType] = Field( + default_factory=lambda: RAY_SERVE_LOG_ENCODING, + description=( + "Encoding type for the serve logs. Defaults to 'TEXT'. The default can be " + "overwritten using the `RAY_SERVE_LOG_ENCODING` environment variable. " + "'JSON' is also supported for structured logging." + ), + ) + log_level: Union[int, str] = Field( + default="INFO", + description=( + "Log level for the serve logs. Defaults to INFO. You can set it to " + "'DEBUG' to get more detailed debug logs." + ), + ) + logs_dir: Union[str, None] = Field( + default=None, + description=( + "Directory to store the logs. Default to None, which means " + "logs will be stored in the default directory " + "('/tmp/ray/session_latest/logs/serve/...')." + ), + ) + enable_access_log: bool = Field( + default=True, + description=( + "Whether to enable access logs for each request. Default to True." + ), + ) + additional_log_standard_attrs: List[str] = Field( + default_factory=list, + description=( + "Default attributes from the Python standard logger that will be " + "added to all log records. " + "See https://docs.python.org/3/library/logging.html#logrecord-attributes " + "for a list of available attributes." + ), + ) + + @validator("encoding") + def valid_encoding_format(cls, v): + if v not in list(EncodingType): + raise ValueError( + f"Got '{v}' for encoding. Encoding must be one " + f"of {set(EncodingType)}." + ) + + return v + + @validator("log_level") + def valid_log_level(cls, v): + if isinstance(v, int): + if v not in logging._levelToName: + raise ValueError( + f'Got "{v}" for log_level. log_level must be one of ' + f"{list(logging._levelToName.keys())}." + ) + return logging._levelToName[v] + + if v not in logging._nameToLevel: + raise ValueError( + f'Got "{v}" for log_level. log_level must be one of ' + f"{list(logging._nameToLevel.keys())}." + ) + return v + + @validator("additional_log_standard_attrs") + def valid_additional_log_standard_attrs(cls, v): + for attr in v: + if attr not in LOGRECORD_STANDARD_ATTRS: + raise ValueError( + f"Unknown attribute '{attr}'. " + f"Additional log standard attributes must be one of {LOGRECORD_STANDARD_ATTRS}." + ) + return list(set(v)) + + def _compute_hash(self) -> int: + return crc32( + ( + str(self.encoding) + + str(self.log_level) + + str(self.logs_dir) + + str(self.enable_access_log) + ).encode("utf-8") + ) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, LoggingConfig): + return False + return self._compute_hash() == other._compute_hash() + + +@PublicAPI(stability="stable") +class RayActorOptionsSchema(BaseModel): + """Options with which to start a replica actor.""" + + runtime_env: dict = Field( + default={}, + description=( + "This deployment's runtime_env. working_dir and " + "py_modules may contain only remote URIs." + ), + ) + num_cpus: float = Field( + default=None, + description=( + "The number of CPUs required by the deployment's " + "application per replica. This is the same as a ray " + "actor's num_cpus. Uses a default if null." + ), + ge=0, + ) + num_gpus: float = Field( + default=None, + description=( + "The number of GPUs required by the deployment's " + "application per replica. This is the same as a ray " + "actor's num_gpus. Uses a default if null." + ), + ge=0, + ) + memory: float = Field( + default=None, + description=( + "Restrict the heap memory usage of each replica. Uses a default if null." + ), + ge=0, + ) + resources: Dict = Field( + default={}, + description=("The custom resources required by each replica."), + ) + accelerator_type: str = Field( + default=None, + description=( + "Forces replicas to run on nodes with the specified accelerator type." + "See :ref:`accelerator types `." + ), + ) + + @validator("runtime_env") + def runtime_env_contains_remote_uris(cls, v): + # Ensure that all uris in py_modules and working_dir are remote + + if v is None: + return + + uris = v.get("py_modules", []) + if "working_dir" in v: + uris = [*uris, v["working_dir"]] + + for uri in uris: + if uri is not None: + try: + parse_uri(uri) + except ValueError as e: + raise ValueError( + "runtime_envs in the Serve config support only " + "remote URIs in working_dir and py_modules. Got " + f"error when parsing URI: {e}" + ) + + return v + + +@PublicAPI(stability="stable") +class DeploymentSchema(BaseModel, allow_population_by_field_name=True): + """ + Specifies options for one deployment within a Serve application. For each deployment + this can optionally be included in `ServeApplicationSchema` to override deployment + options specified in code. + """ + + name: str = Field( + ..., description=("Globally-unique name identifying this deployment.") + ) + num_replicas: Optional[Union[PositiveInt, str]] = Field( + default=DEFAULT.VALUE, + description=( + "The number of processes that handle requests to this " + "deployment. Uses a default if null. Can also be set to " + "`auto` for a default autoscaling configuration " + "(experimental)." + ), + ) + max_ongoing_requests: int = Field( + default=DEFAULT.VALUE, + description=( + "Maximum number of requests that are sent in parallel " + "to each replica of this deployment. The limit is enforced across all " + "callers (HTTP requests or DeploymentHandles). Defaults to " + f"{DEFAULT_MAX_ONGOING_REQUESTS}." + ), + gt=0, + ) + max_queued_requests: StrictInt = Field( + default=DEFAULT.VALUE, + description=( + "[DEPRECATED] The max number of requests that will be executed at once in " + f"each replica. Defaults to {DEFAULT_MAX_ONGOING_REQUESTS}." + ), + ) + user_config: Optional[Dict] = Field( + default=DEFAULT.VALUE, + description=( + "Config to pass into this deployment's " + "reconfigure method. This can be updated dynamically " + "without restarting replicas" + ), + ) + autoscaling_config: Optional[Dict] = Field( + default=DEFAULT.VALUE, + description=( + "Config specifying autoscaling " + "parameters for the deployment's number of replicas. " + "If null, the deployment won't autoscale its number of " + "replicas; the number of replicas will be fixed at " + "num_replicas." + ), + ) + graceful_shutdown_wait_loop_s: float = Field( + default=DEFAULT.VALUE, + description=( + "Duration that deployment replicas will wait until there " + "is no more work to be done before shutting down. Uses a " + "default if null." + ), + ge=0, + ) + graceful_shutdown_timeout_s: float = Field( + default=DEFAULT.VALUE, + description=( + "Serve controller waits for this duration before " + "forcefully killing the replica for shutdown. Uses a " + "default if null." + ), + ge=0, + ) + health_check_period_s: float = Field( + default=DEFAULT.VALUE, + description=( + "Frequency at which the controller will health check " + "replicas. Uses a default if null." + ), + gt=0, + ) + health_check_timeout_s: float = Field( + default=DEFAULT.VALUE, + description=( + "Timeout that the controller will wait for a response " + "from the replica's health check before marking it " + "unhealthy. Uses a default if null." + ), + gt=0, + ) + ray_actor_options: RayActorOptionsSchema = Field( + default=DEFAULT.VALUE, description="Options set for each replica actor." + ) + + placement_group_bundles: List[Dict[str, float]] = Field( + default=DEFAULT.VALUE, + description=( + "Define a set of placement group bundles to be " + "scheduled *for each replica* of this deployment. The replica actor will " + "be scheduled in the first bundle provided, so the resources specified in " + "`ray_actor_options` must be a subset of the first bundle's resources. All " + "actors and tasks created by the replica actor will be scheduled in the " + "placement group by default (`placement_group_capture_child_tasks` is set " + "to True)." + ), + ) + + placement_group_strategy: str = Field( + default=DEFAULT.VALUE, + description=( + "Strategy to use for the replica placement group " + "specified via `placement_group_bundles`. Defaults to `PACK`." + ), + ) + + max_replicas_per_node: int = Field( + default=DEFAULT.VALUE, + description=( + "The max number of replicas of this deployment that can run on a single " + "Valid values are None (default, no limit) or an integer in the range of " + "[1, 100]. " + ), + ) + logging_config: LoggingConfig = Field( + default=DEFAULT.VALUE, + description="Logging config for configuring serve deployment logs.", + ) + request_router_config: Union[Dict, RequestRouterConfig] = Field( + default=DEFAULT.VALUE, + description="Config for the request router used for this deployment.", + ) + + @root_validator + def validate_num_replicas_and_autoscaling_config(cls, values): + num_replicas = values.get("num_replicas", None) + autoscaling_config = values.get("autoscaling_config", None) + + # Cannot have `num_replicas` be an int and a non-null + # autoscaling config + if isinstance(num_replicas, int): + if autoscaling_config not in [None, DEFAULT.VALUE]: + raise ValueError( + "Manually setting num_replicas is not allowed " + "when autoscaling_config is provided." + ) + # A null `num_replicas` or `num_replicas="auto"` can be paired + # with a non-null autoscaling_config + elif num_replicas not in ["auto", None, DEFAULT.VALUE]: + raise ValueError( + f'`num_replicas` must be an int or "auto", but got: {num_replicas}' + ) + + return values + + @root_validator + def validate_max_replicas_per_node_and_placement_group_bundles(cls, values): + max_replicas_per_node = values.get("max_replicas_per_node", None) + placement_group_bundles = values.get("placement_group_bundles", None) + + if max_replicas_per_node not in [ + DEFAULT.VALUE, + None, + ] and placement_group_bundles not in [DEFAULT.VALUE, None]: + raise ValueError( + "Setting max_replicas_per_node is not allowed when " + "placement_group_bundles is provided." + ) + + return values + + @root_validator + def validate_max_queued_requests(cls, values): + max_queued_requests = values.get("max_queued_requests", None) + if max_queued_requests is None or max_queued_requests == DEFAULT.VALUE: + return values + + if max_queued_requests < 1 and max_queued_requests != -1: + raise ValueError( + "max_queued_requests must be -1 (no limit) or a positive integer." + ) + + return values + + def _get_user_configured_option_names(self) -> Set[str]: + """Get set of names for all user-configured options. + + Any field not set to DEFAULT.VALUE is considered a user-configured option. + """ + + return { + field for field, value in self.dict().items() if value is not DEFAULT.VALUE + } + + +def _deployment_info_to_schema(name: str, info: DeploymentInfo) -> DeploymentSchema: + """Converts a DeploymentInfo object to DeploymentSchema.""" + + schema = DeploymentSchema( + name=name, + max_ongoing_requests=info.deployment_config.max_ongoing_requests, + max_queued_requests=info.deployment_config.max_queued_requests, + user_config=info.deployment_config.user_config, + graceful_shutdown_wait_loop_s=( + info.deployment_config.graceful_shutdown_wait_loop_s + ), + graceful_shutdown_timeout_s=info.deployment_config.graceful_shutdown_timeout_s, + health_check_period_s=info.deployment_config.health_check_period_s, + health_check_timeout_s=info.deployment_config.health_check_timeout_s, + ray_actor_options=info.replica_config.ray_actor_options, + request_router_config=info.deployment_config.request_router_config, + ) + + if info.deployment_config.autoscaling_config is not None: + schema.autoscaling_config = info.deployment_config.autoscaling_config.dict() + else: + schema.num_replicas = info.deployment_config.num_replicas + + return schema + + +@PublicAPI(stability="stable") +class ServeApplicationSchema(BaseModel): + """ + Describes one Serve application, and currently can also be used as a standalone + config to deploy a single application to a Ray cluster. + """ + + name: str = Field( + default=SERVE_DEFAULT_APP_NAME, + description=( + "Application name, the name should be unique within the serve instance" + ), + ) + route_prefix: Optional[str] = Field( + default="/", + description=( + "Route prefix for HTTP requests. If not provided, it will use" + "route_prefix of the ingress deployment. By default, the ingress route " + "prefix is '/'." + ), + ) + import_path: str = Field( + ..., + description=( + "An import path to a bound deployment node. Should be of the " + 'form "module.submodule_1...submodule_n.' + 'dag_node". This is equivalent to ' + '"from module.submodule_1...submodule_n import ' + 'dag_node". Only works with Python ' + "applications. This field is REQUIRED when deploying Serve config " + "to a Ray cluster." + ), + ) + runtime_env: dict = Field( + default={}, + description=( + "The runtime_env that the deployment graph will be run in. " + "Per-deployment runtime_envs will inherit from this. working_dir " + "and py_modules may contain only remote URIs." + ), + ) + host: str = Field( + default="0.0.0.0", + description=( + "Host for HTTP servers to listen on. Defaults to " + '"0.0.0.0", which exposes Serve publicly. Cannot be updated once ' + "your Serve application has started running. The Serve application " + "must be shut down and restarted with the new host instead." + ), + ) + port: int = Field( + default=8000, + description=( + "Port for HTTP server. Defaults to 8000. Cannot be updated once " + "your Serve application has started running. The Serve application " + "must be shut down and restarted with the new port instead." + ), + ) + deployments: List[DeploymentSchema] = Field( + default=[], + description="Deployment options that override options specified in the code.", + ) + args: Dict = Field( + default={}, + description="Arguments that will be passed to the application builder.", + ) + logging_config: LoggingConfig = Field( + default=None, + description="Logging config for configuring serve application logs.", + ) + + @property + def deployment_names(self) -> List[str]: + return [d.name for d in self.deployments] + + @validator("runtime_env") + def runtime_env_contains_remote_uris(cls, v): + # Ensure that all uris in py_modules and working_dir are remote. + if v is None: + return + + uris = v.get("py_modules", []) + if "working_dir" in v: + uris = [*uris, v["working_dir"]] + + for uri in uris: + if uri is not None: + try: + parse_uri(uri) + except ValueError as e: + raise ValueError( + "runtime_envs in the Serve config support only " + "remote URIs in working_dir and py_modules. Got " + f"error when parsing URI: {e}" + ) + + return v + + @validator("import_path") + def import_path_format_valid(cls, v: str): + if v is None: + return + + if ":" in v: + if v.count(":") > 1: + raise ValueError( + f'Got invalid import path "{v}". An ' + "import path may have at most one colon." + ) + if v.rfind(":") == 0 or v.rfind(":") == len(v) - 1: + raise ValueError( + f'Got invalid import path "{v}". An ' + "import path may not start or end with a colon." + ) + return v + else: + if v.count(".") < 1: + raise ValueError( + f'Got invalid import path "{v}". An ' + "import path must contain at least on dot or colon " + "separating the module (and potentially submodules) from " + 'the deployment graph. E.g.: "module.deployment_graph".' + ) + if v.rfind(".") == 0 or v.rfind(".") == len(v) - 1: + raise ValueError( + f'Got invalid import path "{v}". An ' + "import path may not start or end with a dot." + ) + + return v + + @staticmethod + def get_empty_schema_dict() -> Dict: + """Returns an empty app schema dictionary. + + Schema can be used as a representation of an empty Serve application config. + """ + + return { + "import_path": "", + "runtime_env": {}, + "deployments": [], + } + + +@PublicAPI(stability="alpha") +class gRPCOptionsSchema(BaseModel): + """Options to start the gRPC Proxy with.""" + + port: int = Field( + default=DEFAULT_GRPC_PORT, + description=( + "Port for gRPC server. Defaults to 9000. Cannot be updated once " + "Serve has started running. Serve must be shut down and restarted " + "with the new port instead." + ), + ) + grpc_servicer_functions: List[str] = Field( + default=[], + description=( + "List of import paths for gRPC `add_servicer_to_server` functions to add " + "to Serve's gRPC proxy. Default to empty list, which means no gRPC methods " + "will be added and no gRPC server will be started. The servicer functions " + "need to be importable from the context of where Serve is running." + ), + ) + request_timeout_s: float = Field( + default=None, + description="The timeout for gRPC requests. Defaults to no timeout.", + ) + + +@PublicAPI(stability="stable") +class HTTPOptionsSchema(BaseModel): + """Options to start the HTTP Proxy with. + + NOTE: This config allows extra parameters to make it forward-compatible (ie + older versions of Serve are able to accept configs from a newer versions, + simply ignoring new parameters). + """ + + host: str = Field( + default="0.0.0.0", + description=( + "Host for HTTP servers to listen on. Defaults to " + '"0.0.0.0", which exposes Serve publicly. Cannot be updated once ' + "Serve has started running. Serve must be shut down and restarted " + "with the new host instead." + ), + ) + port: int = Field( + default=8000, + description=( + "Port for HTTP server. Defaults to 8000. Cannot be updated once " + "Serve has started running. Serve must be shut down and restarted " + "with the new port instead." + ), + ) + root_path: str = Field( + default="", + description=( + 'Root path to mount the serve application (for example, "/serve"). All ' + 'deployment routes will be prefixed with this path. Defaults to "".' + ), + ) + request_timeout_s: float = Field( + default=None, + description="The timeout for HTTP requests. Defaults to no timeout.", + ) + keep_alive_timeout_s: int = Field( + default=DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S, + description="The HTTP proxy will keep idle connections alive for this duration " + "before closing them when no requests are ongoing. Defaults to " + f"{DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S} seconds.", + ) + + +@PublicAPI(stability="stable") +class ServeDeploySchema(BaseModel): + """ + Multi-application config for deploying a list of Serve applications to the Ray + cluster. + + This is the request JSON schema for the v2 REST API + `PUT "/api/serve/applications/"`. + + NOTE: This config allows extra parameters to make it forward-compatible (ie + older versions of Serve are able to accept configs from a newer versions, + simply ignoring new parameters) + """ + + proxy_location: ProxyLocation = Field( + default=ProxyLocation.EveryNode, + description=( + "Config for where to run proxies for ingress traffic to the cluster." + ), + ) + http_options: HTTPOptionsSchema = Field( + default=HTTPOptionsSchema(), description="Options to start the HTTP Proxy with." + ) + grpc_options: gRPCOptionsSchema = Field( + default=gRPCOptionsSchema(), description="Options to start the gRPC Proxy with." + ) + logging_config: LoggingConfig = Field( + default=None, + description="Logging config for configuring serve components logs.", + ) + applications: List[ServeApplicationSchema] = Field( + ..., description="The set of applications to run on the Ray cluster." + ) + target_capacity: Optional[float] = TARGET_CAPACITY_FIELD + + @validator("applications") + def application_names_unique(cls, v): + # Ensure there are no duplicate applications listed + names = [app.name for app in v] + duplicates = {f'"{name}"' for name in names if names.count(name) > 1} + if len(duplicates): + apps_str = ("application " if len(duplicates) == 1 else "applications ") + ( + ", ".join(duplicates) + ) + raise ValueError( + f"Found multiple configs for {apps_str}. Please remove all duplicates." + ) + return v + + @validator("applications") + def application_routes_unique(cls, v): + # Ensure each application with a non-null route prefix has unique route prefixes + routes = [app.route_prefix for app in v if app.route_prefix is not None] + duplicates = {f'"{route}"' for route in routes if routes.count(route) > 1} + if len(duplicates): + routes_str = ( + "route prefix " if len(duplicates) == 1 else "route prefixes " + ) + (", ".join(duplicates)) + raise ValueError( + f"Found duplicate applications for {routes_str}. Please ensure each " + "application's route_prefix is unique." + ) + return v + + @validator("applications") + def application_names_nonempty(cls, v): + for app in v: + if len(app.name) == 0: + raise ValueError("Application names must be nonempty.") + return v + + @root_validator + def nested_host_and_port(cls, values): + # TODO (zcin): ServeApplicationSchema still needs to have host and port + # fields to support single-app mode, but in multi-app mode the host and port + # fields at the top-level deploy config is used instead. Eventually, after + # migration, we should remove these fields from ServeApplicationSchema. + for app_config in values.get("applications"): + if "host" in app_config.dict(exclude_unset=True): + raise ValueError( + f'Host "{app_config.host}" is set in the config for application ' + f"`{app_config.name}`. Please remove it and set host in the top " + "level deploy config only." + ) + if "port" in app_config.dict(exclude_unset=True): + raise ValueError( + f"Port {app_config.port} is set in the config for application " + f"`{app_config.name}`. Please remove it and set port in the top " + "level deploy config only." + ) + return values + + @staticmethod + def get_empty_schema_dict() -> Dict: + """Returns an empty deploy schema dictionary. + + Schema can be used as a representation of an empty Serve deploy config. + """ + + return {"applications": []} + + +# Keep in sync with ServeSystemActorStatus in +# python/ray/dashboard/client/src/type/serve.ts +@PublicAPI(stability="stable") +class ProxyStatus(str, Enum): + """The current status of the proxy.""" + + STARTING = "STARTING" + HEALTHY = "HEALTHY" + UNHEALTHY = "UNHEALTHY" + DRAINING = "DRAINING" + # The DRAINED status is a momentary state + # just before the proxy is removed + # so this status won't show up on the dashboard. + DRAINED = "DRAINED" + + +@PublicAPI(stability="alpha") +@dataclass +class DeploymentStatusOverview: + """Describes the status of a deployment. + + Attributes: + status: The current status of the deployment. + replica_states: A map indicating how many replicas there are of + each replica state. + message: A message describing the deployment status in more + detail. + """ + + status: DeploymentStatus + status_trigger: DeploymentStatusTrigger + replica_states: Dict[ReplicaState, int] + message: str + + +@PublicAPI(stability="stable") +class ApplicationStatus(str, Enum): + """The current status of the application.""" + + NOT_STARTED = "NOT_STARTED" + DEPLOYING = "DEPLOYING" + DEPLOY_FAILED = "DEPLOY_FAILED" + RUNNING = "RUNNING" + UNHEALTHY = "UNHEALTHY" + DELETING = "DELETING" + + +@PublicAPI(stability="alpha") +@dataclass +class ApplicationStatusOverview: + """Describes the status of an application and all its deployments. + + Attributes: + status: The current status of the application. + message: A message describing the application status in more + detail. + last_deployed_time_s: The time at which the application was + deployed. A Unix timestamp in seconds. + deployments: The deployments in this application. + """ + + status: ApplicationStatus + message: str + last_deployed_time_s: float + deployments: Dict[str, DeploymentStatusOverview] + + +@PublicAPI(stability="alpha") +@dataclass(eq=True) +class ServeStatus: + """Describes the status of Serve. + + Attributes: + proxies: The proxy actors running on each node in the cluster. + A map from node ID to proxy status. + applications: The live applications in the cluster. + target_capacity: the target capacity percentage for all replicas across the + cluster. + """ + + proxies: Dict[str, ProxyStatus] = field(default_factory=dict) + applications: Dict[str, ApplicationStatusOverview] = field(default_factory=dict) + target_capacity: Optional[float] = TARGET_CAPACITY_FIELD + + +@PublicAPI(stability="stable") +class ServeActorDetails(BaseModel, frozen=True): + """Detailed info about a Ray Serve actor. + + Attributes: + node_id: ID of the node that the actor is running on. + node_ip: IP address of the node that the actor is running on. + node_instance_id: Cloud provider instance id of the node that the actor is running on. + actor_id: Actor ID. + actor_name: Actor name. + worker_id: Worker ID. + log_file_path: The relative path to the Serve actor's log file from the ray logs + directory. + """ + + node_id: Optional[str] = Field( + description="ID of the node that the actor is running on." + ) + node_ip: Optional[str] = Field( + description="IP address of the node that the actor is running on." + ) + node_instance_id: Optional[str] = Field( + description="Cloud provider instance id of the node that the actor is running on." + ) + actor_id: Optional[str] = Field(description="Actor ID.") + actor_name: Optional[str] = Field(description="Actor name.") + worker_id: Optional[str] = Field(description="Worker ID.") + log_file_path: Optional[str] = Field( + description=( + "The relative path to the Serve actor's log file from the ray logs " + "directory." + ) + ) + + +@PublicAPI(stability="stable") +class ReplicaDetails(ServeActorDetails, frozen=True): + """Detailed info about a single deployment replica.""" + + replica_id: str = Field(description="Unique ID for the replica.") + state: ReplicaState = Field(description="Current state of the replica.") + pid: Optional[int] = Field(description="PID of the replica actor process.") + start_time_s: float = Field( + description=( + "The time at which the replica actor was started. If the controller dies, " + "this is the time at which the controller recovers and retrieves replica " + "state from the running replica actor." + ) + ) + + +@PublicAPI(stability="stable") +class DeploymentDetails(BaseModel, extra=Extra.forbid, frozen=True): + """ + Detailed info about a deployment within a Serve application. + """ + + name: str = Field(description="Deployment name.") + status: DeploymentStatus = Field( + description="The current status of the deployment." + ) + status_trigger: DeploymentStatusTrigger = Field( + description="[EXPERIMENTAL] The trigger for the current status.", + ) + message: str = Field( + description=( + "If there are issues with the deployment, this will describe the issue in " + "more detail." + ) + ) + deployment_config: DeploymentSchema = Field( + description=( + "The set of deployment config options that are currently applied to this " + "deployment. These options may come from the user's code, config file " + "options, or Serve default values." + ) + ) + target_num_replicas: NonNegativeInt = Field( + description=( + "The current target number of replicas for this deployment. This can " + "change over time for autoscaling deployments, but will remain a constant " + "number for other deployments." + ) + ) + required_resources: Dict = Field( + description="The resources required per replica of this deployment." + ) + replicas: List[ReplicaDetails] = Field( + description="Details about the live replicas of this deployment." + ) + + +@PublicAPI(stability="alpha") +class APIType(str, Enum): + """Tracks the type of API that an application originates from.""" + + UNKNOWN = "unknown" + IMPERATIVE = "imperative" + DECLARATIVE = "declarative" + + +@PublicAPI(stability="stable") +class ApplicationDetails(BaseModel, extra=Extra.forbid, frozen=True): + """Detailed info about a Serve application.""" + + name: str = Field(description="Application name.") + route_prefix: Optional[str] = Field( + ..., + description=( + "This is the `route_prefix` of the ingress deployment in the application. " + "Requests to paths under this HTTP path prefix will be routed to this " + "application. This value may be null if the application is deploying " + "and app information has not yet fully propagated in the backend; or " + "if the user explicitly set the prefix to `None`, so the application isn't " + "exposed over HTTP. Routing is done based on longest-prefix match, so if " + 'you have deployment A with a prefix of "/a" and deployment B with a ' + 'prefix of "/a/b", requests to "/a", "/a/", and "/a/c" go to A and ' + 'requests to "/a/b", "/a/b/", and "/a/b/c" go to B. Routes must not end ' + 'with a "/" unless they\'re the root (just "/"), which acts as a catch-all.' + ), + ) + docs_path: Optional[str] = Field( + ..., + description=( + "The path at which the docs for this application is served, for instance " + "the `docs_url` for FastAPI-integrated applications." + ), + ) + status: ApplicationStatus = Field( + description="The current status of the application." + ) + message: str = Field( + description="A message that gives more insight into the application status." + ) + last_deployed_time_s: float = Field( + description="The time at which the application was deployed." + ) + deployed_app_config: Optional[ServeApplicationSchema] = Field( + description=( + "The exact copy of the application config that was submitted to the " + "cluster. This will include all of, and only, the options that were " + "explicitly specified in the submitted config. Default values for " + "unspecified options will not be displayed, and deployments that are part " + "of the application but unlisted in the config will also not be displayed. " + "Note that default values for unspecified options are applied to the " + "cluster under the hood, and deployments that were unlisted will still be " + "deployed. This config simply avoids cluttering with unspecified fields " + "for readability." + ) + ) + source: APIType = Field( + description=( + "The type of API that the application originates from. " + "This is a Developer API that is subject to change." + ), + ) + deployments: Dict[str, DeploymentDetails] = Field( + description="Details about the deployments in this application." + ) + + application_details_route_prefix_format = validator( + "route_prefix", allow_reuse=True + )(_route_prefix_format) + + +@PublicAPI(stability="stable") +class ProxyDetails(ServeActorDetails, frozen=True): + """Detailed info about a Ray Serve ProxyActor. + + Attributes: + status: The current status of the proxy. + """ + + status: ProxyStatus = Field(description="Current status of the proxy.") + + +@PublicAPI(stability="alpha") +class Target(BaseModel, frozen=True): + ip: str = Field(description="IP address of the target.") + port: int = Field(description="Port of the target.") + instance_id: str = Field(description="Instance ID of the target.") + + +@PublicAPI(stability="alpha") +class TargetGroup(BaseModel, frozen=True): + targets: List[Target] = Field(description="List of targets for the given route.") + route_prefix: str = Field(description="Prefix route of the targets.") + protocol: RequestProtocol = Field(description="Protocol of the targets.") + + +@PublicAPI(stability="stable") +class ServeInstanceDetails(BaseModel, extra=Extra.forbid): + """ + Serve metadata with system-level info and details on all applications deployed to + the Ray cluster. + + This is the response JSON schema for v2 REST API `GET /api/serve/applications`. + """ + + controller_info: ServeActorDetails = Field( + description="Details about the Serve controller actor." + ) + proxy_location: Optional[ProxyLocation] = Field( + description=( + "Config for where to run proxies for ingress traffic to the cluster.\n" + '- "Disabled": disable the proxies entirely.\n' + '- "HeadOnly": run only one proxy on the head node.\n' + '- "EveryNode": run proxies on every node that has at least one replica.\n' + ), + ) + http_options: Optional[HTTPOptionsSchema] = Field(description="HTTP Proxy options.") + grpc_options: Optional[gRPCOptionsSchema] = Field(description="gRPC Proxy options.") + proxies: Dict[str, ProxyDetails] = Field( + description=( + "Mapping from node_id to details about the Proxy running on that node." + ) + ) + deploy_mode: ServeDeployMode = Field( + default=ServeDeployMode.MULTI_APP, + description=( + "[DEPRECATED]: single-app configs are removed, so this is always " + "MULTI_APP. This field will be removed in a future release." + ), + ) + applications: Dict[str, ApplicationDetails] = Field( + description="Details about all live applications running on the cluster." + ) + target_capacity: Optional[float] = TARGET_CAPACITY_FIELD + + target_groups: List[TargetGroup] = Field( + default_factory=list, + description=( + "List of target groups, each containing target info for a given route and " + "protocol." + ), + ) + + @staticmethod + def get_empty_schema_dict() -> Dict: + """Empty Serve instance details dictionary. + + Represents no Serve instance running on the cluster. + """ + + return { + "deploy_mode": "MULTI_APP", + "controller_info": {}, + "proxies": {}, + "applications": {}, + "target_capacity": None, + } + + def _get_status(self) -> ServeStatus: + return ServeStatus( + target_capacity=self.target_capacity, + proxies={node_id: proxy.status for node_id, proxy in self.proxies.items()}, + applications={ + app_name: ApplicationStatusOverview( + status=app.status, + message=app.message, + last_deployed_time_s=app.last_deployed_time_s, + deployments={ + deployment_name: DeploymentStatusOverview( + status=deployment.status, + status_trigger=deployment.status_trigger, + replica_states=dict( + Counter([r.state.value for r in deployment.replicas]) + ), + message=deployment.message, + ) + for deployment_name, deployment in app.deployments.items() + }, + ) + for app_name, app in self.applications.items() + }, + ) + + def _get_user_facing_json_serializable_dict( + self, *args, **kwargs + ) -> Dict[str, Any]: + """Generates json serializable dictionary with user facing data.""" + values = super().dict(*args, **kwargs) + + # `serialized_policy_def` and internal router config fields are only used + # internally and should not be exposed to the REST api. This method iteratively + # removes them from each deployment config if exists. + for app_name, application in values["applications"].items(): + for deployment_name, deployment in application["deployments"].items(): + if "deployment_config" in deployment: + # Remove internal fields from request_router_config if it exists + if "request_router_config" in deployment["deployment_config"]: + deployment["deployment_config"]["request_router_config"].pop( + "_serialized_request_router_cls", None + ) + if "autoscaling_config" in deployment["deployment_config"]: + deployment["deployment_config"]["autoscaling_config"].pop( + "_serialized_policy_def", None + ) + + return values diff --git a/venv/lib/python3.10/site-packages/ray/serve/scripts.py b/venv/lib/python3.10/site-packages/ray/serve/scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..44e7e2f928d06542c7a862a23283e821d1d53fda --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/serve/scripts.py @@ -0,0 +1,916 @@ +#!/usr/bin/env python +import os +import pathlib +import re +import sys +import time +import traceback +from dataclasses import asdict +from typing import Any, Dict, List, Optional, Tuple + +import click +import watchfiles +import yaml + +import ray +from ray import serve +from ray._common.utils import import_attr +from ray.autoscaler._private.cli_logger import cli_logger +from ray.dashboard.modules.dashboard_sdk import parse_runtime_env_args +from ray.dashboard.modules.serve.sdk import ServeSubmissionClient +from ray.serve._private import api as _private_api +from ray.serve._private.build_app import BuiltApplication, build_app +from ray.serve._private.constants import ( + DEFAULT_GRPC_PORT, + DEFAULT_HTTP_HOST, + DEFAULT_HTTP_PORT, + SERVE_DEFAULT_APP_NAME, + SERVE_NAMESPACE, +) +from ray.serve.config import DeploymentMode, ProxyLocation, gRPCOptions +from ray.serve.deployment import Application, deployment_to_schema +from ray.serve.schema import ( + LoggingConfig, + ServeApplicationSchema, + ServeDeploySchema, + ServeInstanceDetails, +) + +APP_DIR_HELP_STR = ( + "Local directory to look for the IMPORT_PATH (will be inserted into " + "PYTHONPATH). Defaults to '.', meaning that an object in ./main.py " + "can be imported as 'main.object'. Not relevant if you're importing " + "from an installed module." +) +RAY_INIT_ADDRESS_HELP_STR = ( + "Address to use for ray.init(). Can also be set using " + "the RAY_ADDRESS environment variable." +) +RAY_DASHBOARD_ADDRESS_HELP_STR = ( + "Address for the Ray dashboard. Defaults to http://localhost:8265. " + "Can also be set using the RAY_DASHBOARD_ADDRESS environment variable." +) + + +# See https://stackoverflow.com/a/33300001/11162437 +def str_presenter(dumper: yaml.Dumper, data): + """ + A custom representer to write multi-line strings in block notation using a literal + style. + + Ensures strings with newline characters print correctly. + """ + + if len(data.splitlines()) > 1: + return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|") + return dumper.represent_scalar("tag:yaml.org,2002:str", data) + + +# See https://stackoverflow.com/a/14693789/11162437 +def remove_ansi_escape_sequences(input: str): + """Removes ANSI escape sequences in a string""" + ansi_escape = re.compile( + r""" + \x1B # ESC + (?: # 7-bit C1 Fe (except CSI) + [@-Z\\-_] + | # or [ for CSI, followed by a control sequence + \[ + [0-?]* # Parameter bytes + [ -/]* # Intermediate bytes + [@-~] # Final byte + ) + """, + re.VERBOSE, + ) + + return ansi_escape.sub("", input) + + +def process_dict_for_yaml_dump(data): + """ + Removes ANSI escape sequences recursively for all strings in dict. + + We often need to use yaml.dump() to print dictionaries that contain exception + tracebacks, which can contain ANSI escape sequences that color printed text. However + yaml.dump() will format the tracebacks incorrectly if ANSI escape sequences are + present, so we need to remove them before dumping. + """ + + for k, v in data.items(): + if isinstance(v, dict): + data[k] = process_dict_for_yaml_dump(v) + if isinstance(v, list): + data[k] = [process_dict_for_yaml_dump(item) for item in v] + elif isinstance(v, str): + data[k] = remove_ansi_escape_sequences(v) + + return data + + +def convert_args_to_dict(args: Tuple[str]) -> Dict[str, str]: + args_dict = dict() + for arg in args: + split = arg.split("=", maxsplit=1) + if len(split) != 2 or len(split[1]) == 0: + raise click.ClickException( + f"Invalid application argument '{arg}', " + "must be of the form '='." + ) + + args_dict[split[0]] = split[1] + + return args_dict + + +def warn_if_agent_address_set(): + if "RAY_AGENT_ADDRESS" in os.environ: + cli_logger.warning( + "The `RAY_AGENT_ADDRESS` env var has been deprecated in favor of " + "the `RAY_DASHBOARD_ADDRESS` env var. The `RAY_AGENT_ADDRESS` is " + "ignored." + ) + + +@click.group( + help="CLI for managing Serve applications on a Ray cluster.", + context_settings=dict(help_option_names=["--help", "-h"]), +) +def cli(): + pass + + +@cli.command(help="Start Serve on the Ray cluster.") +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_ADDRESS", "auto"), + required=False, + type=str, + help=RAY_INIT_ADDRESS_HELP_STR, +) +@click.option( + "--http-host", + default=DEFAULT_HTTP_HOST, + required=False, + type=str, + help="Host for HTTP proxies to listen on. " f"Defaults to {DEFAULT_HTTP_HOST}.", +) +@click.option( + "--http-port", + default=DEFAULT_HTTP_PORT, + required=False, + type=int, + help="Port for HTTP proxies to listen on. " f"Defaults to {DEFAULT_HTTP_PORT}.", +) +@click.option( + "--http-location", + default=DeploymentMode.HeadOnly, + required=False, + type=click.Choice(list(DeploymentMode)), + help="DEPRECATED: Use `--proxy-location` instead.", +) +@click.option( + "--proxy-location", + default=ProxyLocation.EveryNode, + required=False, + type=click.Choice(list(ProxyLocation)), + help="Location of the proxies. Defaults to EveryNode.", +) +@click.option( + "--grpc-port", + default=DEFAULT_GRPC_PORT, + required=False, + type=int, + help="Port for gRPC proxies to listen on. " f"Defaults to {DEFAULT_GRPC_PORT}.", +) +@click.option( + "--grpc-servicer-functions", + default=[], + required=False, + multiple=True, + help="Servicer function for adding the method handler to the gRPC server. " + "Defaults to an empty list and no gRPC server is started.", +) +def start( + address, + http_host, + http_port, + http_location, + proxy_location, + grpc_port, + grpc_servicer_functions, +): + if http_location != DeploymentMode.HeadOnly: + cli_logger.warning( + "The `--http-location` flag to `serve start` is deprecated, " + "use `--proxy-location` instead." + ) + + proxy_location = http_location + + ray.init( + address=address, + namespace=SERVE_NAMESPACE, + ) + serve.start( + proxy_location=proxy_location, + http_options=dict( + host=http_host, + port=http_port, + ), + grpc_options=gRPCOptions( + port=grpc_port, + grpc_servicer_functions=grpc_servicer_functions, + ), + ) + + +def _generate_config_from_file_or_import_path( + config_or_import_path: str, + *, + name: Optional[str], + arguments: Dict[str, str], + runtime_env: Optional[Dict[str, Any]], +) -> ServeDeploySchema: + """Generates a deployable config schema for the passed application(s).""" + if pathlib.Path(config_or_import_path).is_file(): + config_path = config_or_import_path + cli_logger.print(f"Deploying from config file: '{config_path}'.") + if len(arguments) > 0: + raise click.ClickException( + "Application arguments cannot be specified for a config file." + ) + + # TODO(edoakes): should we enable overriding? + with open(config_path, "r") as config_file: + if runtime_env and len(runtime_env) > 0: + cli_logger.warning( + "Passed in runtime_env is ignored when using config file" + ) + if name is not None: + cli_logger.warning("Passed in name is ignored when using config file") + config_dict = yaml.safe_load(config_file) + config = ServeDeploySchema.parse_obj(config_dict) + else: + # TODO(edoakes): should we default to --working-dir="." for this? + import_path = config_or_import_path + cli_logger.print(f"Deploying from import path: '{import_path}'.") + + app = ServeApplicationSchema( + import_path=import_path, + runtime_env=runtime_env, + args=arguments, + ) + if name is not None: + app.name = name + config = ServeDeploySchema(applications=[app]) + + return config + + +@cli.command( + short_help="Deploy an application or group of applications.", + help=( + "Deploy an application from an import path (e.g., main:app) " + "or a group of applications from a YAML config file.\n\n" + "Passed import paths must point to an Application object or " + "a function that returns one. If a function is used, arguments can be " + "passed to it in 'key=val' format after the import path, for example:\n\n" + "serve deploy main:app model_path='/path/to/model.pkl' num_replicas=5\n\n" + "This command makes a REST API request to a running Ray cluster." + ), +) +@click.argument("config_or_import_path") +@click.argument("arguments", nargs=-1, required=False) +@click.option( + "--runtime-env", + type=str, + default=None, + required=False, + help=( + "Path to a local YAML file containing a runtime_env definition. Ignored " + "when deploying from a config file." + ), +) +@click.option( + "--runtime-env-json", + type=str, + default=None, + required=False, + help=( + "JSON-serialized runtime_env dictionary. Ignored when deploying from a " + "config file." + ), +) +@click.option( + "--working-dir", + type=str, + default=None, + required=False, + help=( + "Directory containing files that your application(s) will run in. This must " + "be a remote URI to a .zip file (e.g., S3 bucket). This overrides the " + "working_dir in --runtime-env if both are specified. Ignored when deploying " + "from a config file." + ), +) +@click.option( + "--name", + required=False, + default=None, + type=str, + help="Custom name for the application. Ignored when deploying from a config file.", +) +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_DASHBOARD_ADDRESS", "http://localhost:8265"), + required=False, + type=str, + help=RAY_DASHBOARD_ADDRESS_HELP_STR, +) +def deploy( + config_or_import_path: str, + arguments: Tuple[str], + runtime_env: str, + runtime_env_json: str, + working_dir: str, + name: Optional[str], + address: str, +): + args_dict = convert_args_to_dict(arguments) + final_runtime_env = parse_runtime_env_args( + runtime_env=runtime_env, + runtime_env_json=runtime_env_json, + working_dir=working_dir, + ) + + config = _generate_config_from_file_or_import_path( + config_or_import_path, + name=name, + arguments=args_dict, + runtime_env=final_runtime_env, + ) + + ServeSubmissionClient(address).deploy_applications( + config.dict(exclude_unset=True), + ) + cli_logger.success( + "\nSent deploy request successfully.\n " + "* Use `serve status` to check applications' statuses.\n " + "* Use `serve config` to see the current application config(s).\n" + ) + + +@cli.command( + short_help="Run an application or group of applications.", + help=( + "Run an application from an import path (e.g., my_script:" + "app) or a group of applications from a YAML config file.\n\n" + "Passed import paths must point to an Application object or " + "a function that returns one. If a function is used, arguments can be " + "passed to it in 'key=val' format after the import path, for example:\n\n" + "serve run my_script:app model_path='/path/to/model.pkl' num_replicas=5\n\n" + "If passing a YAML config, existing applications with no code changes will not " + "be updated.\n\n" + "By default, this will block and stream logs to the console. If you " + "Ctrl-C the command, it will shut down Serve on the cluster." + ), +) +@click.argument("config_or_import_path") +@click.argument("arguments", nargs=-1, required=False) +@click.option( + "--runtime-env", + type=str, + default=None, + required=False, + help="Path to a local YAML file containing a runtime_env definition. " + "This will be passed to ray.init() as the default for deployments.", +) +@click.option( + "--runtime-env-json", + type=str, + default=None, + required=False, + help="JSON-serialized runtime_env dictionary. This will be passed to " + "ray.init() as the default for deployments.", +) +@click.option( + "--working-dir", + type=str, + default=None, + required=False, + help=( + "Directory containing files that your application(s) will run in. Can be a " + "local directory or a remote URI to a .zip file (S3, GS, HTTP). " + "This overrides the working_dir in --runtime-env if both are " + "specified. This will be passed to ray.init() as the default for " + "deployments." + ), +) +@click.option( + "--app-dir", + "-d", + default=".", + type=str, + help=APP_DIR_HELP_STR, +) +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_ADDRESS", None), + required=False, + type=str, + help=RAY_INIT_ADDRESS_HELP_STR, +) +@click.option( + "--blocking/--non-blocking", + default=True, + help=( + "Whether or not this command should be blocking. If blocking, it " + "will loop and log status until Ctrl-C'd, then clean up the app." + ), +) +@click.option( + "--reload", + "-r", + is_flag=True, + help=( + "This is an experimental feature - Listens for changes to files in the working directory, " + "--working-dir or the working_dir in the --runtime-env, and automatically redeploys " + "the application. This will block until Ctrl-C'd, then clean up the " + "app." + ), +) +@click.option( + "--route-prefix", + required=False, + type=str, + default="/", + help=( + "Route prefix for the application. This should only be used " + "when running an application specified by import path and " + "will be ignored if running a config file." + ), +) +@click.option( + "--name", + required=False, + default=SERVE_DEFAULT_APP_NAME, + type=str, + help=( + "Name of the application. This should only be used " + "when running an application specified by import path and " + "will be ignored if running a config file." + ), +) +def run( + config_or_import_path: str, + arguments: Tuple[str], + runtime_env: str, + runtime_env_json: str, + working_dir: str, + app_dir: str, + address: str, + blocking: bool, + reload: bool, + route_prefix: str, + name: str, +): + sys.path.insert(0, app_dir) + args_dict = convert_args_to_dict(arguments) + final_runtime_env = parse_runtime_env_args( + runtime_env=runtime_env, + runtime_env_json=runtime_env_json, + working_dir=working_dir, + ) + + if pathlib.Path(config_or_import_path).is_file(): + if len(args_dict) > 0: + cli_logger.warning( + "Application arguments are ignored when running a config file." + ) + + is_config = True + config_path = config_or_import_path + cli_logger.print(f"Running config file: '{config_path}'.") + + with open(config_path, "r") as config_file: + config_dict = yaml.safe_load(config_file) + + config = ServeDeploySchema.parse_obj(config_dict) + + else: + is_config = False + import_path = config_or_import_path + cli_logger.print(f"Running import path: '{import_path}'.") + app = _private_api.call_user_app_builder_with_args_if_necessary( + import_attr(import_path), args_dict + ) + + # Only initialize ray if it has not happened yet. + if not ray.is_initialized(): + # Setting the runtime_env here will set defaults for the deployments. + ray.init( + address=address, namespace=SERVE_NAMESPACE, runtime_env=final_runtime_env + ) + elif ( + address is not None + and address != "auto" + and address != ray.get_runtime_context().gcs_address + ): + # Warning users the address they passed is different from the existing ray + # instance. + ray_address = ray.get_runtime_context().gcs_address + cli_logger.warning( + "An address was passed to `serve run` but the imported module also " + f"connected to Ray at a different address: '{ray_address}'. You do not " + "need to call `ray.init` in your code when using `serve run`." + ) + + http_options = {"location": "EveryNode"} + grpc_options = gRPCOptions() + # Merge http_options and grpc_options with the ones on ServeDeploySchema. + if is_config and isinstance(config, ServeDeploySchema): + config_http_options = config.http_options.dict() + http_options = {**config_http_options, **http_options} + grpc_options = gRPCOptions(**config.grpc_options.dict()) + + client = _private_api.serve_start( + http_options=http_options, + grpc_options=grpc_options, + ) + + try: + if is_config: + client.deploy_apps(config, _blocking=False) + cli_logger.success("Submitted deploy config successfully.") + if blocking: + while True: + # Block, letting Ray print logs to the terminal. + time.sleep(10) + else: + # This should not block if reload is true so the watchfiles can be triggered + should_block = blocking and not reload + serve.run(app, blocking=should_block, name=name, route_prefix=route_prefix) + + if reload: + if not blocking: + raise click.ClickException( + "The --non-blocking option conflicts with the --reload option." + ) + if working_dir: + watch_dir = working_dir + else: + watch_dir = app_dir + + for changes in watchfiles.watch( + watch_dir, + rust_timeout=10000, + yield_on_timeout=True, + ): + if changes: + try: + # The module needs to be reloaded with `importlib` in order to + # pick up any changes. + app = _private_api.call_user_app_builder_with_args_if_necessary( + import_attr(import_path, reload_module=True), args_dict + ) + serve.run( + target=app, + blocking=False, + name=name, + route_prefix=route_prefix, + ) + except Exception: + traceback.print_exc() + cli_logger.error( + "Deploying the latest version of the application failed." + ) + + except KeyboardInterrupt: + cli_logger.info("Got KeyboardInterrupt, shutting down...") + serve.shutdown() + sys.exit() + + except Exception: + traceback.print_exc() + cli_logger.error( + "Received unexpected error, see console logs for more details. Shutting " + "down..." + ) + serve.shutdown() + sys.exit() + + +@cli.command(help="Gets the current configs of Serve applications on the cluster.") +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_DASHBOARD_ADDRESS", "http://localhost:8265"), + required=False, + type=str, + help=RAY_DASHBOARD_ADDRESS_HELP_STR, +) +@click.option( + "--name", + "-n", + required=False, + type=str, + help=( + "Name of an application. Only applies to multi-application mode. If set, this " + "will only fetch the config for the specified application." + ), +) +def config(address: str, name: Optional[str]): + warn_if_agent_address_set() + + serve_details = ServeInstanceDetails( + **ServeSubmissionClient(address).get_serve_details() + ) + + # Fetch app configs for all live applications on the cluster + if name is None: + print( + "\n---\n\n".join( + yaml.safe_dump( + app.deployed_app_config.dict(exclude_unset=True), + sort_keys=False, + ) + for app in serve_details.applications.values() + if app.deployed_app_config is not None + ), + end="", + ) + # Fetch a specific app config by name. + else: + app = serve_details.applications.get(name) + if app is None or app.deployed_app_config is None: + print(f'No config has been deployed for application "{name}".') + else: + config = app.deployed_app_config.dict(exclude_unset=True) + print(yaml.safe_dump(config, sort_keys=False), end="") + + +@cli.command( + short_help="Get the current status of all Serve applications on the cluster.", + help=( + "Prints status information about all applications on the cluster.\n\n" + "An application may be:\n\n" + "- NOT_STARTED: the application does not exist.\n" + "- DEPLOYING: the deployments in the application are still deploying and " + "haven't reached the target number of replicas.\n" + "- RUNNING: all deployments are healthy.\n" + "- DEPLOY_FAILED: the application failed to deploy or reach a running state.\n" + "- DELETING: the application is being deleted, and the deployments in the " + "application are being teared down.\n\n" + "The deployments within each application may be:\n\n" + "- HEALTHY: all replicas are acting normally and passing their health checks.\n" + "- UNHEALTHY: at least one replica is not acting normally and may not be " + "passing its health check.\n" + "- UPDATING: the deployment is updating." + ), +) +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_DASHBOARD_ADDRESS", "http://localhost:8265"), + required=False, + type=str, + help=RAY_DASHBOARD_ADDRESS_HELP_STR, +) +@click.option( + "--name", + "-n", + default=None, + required=False, + type=str, + help=( + "Name of an application. If set, this will display only the status of the " + "specified application." + ), +) +def status(address: str, name: Optional[str]): + warn_if_agent_address_set() + + serve_details = ServeInstanceDetails( + **ServeSubmissionClient(address).get_serve_details() + ) + status = asdict(serve_details._get_status()) + + # Ensure multi-line strings in app_status is dumped/printed correctly + yaml.SafeDumper.add_representer(str, str_presenter) + + if name is None: + print( + yaml.safe_dump( + # Ensure exception traceback in app_status are printed correctly + process_dict_for_yaml_dump(status), + default_flow_style=False, + sort_keys=False, + ), + end="", + ) + else: + if name not in serve_details.applications: + cli_logger.error(f'Application "{name}" does not exist.') + else: + print( + yaml.safe_dump( + # Ensure exception tracebacks in app_status are printed correctly + process_dict_for_yaml_dump(status["applications"][name]), + default_flow_style=False, + sort_keys=False, + ), + end="", + ) + + +@cli.command( + help="Shuts down Serve on the cluster, deleting all applications.", +) +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_DASHBOARD_ADDRESS", "http://localhost:8265"), + required=False, + type=str, + help=RAY_DASHBOARD_ADDRESS_HELP_STR, +) +@click.option("--yes", "-y", is_flag=True, help="Bypass confirmation prompt.") +def shutdown(address: str, yes: bool): + warn_if_agent_address_set() + + # check if the address is a valid Ray address + try: + # see what applications are deployed on the cluster + serve_details = ServeInstanceDetails( + **ServeSubmissionClient(address).get_serve_details() + ) + if serve_details.controller_info.node_id is None: + cli_logger.warning( + f"No Serve instance found running on the cluster at {address}." + ) + return + except Exception as e: + cli_logger.error( + f"Unable to shutdown Serve on the cluster at address {address}: {e}" + ) + return + + if not yes: + click.confirm( + f"This will shut down Serve on the cluster at address " + f'"{address}" and delete all applications there. Do you ' + "want to continue?", + abort=True, + ) + + ServeSubmissionClient(address).delete_applications() + + cli_logger.success( + "Sent shutdown request; applications will be deleted asynchronously." + ) + + +@cli.command( + short_help="Generate a config file for the specified applications.", + help=( + "Imports the applications at IMPORT_PATHS and generates a structured, multi-" + "application config for them. If the flag --single-app is set, accepts one " + "application and generates a single-application config. Config " + "outputted from this command can be used by `serve deploy` or the REST API. " + ), +) +@click.argument("import_paths", nargs=-1, required=True) +@click.option( + "--app-dir", + "-d", + default=".", + type=str, + help=APP_DIR_HELP_STR, +) +@click.option( + "--output-path", + "-o", + default=None, + type=str, + help=( + "Local path where the output config will be written in YAML format. " + "If not provided, the config will be printed to STDOUT." + ), +) +@click.option( + "--grpc-servicer-functions", + default=[], + required=False, + multiple=True, + help="Servicer function for adding the method handler to the gRPC server. " + "Defaults to an empty list and no gRPC server is started.", +) +def build( + import_paths: Tuple[str], + app_dir: str, + output_path: Optional[str], + grpc_servicer_functions: List[str], +): + sys.path.insert(0, app_dir) + + def build_app_config(import_path: str, name: str = None): + app: Application = import_attr(import_path) + if not isinstance(app, Application): + raise TypeError( + f"Expected '{import_path}' to be an Application but got {type(app)}." + ) + + built_app: BuiltApplication = build_app(app, name=name) + schema = ServeApplicationSchema( + name=name, + route_prefix="/" if len(import_paths) == 1 else f"/{name}", + import_path=import_path, + runtime_env={}, + deployments=[deployment_to_schema(d) for d in built_app.deployments], + ) + + return schema.dict(exclude_unset=True) + + config_str = ( + "# This file was generated using the `serve build` command " + f"on Ray v{ray.__version__}.\n\n" + ) + + app_configs = [] + for app_index, import_path in enumerate(import_paths): + app_configs.append(build_app_config(import_path, name=f"app{app_index + 1}")) + + deploy_config = { + "proxy_location": "EveryNode", + "http_options": { + "host": "0.0.0.0", + "port": 8000, + }, + "grpc_options": { + "port": DEFAULT_GRPC_PORT, + "grpc_servicer_functions": grpc_servicer_functions, + }, + "logging_config": LoggingConfig().dict(), + "applications": app_configs, + } + + # Parse + validate the set of application configs + ServeDeploySchema.parse_obj(deploy_config) + + config_str += yaml.dump( + deploy_config, + Dumper=ServeDeploySchemaDumper, + default_flow_style=False, + sort_keys=False, + ) + cli_logger.info( + "The auto-generated application names default to `app1`, `app2`, ... etc. " + "Rename as necessary.\n", + ) + + # Ensure file ends with only one newline + config_str = config_str.rstrip("\n") + "\n" + + with open(output_path, "w") if output_path else sys.stdout as f: + f.write(config_str) + + +class ServeDeploySchemaDumper(yaml.SafeDumper): + """YAML dumper object with custom formatting for ServeDeploySchema. + + Reformat config to follow this spacing: + --------------------------------------- + + host: 0.0.0.0 + + port: 8000 + + applications: + + - name: app1 + + import_path: app1.path + + runtime_env: {} + + deployments: + + - name: deployment1 + ... + + - name: deployment2 + ... + """ + + def write_line_break(self, data=None): + # https://github.com/yaml/pyyaml/issues/127#issuecomment-525800484 + super().write_line_break(data) + + # Indents must be at most 4 to ensure that only the top 4 levels of + # the config file have line breaks between them. + if len(self.indents) <= 4: + super().write_line_break() diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/METADATA b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..a1b5c57543005b310ac2efb02243a6b6ab6d8932 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/METADATA @@ -0,0 +1,441 @@ +Metadata-Version: 2.1 +Name: colorama +Version: 0.4.6 +Summary: Cross-platform colored terminal text. +Project-URL: Homepage, https://github.com/tartley/colorama +Author-email: Jonathan Hartley +License-File: LICENSE.txt +Keywords: ansi,color,colour,crossplatform,terminal,text,windows,xplatform +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Terminals +Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7 +Description-Content-Type: text/x-rst + +.. image:: https://img.shields.io/pypi/v/colorama.svg + :target: https://pypi.org/project/colorama/ + :alt: Latest Version + +.. image:: https://img.shields.io/pypi/pyversions/colorama.svg + :target: https://pypi.org/project/colorama/ + :alt: Supported Python versions + +.. image:: https://github.com/tartley/colorama/actions/workflows/test.yml/badge.svg + :target: https://github.com/tartley/colorama/actions/workflows/test.yml + :alt: Build Status + +Colorama +======== + +Makes ANSI escape character sequences (for producing colored terminal text and +cursor positioning) work under MS Windows. + +.. |donate| image:: https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif + :target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=2MZ9D2GMLYCUJ&item_name=Colorama¤cy_code=USD + :alt: Donate with Paypal + +`PyPI for releases `_ | +`Github for source `_ | +`Colorama for enterprise on Tidelift `_ + +If you find Colorama useful, please |donate| to the authors. Thank you! + +Installation +------------ + +Tested on CPython 2.7, 3.7, 3.8, 3.9 and 3.10 and Pypy 2.7 and 3.8. + +No requirements other than the standard library. + +.. code-block:: bash + + pip install colorama + # or + conda install -c anaconda colorama + +Description +----------- + +ANSI escape character sequences have long been used to produce colored terminal +text and cursor positioning on Unix and Macs. Colorama makes this work on +Windows, too, by wrapping ``stdout``, stripping ANSI sequences it finds (which +would appear as gobbledygook in the output), and converting them into the +appropriate win32 calls to modify the state of the terminal. On other platforms, +Colorama does nothing. + +This has the upshot of providing a simple cross-platform API for printing +colored terminal text from Python, and has the happy side-effect that existing +applications or libraries which use ANSI sequences to produce colored output on +Linux or Macs can now also work on Windows, simply by calling +``colorama.just_fix_windows_console()`` (since v0.4.6) or ``colorama.init()`` +(all versions, but may have other side-effects – see below). + +An alternative approach is to install ``ansi.sys`` on Windows machines, which +provides the same behaviour for all applications running in terminals. Colorama +is intended for situations where that isn't easy (e.g., maybe your app doesn't +have an installer.) + +Demo scripts in the source code repository print some colored text using +ANSI sequences. Compare their output under Gnome-terminal's built in ANSI +handling, versus on Windows Command-Prompt using Colorama: + +.. image:: https://github.com/tartley/colorama/raw/master/screenshots/ubuntu-demo.png + :width: 661 + :height: 357 + :alt: ANSI sequences on Ubuntu under gnome-terminal. + +.. image:: https://github.com/tartley/colorama/raw/master/screenshots/windows-demo.png + :width: 668 + :height: 325 + :alt: Same ANSI sequences on Windows, using Colorama. + +These screenshots show that, on Windows, Colorama does not support ANSI 'dim +text'; it looks the same as 'normal text'. + +Usage +----- + +Initialisation +.............. + +If the only thing you want from Colorama is to get ANSI escapes to work on +Windows, then run: + +.. code-block:: python + + from colorama import just_fix_windows_console + just_fix_windows_console() + +If you're on a recent version of Windows 10 or better, and your stdout/stderr +are pointing to a Windows console, then this will flip the magic configuration +switch to enable Windows' built-in ANSI support. + +If you're on an older version of Windows, and your stdout/stderr are pointing to +a Windows console, then this will wrap ``sys.stdout`` and/or ``sys.stderr`` in a +magic file object that intercepts ANSI escape sequences and issues the +appropriate Win32 calls to emulate them. + +In all other circumstances, it does nothing whatsoever. Basically the idea is +that this makes Windows act like Unix with respect to ANSI escape handling. + +It's safe to call this function multiple times. It's safe to call this function +on non-Windows platforms, but it won't do anything. It's safe to call this +function when one or both of your stdout/stderr are redirected to a file – it +won't do anything to those streams. + +Alternatively, you can use the older interface with more features (but also more +potential footguns): + +.. code-block:: python + + from colorama import init + init() + +This does the same thing as ``just_fix_windows_console``, except for the +following differences: + +- It's not safe to call ``init`` multiple times; you can end up with multiple + layers of wrapping and broken ANSI support. + +- Colorama will apply a heuristic to guess whether stdout/stderr support ANSI, + and if it thinks they don't, then it will wrap ``sys.stdout`` and + ``sys.stderr`` in a magic file object that strips out ANSI escape sequences + before printing them. This happens on all platforms, and can be convenient if + you want to write your code to emit ANSI escape sequences unconditionally, and + let Colorama decide whether they should actually be output. But note that + Colorama's heuristic is not particularly clever. + +- ``init`` also accepts explicit keyword args to enable/disable various + functionality – see below. + +To stop using Colorama before your program exits, simply call ``deinit()``. +This will restore ``stdout`` and ``stderr`` to their original values, so that +Colorama is disabled. To resume using Colorama again, call ``reinit()``; it is +cheaper than calling ``init()`` again (but does the same thing). + +Most users should depend on ``colorama >= 0.4.6``, and use +``just_fix_windows_console``. The old ``init`` interface will be supported +indefinitely for backwards compatibility, but we don't plan to fix any issues +with it, also for backwards compatibility. + +Colored Output +.............. + +Cross-platform printing of colored text can then be done using Colorama's +constant shorthand for ANSI escape sequences. These are deliberately +rudimentary, see below. + +.. code-block:: python + + from colorama import Fore, Back, Style + print(Fore.RED + 'some red text') + print(Back.GREEN + 'and with a green background') + print(Style.DIM + 'and in dim text') + print(Style.RESET_ALL) + print('back to normal now') + +...or simply by manually printing ANSI sequences from your own code: + +.. code-block:: python + + print('\033[31m' + 'some red text') + print('\033[39m') # and reset to default color + +...or, Colorama can be used in conjunction with existing ANSI libraries +such as the venerable `Termcolor `_ +the fabulous `Blessings `_, +or the incredible `_Rich `_. + +If you wish Colorama's Fore, Back and Style constants were more capable, +then consider using one of the above highly capable libraries to generate +colors, etc, and use Colorama just for its primary purpose: to convert +those ANSI sequences to also work on Windows: + +SIMILARLY, do not send PRs adding the generation of new ANSI types to Colorama. +We are only interested in converting ANSI codes to win32 API calls, not +shortcuts like the above to generate ANSI characters. + +.. code-block:: python + + from colorama import just_fix_windows_console + from termcolor import colored + + # use Colorama to make Termcolor work on Windows too + just_fix_windows_console() + + # then use Termcolor for all colored text output + print(colored('Hello, World!', 'green', 'on_red')) + +Available formatting constants are:: + + Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. + Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. + Style: DIM, NORMAL, BRIGHT, RESET_ALL + +``Style.RESET_ALL`` resets foreground, background, and brightness. Colorama will +perform this reset automatically on program exit. + +These are fairly well supported, but not part of the standard:: + + Fore: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX + Back: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX + +Cursor Positioning +.................. + +ANSI codes to reposition the cursor are supported. See ``demos/demo06.py`` for +an example of how to generate them. + +Init Keyword Args +................. + +``init()`` accepts some ``**kwargs`` to override default behaviour. + +init(autoreset=False): + If you find yourself repeatedly sending reset sequences to turn off color + changes at the end of every print, then ``init(autoreset=True)`` will + automate that: + + .. code-block:: python + + from colorama import init + init(autoreset=True) + print(Fore.RED + 'some red text') + print('automatically back to default color again') + +init(strip=None): + Pass ``True`` or ``False`` to override whether ANSI codes should be + stripped from the output. The default behaviour is to strip if on Windows + or if output is redirected (not a tty). + +init(convert=None): + Pass ``True`` or ``False`` to override whether to convert ANSI codes in the + output into win32 calls. The default behaviour is to convert if on Windows + and output is to a tty (terminal). + +init(wrap=True): + On Windows, Colorama works by replacing ``sys.stdout`` and ``sys.stderr`` + with proxy objects, which override the ``.write()`` method to do their work. + If this wrapping causes you problems, then this can be disabled by passing + ``init(wrap=False)``. The default behaviour is to wrap if ``autoreset`` or + ``strip`` or ``convert`` are True. + + When wrapping is disabled, colored printing on non-Windows platforms will + continue to work as normal. To do cross-platform colored output, you can + use Colorama's ``AnsiToWin32`` proxy directly: + + .. code-block:: python + + import sys + from colorama import init, AnsiToWin32 + init(wrap=False) + stream = AnsiToWin32(sys.stderr).stream + + # Python 2 + print >>stream, Fore.BLUE + 'blue text on stderr' + + # Python 3 + print(Fore.BLUE + 'blue text on stderr', file=stream) + +Recognised ANSI Sequences +......................... + +ANSI sequences generally take the form:: + + ESC [ ; ... + +Where ```` is an integer, and ```` is a single letter. Zero or +more params are passed to a ````. If no params are passed, it is +generally synonymous with passing a single zero. No spaces exist in the +sequence; they have been inserted here simply to read more easily. + +The only ANSI sequences that Colorama converts into win32 calls are:: + + ESC [ 0 m # reset all (colors and brightness) + ESC [ 1 m # bright + ESC [ 2 m # dim (looks same as normal brightness) + ESC [ 22 m # normal brightness + + # FOREGROUND: + ESC [ 30 m # black + ESC [ 31 m # red + ESC [ 32 m # green + ESC [ 33 m # yellow + ESC [ 34 m # blue + ESC [ 35 m # magenta + ESC [ 36 m # cyan + ESC [ 37 m # white + ESC [ 39 m # reset + + # BACKGROUND + ESC [ 40 m # black + ESC [ 41 m # red + ESC [ 42 m # green + ESC [ 43 m # yellow + ESC [ 44 m # blue + ESC [ 45 m # magenta + ESC [ 46 m # cyan + ESC [ 47 m # white + ESC [ 49 m # reset + + # cursor positioning + ESC [ y;x H # position cursor at x across, y down + ESC [ y;x f # position cursor at x across, y down + ESC [ n A # move cursor n lines up + ESC [ n B # move cursor n lines down + ESC [ n C # move cursor n characters forward + ESC [ n D # move cursor n characters backward + + # clear the screen + ESC [ mode J # clear the screen + + # clear the line + ESC [ mode K # clear the line + +Multiple numeric params to the ``'m'`` command can be combined into a single +sequence:: + + ESC [ 36 ; 45 ; 1 m # bright cyan text on magenta background + +All other ANSI sequences of the form ``ESC [ ; ... `` +are silently stripped from the output on Windows. + +Any other form of ANSI sequence, such as single-character codes or alternative +initial characters, are not recognised or stripped. It would be cool to add +them though. Let me know if it would be useful for you, via the Issues on +GitHub. + +Status & Known Problems +----------------------- + +I've personally only tested it on Windows XP (CMD, Console2), Ubuntu +(gnome-terminal, xterm), and OS X. + +Some valid ANSI sequences aren't recognised. + +If you're hacking on the code, see `README-hacking.md`_. ESPECIALLY, see the +explanation there of why we do not want PRs that allow Colorama to generate new +types of ANSI codes. + +See outstanding issues and wish-list: +https://github.com/tartley/colorama/issues + +If anything doesn't work for you, or doesn't do what you expected or hoped for, +I'd love to hear about it on that issues list, would be delighted by patches, +and would be happy to grant commit access to anyone who submits a working patch +or two. + +.. _README-hacking.md: README-hacking.md + +License +------- + +Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see +LICENSE file. + +Professional support +-------------------- + +.. |tideliftlogo| image:: https://cdn2.hubspot.net/hubfs/4008838/website/logos/logos_for_download/Tidelift_primary-shorthand-logo.png + :alt: Tidelift + :target: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme + +.. list-table:: + :widths: 10 100 + + * - |tideliftlogo| + - Professional support for colorama is available as part of the + `Tidelift Subscription`_. + Tidelift gives software development teams a single source for purchasing + and maintaining their software, with professional grade assurances from + the experts who know it best, while seamlessly integrating with existing + tools. + +.. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme + +Thanks +------ + +See the CHANGELOG for more thanks! + +* Marc Schlaich (schlamar) for a ``setup.py`` fix for Python2.5. +* Marc Abramowitz, reported & fixed a crash on exit with closed ``stdout``, + providing a solution to issue #7's setuptools/distutils debate, + and other fixes. +* User 'eryksun', for guidance on correctly instantiating ``ctypes.windll``. +* Matthew McCormick for politely pointing out a longstanding crash on non-Win. +* Ben Hoyt, for a magnificent fix under 64-bit Windows. +* Jesse at Empty Square for submitting a fix for examples in the README. +* User 'jamessp', an observant documentation fix for cursor positioning. +* User 'vaal1239', Dave Mckee & Lackner Kristof for a tiny but much-needed Win7 + fix. +* Julien Stuyck, for wisely suggesting Python3 compatible updates to README. +* Daniel Griffith for multiple fabulous patches. +* Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty + output. +* Roger Binns, for many suggestions, valuable feedback, & bug reports. +* Tim Golden for thought and much appreciated feedback on the initial idea. +* User 'Zearin' for updates to the README file. +* John Szakmeister for adding support for light colors +* Charles Merriam for adding documentation to demos +* Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes +* Florian Bruhin for a fix when stdout or stderr are None +* Thomas Weininger for fixing ValueError on Windows +* Remi Rampin for better Github integration and fixes to the README file +* Simeon Visser for closing a file handle using 'with' and updating classifiers + to include Python 3.3 and 3.4 +* Andy Neff for fixing RESET of LIGHT_EX colors. +* Jonathan Hartley for the initial idea and implementation. diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/RECORD b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..a516050a5392527c9a4b5e413bd7a6183a3541b8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/RECORD @@ -0,0 +1,32 @@ +colorama-0.4.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +colorama-0.4.6.dist-info/METADATA,sha256=e67SnrUMOym9sz_4TjF3vxvAV4T3aF7NyqRHHH3YEMw,17158 +colorama-0.4.6.dist-info/RECORD,, +colorama-0.4.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +colorama-0.4.6.dist-info/WHEEL,sha256=cdcF4Fbd0FPtw2EMIOwH-3rSOTUdTCeOSXRMD1iLUb8,105 +colorama-0.4.6.dist-info/licenses/LICENSE.txt,sha256=ysNcAmhuXQSlpxQL-zs25zrtSWZW6JEQLkKIhteTAxg,1491 +colorama/__init__.py,sha256=wePQA4U20tKgYARySLEC047ucNX-g8pRLpYBuiHlLb8,266 +colorama/__pycache__/__init__.cpython-310.pyc,, +colorama/__pycache__/ansi.cpython-310.pyc,, +colorama/__pycache__/ansitowin32.cpython-310.pyc,, +colorama/__pycache__/initialise.cpython-310.pyc,, +colorama/__pycache__/win32.cpython-310.pyc,, +colorama/__pycache__/winterm.cpython-310.pyc,, +colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522 +colorama/ansitowin32.py,sha256=vPNYa3OZbxjbuFyaVo0Tmhmy1FZ1lKMWCnT7odXpItk,11128 +colorama/initialise.py,sha256=-hIny86ClXo39ixh5iSCfUIa2f_h_bgKRDW7gqs-KLU,3325 +colorama/tests/__init__.py,sha256=MkgPAEzGQd-Rq0w0PZXSX2LadRWhUECcisJY8lSrm4Q,75 +colorama/tests/__pycache__/__init__.cpython-310.pyc,, +colorama/tests/__pycache__/ansi_test.cpython-310.pyc,, +colorama/tests/__pycache__/ansitowin32_test.cpython-310.pyc,, +colorama/tests/__pycache__/initialise_test.cpython-310.pyc,, +colorama/tests/__pycache__/isatty_test.cpython-310.pyc,, +colorama/tests/__pycache__/utils.cpython-310.pyc,, +colorama/tests/__pycache__/winterm_test.cpython-310.pyc,, +colorama/tests/ansi_test.py,sha256=FeViDrUINIZcr505PAxvU4AjXz1asEiALs9GXMhwRaE,2839 +colorama/tests/ansitowin32_test.py,sha256=RN7AIhMJ5EqDsYaCjVo-o4u8JzDD4ukJbmevWKS70rY,10678 +colorama/tests/initialise_test.py,sha256=BbPy-XfyHwJ6zKozuQOvNvQZzsx9vdb_0bYXn7hsBTc,6741 +colorama/tests/isatty_test.py,sha256=Pg26LRpv0yQDB5Ac-sxgVXG7hsA1NYvapFgApZfYzZg,1866 +colorama/tests/utils.py,sha256=1IIRylG39z5-dzq09R_ngufxyPZxgldNbrxKxUGwGKE,1079 +colorama/tests/winterm_test.py,sha256=qoWFPEjym5gm2RuMwpf3pOis3a5r_PJZFCzK254JL8A,3709 +colorama/win32.py,sha256=YQOKwMTwtGBbsY4dL5HYTvwTeP9wIQra5MvPNddpxZs,6181 +colorama/winterm.py,sha256=XCQFDHjPi6AHYNdZwy0tA02H-Jh48Jp-HvCjeLeLp3U,7134 diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/REQUESTED b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/WHEEL b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d79189fda3251187de18c3998f23ae6fec11b20f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.11.1 +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/licenses/LICENSE.txt b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..3105888ec149d10cad51c11d332779e94b548661 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama-0.4.6.dist-info/licenses/LICENSE.txt @@ -0,0 +1,27 @@ +Copyright (c) 2010 Jonathan Hartley +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holders, nor those of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__init__.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..383101cdb38706c305449674044e9288b92b7d75 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__init__.py @@ -0,0 +1,7 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +from .initialise import init, deinit, reinit, colorama_text, just_fix_windows_console +from .ansi import Fore, Back, Style, Cursor +from .ansitowin32 import AnsiToWin32 + +__version__ = '0.4.6' + diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ccc717f078c2691943c7cb071c27ca27e8cb696 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/ansi.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/ansi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52be471195509787f12622ac63b11d1ee4ff4322 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/ansi.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/ansitowin32.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/ansitowin32.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72048b9b9c2e59ab2fb620201bbf4e2b0eac752d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/ansitowin32.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/initialise.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/initialise.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec8cb4dd798a6509a93069784747f2bc104b09eb Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/initialise.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/win32.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/win32.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e7974890ca5c460716ac97c49599982feb3b3c0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/win32.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/winterm.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/winterm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45f8e9a214df93600b704cef17847f63514f760d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/__pycache__/winterm.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/ansi.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/ansi.py new file mode 100644 index 0000000000000000000000000000000000000000..11ec695ff79627463a0282d25079527562de9e42 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/ansi.py @@ -0,0 +1,102 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +''' +This module generates ANSI character codes to printing colors to terminals. +See: http://en.wikipedia.org/wiki/ANSI_escape_code +''' + +CSI = '\033[' +OSC = '\033]' +BEL = '\a' + + +def code_to_chars(code): + return CSI + str(code) + 'm' + +def set_title(title): + return OSC + '2;' + title + BEL + +def clear_screen(mode=2): + return CSI + str(mode) + 'J' + +def clear_line(mode=2): + return CSI + str(mode) + 'K' + + +class AnsiCodes(object): + def __init__(self): + # the subclasses declare class attributes which are numbers. + # Upon instantiation we define instance attributes, which are the same + # as the class attributes but wrapped with the ANSI escape sequence + for name in dir(self): + if not name.startswith('_'): + value = getattr(self, name) + setattr(self, name, code_to_chars(value)) + + +class AnsiCursor(object): + def UP(self, n=1): + return CSI + str(n) + 'A' + def DOWN(self, n=1): + return CSI + str(n) + 'B' + def FORWARD(self, n=1): + return CSI + str(n) + 'C' + def BACK(self, n=1): + return CSI + str(n) + 'D' + def POS(self, x=1, y=1): + return CSI + str(y) + ';' + str(x) + 'H' + + +class AnsiFore(AnsiCodes): + BLACK = 30 + RED = 31 + GREEN = 32 + YELLOW = 33 + BLUE = 34 + MAGENTA = 35 + CYAN = 36 + WHITE = 37 + RESET = 39 + + # These are fairly well supported, but not part of the standard. + LIGHTBLACK_EX = 90 + LIGHTRED_EX = 91 + LIGHTGREEN_EX = 92 + LIGHTYELLOW_EX = 93 + LIGHTBLUE_EX = 94 + LIGHTMAGENTA_EX = 95 + LIGHTCYAN_EX = 96 + LIGHTWHITE_EX = 97 + + +class AnsiBack(AnsiCodes): + BLACK = 40 + RED = 41 + GREEN = 42 + YELLOW = 43 + BLUE = 44 + MAGENTA = 45 + CYAN = 46 + WHITE = 47 + RESET = 49 + + # These are fairly well supported, but not part of the standard. + LIGHTBLACK_EX = 100 + LIGHTRED_EX = 101 + LIGHTGREEN_EX = 102 + LIGHTYELLOW_EX = 103 + LIGHTBLUE_EX = 104 + LIGHTMAGENTA_EX = 105 + LIGHTCYAN_EX = 106 + LIGHTWHITE_EX = 107 + + +class AnsiStyle(AnsiCodes): + BRIGHT = 1 + DIM = 2 + NORMAL = 22 + RESET_ALL = 0 + +Fore = AnsiFore() +Back = AnsiBack() +Style = AnsiStyle() +Cursor = AnsiCursor() diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/ansitowin32.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/ansitowin32.py new file mode 100644 index 0000000000000000000000000000000000000000..abf209e60c7c4a9b1ae57452e36b383969848c2e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/ansitowin32.py @@ -0,0 +1,277 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import re +import sys +import os + +from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL +from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle +from .win32 import windll, winapi_test + + +winterm = None +if windll is not None: + winterm = WinTerm() + + +class StreamWrapper(object): + ''' + Wraps a stream (such as stdout), acting as a transparent proxy for all + attribute access apart from method 'write()', which is delegated to our + Converter instance. + ''' + def __init__(self, wrapped, converter): + # double-underscore everything to prevent clashes with names of + # attributes on the wrapped stream object. + self.__wrapped = wrapped + self.__convertor = converter + + def __getattr__(self, name): + return getattr(self.__wrapped, name) + + def __enter__(self, *args, **kwargs): + # special method lookup bypasses __getattr__/__getattribute__, see + # https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit + # thus, contextlib magic methods are not proxied via __getattr__ + return self.__wrapped.__enter__(*args, **kwargs) + + def __exit__(self, *args, **kwargs): + return self.__wrapped.__exit__(*args, **kwargs) + + def __setstate__(self, state): + self.__dict__ = state + + def __getstate__(self): + return self.__dict__ + + def write(self, text): + self.__convertor.write(text) + + def isatty(self): + stream = self.__wrapped + if 'PYCHARM_HOSTED' in os.environ: + if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__): + return True + try: + stream_isatty = stream.isatty + except AttributeError: + return False + else: + return stream_isatty() + + @property + def closed(self): + stream = self.__wrapped + try: + return stream.closed + # AttributeError in the case that the stream doesn't support being closed + # ValueError for the case that the stream has already been detached when atexit runs + except (AttributeError, ValueError): + return True + + +class AnsiToWin32(object): + ''' + Implements a 'write()' method which, on Windows, will strip ANSI character + sequences from the text, and if outputting to a tty, will convert them into + win32 function calls. + ''' + ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer + ANSI_OSC_RE = re.compile('\001?\033\\]([^\a]*)(\a)\002?') # Operating System Command + + def __init__(self, wrapped, convert=None, strip=None, autoreset=False): + # The wrapped stream (normally sys.stdout or sys.stderr) + self.wrapped = wrapped + + # should we reset colors to defaults after every .write() + self.autoreset = autoreset + + # create the proxy wrapping our output stream + self.stream = StreamWrapper(wrapped, self) + + on_windows = os.name == 'nt' + # We test if the WinAPI works, because even if we are on Windows + # we may be using a terminal that doesn't support the WinAPI + # (e.g. Cygwin Terminal). In this case it's up to the terminal + # to support the ANSI codes. + conversion_supported = on_windows and winapi_test() + try: + fd = wrapped.fileno() + except Exception: + fd = -1 + system_has_native_ansi = not on_windows or enable_vt_processing(fd) + have_tty = not self.stream.closed and self.stream.isatty() + need_conversion = conversion_supported and not system_has_native_ansi + + # should we strip ANSI sequences from our output? + if strip is None: + strip = need_conversion or not have_tty + self.strip = strip + + # should we should convert ANSI sequences into win32 calls? + if convert is None: + convert = need_conversion and have_tty + self.convert = convert + + # dict of ansi codes to win32 functions and parameters + self.win32_calls = self.get_win32_calls() + + # are we wrapping stderr? + self.on_stderr = self.wrapped is sys.stderr + + def should_wrap(self): + ''' + True if this class is actually needed. If false, then the output + stream will not be affected, nor will win32 calls be issued, so + wrapping stdout is not actually required. This will generally be + False on non-Windows platforms, unless optional functionality like + autoreset has been requested using kwargs to init() + ''' + return self.convert or self.strip or self.autoreset + + def get_win32_calls(self): + if self.convert and winterm: + return { + AnsiStyle.RESET_ALL: (winterm.reset_all, ), + AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT), + AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL), + AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL), + AnsiFore.BLACK: (winterm.fore, WinColor.BLACK), + AnsiFore.RED: (winterm.fore, WinColor.RED), + AnsiFore.GREEN: (winterm.fore, WinColor.GREEN), + AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW), + AnsiFore.BLUE: (winterm.fore, WinColor.BLUE), + AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA), + AnsiFore.CYAN: (winterm.fore, WinColor.CYAN), + AnsiFore.WHITE: (winterm.fore, WinColor.GREY), + AnsiFore.RESET: (winterm.fore, ), + AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True), + AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True), + AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True), + AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True), + AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True), + AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True), + AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True), + AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True), + AnsiBack.BLACK: (winterm.back, WinColor.BLACK), + AnsiBack.RED: (winterm.back, WinColor.RED), + AnsiBack.GREEN: (winterm.back, WinColor.GREEN), + AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW), + AnsiBack.BLUE: (winterm.back, WinColor.BLUE), + AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA), + AnsiBack.CYAN: (winterm.back, WinColor.CYAN), + AnsiBack.WHITE: (winterm.back, WinColor.GREY), + AnsiBack.RESET: (winterm.back, ), + AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True), + AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True), + AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True), + AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True), + AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True), + AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True), + AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True), + AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True), + } + return dict() + + def write(self, text): + if self.strip or self.convert: + self.write_and_convert(text) + else: + self.wrapped.write(text) + self.wrapped.flush() + if self.autoreset: + self.reset_all() + + + def reset_all(self): + if self.convert: + self.call_win32('m', (0,)) + elif not self.strip and not self.stream.closed: + self.wrapped.write(Style.RESET_ALL) + + + def write_and_convert(self, text): + ''' + Write the given text to our wrapped stream, stripping any ANSI + sequences from the text, and optionally converting them into win32 + calls. + ''' + cursor = 0 + text = self.convert_osc(text) + for match in self.ANSI_CSI_RE.finditer(text): + start, end = match.span() + self.write_plain_text(text, cursor, start) + self.convert_ansi(*match.groups()) + cursor = end + self.write_plain_text(text, cursor, len(text)) + + + def write_plain_text(self, text, start, end): + if start < end: + self.wrapped.write(text[start:end]) + self.wrapped.flush() + + + def convert_ansi(self, paramstring, command): + if self.convert: + params = self.extract_params(command, paramstring) + self.call_win32(command, params) + + + def extract_params(self, command, paramstring): + if command in 'Hf': + params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';')) + while len(params) < 2: + # defaults: + params = params + (1,) + else: + params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0) + if len(params) == 0: + # defaults: + if command in 'JKm': + params = (0,) + elif command in 'ABCD': + params = (1,) + + return params + + + def call_win32(self, command, params): + if command == 'm': + for param in params: + if param in self.win32_calls: + func_args = self.win32_calls[param] + func = func_args[0] + args = func_args[1:] + kwargs = dict(on_stderr=self.on_stderr) + func(*args, **kwargs) + elif command in 'J': + winterm.erase_screen(params[0], on_stderr=self.on_stderr) + elif command in 'K': + winterm.erase_line(params[0], on_stderr=self.on_stderr) + elif command in 'Hf': # cursor position - absolute + winterm.set_cursor_position(params, on_stderr=self.on_stderr) + elif command in 'ABCD': # cursor position - relative + n = params[0] + # A - up, B - down, C - forward, D - back + x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command] + winterm.cursor_adjust(x, y, on_stderr=self.on_stderr) + + + def convert_osc(self, text): + for match in self.ANSI_OSC_RE.finditer(text): + start, end = match.span() + text = text[:start] + text[end:] + paramstring, command = match.groups() + if command == BEL: + if paramstring.count(";") == 1: + params = paramstring.split(";") + # 0 - change title and icon (we will only change title) + # 1 - change icon (we don't support this) + # 2 - change title + if params[0] in '02': + winterm.set_title(params[1]) + return text + + + def flush(self): + self.wrapped.flush() diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/initialise.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/initialise.py new file mode 100644 index 0000000000000000000000000000000000000000..d5fd4b71fed1bb4871717f978f0c470280f099c1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/initialise.py @@ -0,0 +1,121 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import atexit +import contextlib +import sys + +from .ansitowin32 import AnsiToWin32 + + +def _wipe_internal_state_for_tests(): + global orig_stdout, orig_stderr + orig_stdout = None + orig_stderr = None + + global wrapped_stdout, wrapped_stderr + wrapped_stdout = None + wrapped_stderr = None + + global atexit_done + atexit_done = False + + global fixed_windows_console + fixed_windows_console = False + + try: + # no-op if it wasn't registered + atexit.unregister(reset_all) + except AttributeError: + # python 2: no atexit.unregister. Oh well, we did our best. + pass + + +def reset_all(): + if AnsiToWin32 is not None: # Issue #74: objects might become None at exit + AnsiToWin32(orig_stdout).reset_all() + + +def init(autoreset=False, convert=None, strip=None, wrap=True): + + if not wrap and any([autoreset, convert, strip]): + raise ValueError('wrap=False conflicts with any other arg=True') + + global wrapped_stdout, wrapped_stderr + global orig_stdout, orig_stderr + + orig_stdout = sys.stdout + orig_stderr = sys.stderr + + if sys.stdout is None: + wrapped_stdout = None + else: + sys.stdout = wrapped_stdout = \ + wrap_stream(orig_stdout, convert, strip, autoreset, wrap) + if sys.stderr is None: + wrapped_stderr = None + else: + sys.stderr = wrapped_stderr = \ + wrap_stream(orig_stderr, convert, strip, autoreset, wrap) + + global atexit_done + if not atexit_done: + atexit.register(reset_all) + atexit_done = True + + +def deinit(): + if orig_stdout is not None: + sys.stdout = orig_stdout + if orig_stderr is not None: + sys.stderr = orig_stderr + + +def just_fix_windows_console(): + global fixed_windows_console + + if sys.platform != "win32": + return + if fixed_windows_console: + return + if wrapped_stdout is not None or wrapped_stderr is not None: + # Someone already ran init() and it did stuff, so we won't second-guess them + return + + # On newer versions of Windows, AnsiToWin32.__init__ will implicitly enable the + # native ANSI support in the console as a side-effect. We only need to actually + # replace sys.stdout/stderr if we're in the old-style conversion mode. + new_stdout = AnsiToWin32(sys.stdout, convert=None, strip=None, autoreset=False) + if new_stdout.convert: + sys.stdout = new_stdout + new_stderr = AnsiToWin32(sys.stderr, convert=None, strip=None, autoreset=False) + if new_stderr.convert: + sys.stderr = new_stderr + + fixed_windows_console = True + +@contextlib.contextmanager +def colorama_text(*args, **kwargs): + init(*args, **kwargs) + try: + yield + finally: + deinit() + + +def reinit(): + if wrapped_stdout is not None: + sys.stdout = wrapped_stdout + if wrapped_stderr is not None: + sys.stderr = wrapped_stderr + + +def wrap_stream(stream, convert, strip, autoreset, wrap): + if wrap: + wrapper = AnsiToWin32(stream, + convert=convert, strip=strip, autoreset=autoreset) + if wrapper.should_wrap(): + stream = wrapper.stream + return stream + + +# Use this for initial setup as well, to reduce code duplication +_wipe_internal_state_for_tests() diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/win32.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/win32.py new file mode 100644 index 0000000000000000000000000000000000000000..841b0e270a381cdfaca544a9be976d7276d83b1e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/win32.py @@ -0,0 +1,180 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. + +# from winbase.h +STDOUT = -11 +STDERR = -12 + +ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 + +try: + import ctypes + from ctypes import LibraryLoader + windll = LibraryLoader(ctypes.WinDLL) + from ctypes import wintypes +except (AttributeError, ImportError): + windll = None + SetConsoleTextAttribute = lambda *_: None + winapi_test = lambda *_: None +else: + from ctypes import byref, Structure, c_char, POINTER + + COORD = wintypes._COORD + + class CONSOLE_SCREEN_BUFFER_INFO(Structure): + """struct in wincon.h.""" + _fields_ = [ + ("dwSize", COORD), + ("dwCursorPosition", COORD), + ("wAttributes", wintypes.WORD), + ("srWindow", wintypes.SMALL_RECT), + ("dwMaximumWindowSize", COORD), + ] + def __str__(self): + return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % ( + self.dwSize.Y, self.dwSize.X + , self.dwCursorPosition.Y, self.dwCursorPosition.X + , self.wAttributes + , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right + , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X + ) + + _GetStdHandle = windll.kernel32.GetStdHandle + _GetStdHandle.argtypes = [ + wintypes.DWORD, + ] + _GetStdHandle.restype = wintypes.HANDLE + + _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo + _GetConsoleScreenBufferInfo.argtypes = [ + wintypes.HANDLE, + POINTER(CONSOLE_SCREEN_BUFFER_INFO), + ] + _GetConsoleScreenBufferInfo.restype = wintypes.BOOL + + _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute + _SetConsoleTextAttribute.argtypes = [ + wintypes.HANDLE, + wintypes.WORD, + ] + _SetConsoleTextAttribute.restype = wintypes.BOOL + + _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition + _SetConsoleCursorPosition.argtypes = [ + wintypes.HANDLE, + COORD, + ] + _SetConsoleCursorPosition.restype = wintypes.BOOL + + _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA + _FillConsoleOutputCharacterA.argtypes = [ + wintypes.HANDLE, + c_char, + wintypes.DWORD, + COORD, + POINTER(wintypes.DWORD), + ] + _FillConsoleOutputCharacterA.restype = wintypes.BOOL + + _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute + _FillConsoleOutputAttribute.argtypes = [ + wintypes.HANDLE, + wintypes.WORD, + wintypes.DWORD, + COORD, + POINTER(wintypes.DWORD), + ] + _FillConsoleOutputAttribute.restype = wintypes.BOOL + + _SetConsoleTitleW = windll.kernel32.SetConsoleTitleW + _SetConsoleTitleW.argtypes = [ + wintypes.LPCWSTR + ] + _SetConsoleTitleW.restype = wintypes.BOOL + + _GetConsoleMode = windll.kernel32.GetConsoleMode + _GetConsoleMode.argtypes = [ + wintypes.HANDLE, + POINTER(wintypes.DWORD) + ] + _GetConsoleMode.restype = wintypes.BOOL + + _SetConsoleMode = windll.kernel32.SetConsoleMode + _SetConsoleMode.argtypes = [ + wintypes.HANDLE, + wintypes.DWORD + ] + _SetConsoleMode.restype = wintypes.BOOL + + def _winapi_test(handle): + csbi = CONSOLE_SCREEN_BUFFER_INFO() + success = _GetConsoleScreenBufferInfo( + handle, byref(csbi)) + return bool(success) + + def winapi_test(): + return any(_winapi_test(h) for h in + (_GetStdHandle(STDOUT), _GetStdHandle(STDERR))) + + def GetConsoleScreenBufferInfo(stream_id=STDOUT): + handle = _GetStdHandle(stream_id) + csbi = CONSOLE_SCREEN_BUFFER_INFO() + success = _GetConsoleScreenBufferInfo( + handle, byref(csbi)) + return csbi + + def SetConsoleTextAttribute(stream_id, attrs): + handle = _GetStdHandle(stream_id) + return _SetConsoleTextAttribute(handle, attrs) + + def SetConsoleCursorPosition(stream_id, position, adjust=True): + position = COORD(*position) + # If the position is out of range, do nothing. + if position.Y <= 0 or position.X <= 0: + return + # Adjust for Windows' SetConsoleCursorPosition: + # 1. being 0-based, while ANSI is 1-based. + # 2. expecting (x,y), while ANSI uses (y,x). + adjusted_position = COORD(position.Y - 1, position.X - 1) + if adjust: + # Adjust for viewport's scroll position + sr = GetConsoleScreenBufferInfo(STDOUT).srWindow + adjusted_position.Y += sr.Top + adjusted_position.X += sr.Left + # Resume normal processing + handle = _GetStdHandle(stream_id) + return _SetConsoleCursorPosition(handle, adjusted_position) + + def FillConsoleOutputCharacter(stream_id, char, length, start): + handle = _GetStdHandle(stream_id) + char = c_char(char.encode()) + length = wintypes.DWORD(length) + num_written = wintypes.DWORD(0) + # Note that this is hard-coded for ANSI (vs wide) bytes. + success = _FillConsoleOutputCharacterA( + handle, char, length, start, byref(num_written)) + return num_written.value + + def FillConsoleOutputAttribute(stream_id, attr, length, start): + ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )''' + handle = _GetStdHandle(stream_id) + attribute = wintypes.WORD(attr) + length = wintypes.DWORD(length) + num_written = wintypes.DWORD(0) + # Note that this is hard-coded for ANSI (vs wide) bytes. + return _FillConsoleOutputAttribute( + handle, attribute, length, start, byref(num_written)) + + def SetConsoleTitle(title): + return _SetConsoleTitleW(title) + + def GetConsoleMode(handle): + mode = wintypes.DWORD() + success = _GetConsoleMode(handle, byref(mode)) + if not success: + raise ctypes.WinError() + return mode.value + + def SetConsoleMode(handle, mode): + success = _SetConsoleMode(handle, mode) + if not success: + raise ctypes.WinError() diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/winterm.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/winterm.py new file mode 100644 index 0000000000000000000000000000000000000000..aad867e8c80b826bf6a060116f17fa08a8eb0765 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/colorama/winterm.py @@ -0,0 +1,195 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +try: + from msvcrt import get_osfhandle +except ImportError: + def get_osfhandle(_): + raise OSError("This isn't windows!") + + +from . import win32 + +# from wincon.h +class WinColor(object): + BLACK = 0 + BLUE = 1 + GREEN = 2 + CYAN = 3 + RED = 4 + MAGENTA = 5 + YELLOW = 6 + GREY = 7 + +# from wincon.h +class WinStyle(object): + NORMAL = 0x00 # dim text, dim background + BRIGHT = 0x08 # bright text, dim background + BRIGHT_BACKGROUND = 0x80 # dim text, bright background + +class WinTerm(object): + + def __init__(self): + self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes + self.set_attrs(self._default) + self._default_fore = self._fore + self._default_back = self._back + self._default_style = self._style + # In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style. + # So that LIGHT_EX colors and BRIGHT style do not clobber each other, + # we track them separately, since LIGHT_EX is overwritten by Fore/Back + # and BRIGHT is overwritten by Style codes. + self._light = 0 + + def get_attrs(self): + return self._fore + self._back * 16 + (self._style | self._light) + + def set_attrs(self, value): + self._fore = value & 7 + self._back = (value >> 4) & 7 + self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND) + + def reset_all(self, on_stderr=None): + self.set_attrs(self._default) + self.set_console(attrs=self._default) + self._light = 0 + + def fore(self, fore=None, light=False, on_stderr=False): + if fore is None: + fore = self._default_fore + self._fore = fore + # Emulate LIGHT_EX with BRIGHT Style + if light: + self._light |= WinStyle.BRIGHT + else: + self._light &= ~WinStyle.BRIGHT + self.set_console(on_stderr=on_stderr) + + def back(self, back=None, light=False, on_stderr=False): + if back is None: + back = self._default_back + self._back = back + # Emulate LIGHT_EX with BRIGHT_BACKGROUND Style + if light: + self._light |= WinStyle.BRIGHT_BACKGROUND + else: + self._light &= ~WinStyle.BRIGHT_BACKGROUND + self.set_console(on_stderr=on_stderr) + + def style(self, style=None, on_stderr=False): + if style is None: + style = self._default_style + self._style = style + self.set_console(on_stderr=on_stderr) + + def set_console(self, attrs=None, on_stderr=False): + if attrs is None: + attrs = self.get_attrs() + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + win32.SetConsoleTextAttribute(handle, attrs) + + def get_position(self, handle): + position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition + # Because Windows coordinates are 0-based, + # and win32.SetConsoleCursorPosition expects 1-based. + position.X += 1 + position.Y += 1 + return position + + def set_cursor_position(self, position=None, on_stderr=False): + if position is None: + # I'm not currently tracking the position, so there is no default. + # position = self.get_position() + return + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + win32.SetConsoleCursorPosition(handle, position) + + def cursor_adjust(self, x, y, on_stderr=False): + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + position = self.get_position(handle) + adjusted_position = (position.Y + y, position.X + x) + win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False) + + def erase_screen(self, mode=0, on_stderr=False): + # 0 should clear from the cursor to the end of the screen. + # 1 should clear from the cursor to the beginning of the screen. + # 2 should clear the entire screen, and move cursor to (1,1) + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + csbi = win32.GetConsoleScreenBufferInfo(handle) + # get the number of character cells in the current buffer + cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y + # get number of character cells before current cursor position + cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X + if mode == 0: + from_coord = csbi.dwCursorPosition + cells_to_erase = cells_in_screen - cells_before_cursor + elif mode == 1: + from_coord = win32.COORD(0, 0) + cells_to_erase = cells_before_cursor + elif mode == 2: + from_coord = win32.COORD(0, 0) + cells_to_erase = cells_in_screen + else: + # invalid mode + return + # fill the entire screen with blanks + win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord) + # now set the buffer's attributes accordingly + win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord) + if mode == 2: + # put the cursor where needed + win32.SetConsoleCursorPosition(handle, (1, 1)) + + def erase_line(self, mode=0, on_stderr=False): + # 0 should clear from the cursor to the end of the line. + # 1 should clear from the cursor to the beginning of the line. + # 2 should clear the entire line. + handle = win32.STDOUT + if on_stderr: + handle = win32.STDERR + csbi = win32.GetConsoleScreenBufferInfo(handle) + if mode == 0: + from_coord = csbi.dwCursorPosition + cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X + elif mode == 1: + from_coord = win32.COORD(0, csbi.dwCursorPosition.Y) + cells_to_erase = csbi.dwCursorPosition.X + elif mode == 2: + from_coord = win32.COORD(0, csbi.dwCursorPosition.Y) + cells_to_erase = csbi.dwSize.X + else: + # invalid mode + return + # fill the entire screen with blanks + win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord) + # now set the buffer's attributes accordingly + win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord) + + def set_title(self, title): + win32.SetConsoleTitle(title) + + +def enable_vt_processing(fd): + if win32.windll is None or not win32.winapi_test(): + return False + + try: + handle = get_osfhandle(fd) + mode = win32.GetConsoleMode(handle) + win32.SetConsoleMode( + handle, + mode | win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING, + ) + + mode = win32.GetConsoleMode(handle) + if mode & win32.ENABLE_VIRTUAL_TERMINAL_PROCESSING: + return True + # Can get TypeError in testsuite where 'fd' is a Mock() + except (OSError, TypeError): + return False diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/LICENSE b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cff5eb74e1badd1c5237ed2654b349530179ad1d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2009, Jay Loden, Dave Daeschler, Giampaolo Rodola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name of the psutil authors nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..685d2e23f3819f5ec01d154c33443572e03cd618 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/METADATA @@ -0,0 +1,546 @@ +Metadata-Version: 2.1 +Name: psutil +Version: 7.0.0 +Summary: Cross-platform lib for process and system monitoring in Python. NOTE: the syntax of this script MUST be kept compatible with Python 2.7. +Home-page: https://github.com/giampaolo/psutil +Author: Giampaolo Rodola +Author-email: g.rodola@gmail.com +License: BSD-3-Clause +Keywords: ps,top,kill,free,lsof,netstat,nice,tty,ionice,uptime,taskmgr,process,df,iotop,iostat,ifconfig,taskset,who,pidof,pmap,smem,pstree,monitoring,ulimit,prlimit,smem,performance,metrics,agent,observability +Platform: Platform Independent +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Environment :: Win32 (MS Windows) +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: System Administrators +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows :: Windows 10 +Classifier: Operating System :: Microsoft :: Windows :: Windows 7 +Classifier: Operating System :: Microsoft :: Windows :: Windows 8 +Classifier: Operating System :: Microsoft :: Windows :: Windows 8.1 +Classifier: Operating System :: Microsoft :: Windows :: Windows Server 2003 +Classifier: Operating System :: Microsoft :: Windows :: Windows Server 2008 +Classifier: Operating System :: Microsoft :: Windows :: Windows Vista +Classifier: Operating System :: Microsoft +Classifier: Operating System :: OS Independent +Classifier: Operating System :: POSIX :: AIX +Classifier: Operating System :: POSIX :: BSD :: FreeBSD +Classifier: Operating System :: POSIX :: BSD :: NetBSD +Classifier: Operating System :: POSIX :: BSD :: OpenBSD +Classifier: Operating System :: POSIX :: BSD +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: POSIX :: SunOS/Solaris +Classifier: Operating System :: POSIX +Classifier: Programming Language :: C +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: System :: Benchmark +Classifier: Topic :: System :: Hardware :: Hardware Drivers +Classifier: Topic :: System :: Hardware +Classifier: Topic :: System :: Monitoring +Classifier: Topic :: System :: Networking :: Monitoring :: Hardware Watchdog +Classifier: Topic :: System :: Networking :: Monitoring +Classifier: Topic :: System :: Networking +Classifier: Topic :: System :: Operating System +Classifier: Topic :: System :: Systems Administration +Classifier: Topic :: Utilities +Requires-Python: >=3.6 +Description-Content-Type: text/x-rst +License-File: LICENSE +Provides-Extra: dev +Requires-Dist: pytest ; extra == 'dev' +Requires-Dist: pytest-xdist ; extra == 'dev' +Requires-Dist: setuptools ; extra == 'dev' +Requires-Dist: abi3audit ; extra == 'dev' +Requires-Dist: black (==24.10.0) ; extra == 'dev' +Requires-Dist: check-manifest ; extra == 'dev' +Requires-Dist: coverage ; extra == 'dev' +Requires-Dist: packaging ; extra == 'dev' +Requires-Dist: pylint ; extra == 'dev' +Requires-Dist: pyperf ; extra == 'dev' +Requires-Dist: pypinfo ; extra == 'dev' +Requires-Dist: pytest-cov ; extra == 'dev' +Requires-Dist: requests ; extra == 'dev' +Requires-Dist: rstcheck ; extra == 'dev' +Requires-Dist: ruff ; extra == 'dev' +Requires-Dist: sphinx ; extra == 'dev' +Requires-Dist: sphinx-rtd-theme ; extra == 'dev' +Requires-Dist: toml-sort ; extra == 'dev' +Requires-Dist: twine ; extra == 'dev' +Requires-Dist: virtualenv ; extra == 'dev' +Requires-Dist: vulture ; extra == 'dev' +Requires-Dist: wheel ; extra == 'dev' +Provides-Extra: test +Requires-Dist: pytest ; extra == 'test' +Requires-Dist: pytest-xdist ; extra == 'test' +Requires-Dist: setuptools ; extra == 'test' + +| |downloads| |stars| |forks| |contributors| |coverage| +| |version| |py-versions| |packages| |license| +| |github-actions-wheels| |github-actions-bsd| |doc| |twitter| |tidelift| + +.. |downloads| image:: https://img.shields.io/pypi/dm/psutil.svg + :target: https://pepy.tech/project/psutil + :alt: Downloads + +.. |stars| image:: https://img.shields.io/github/stars/giampaolo/psutil.svg + :target: https://github.com/giampaolo/psutil/stargazers + :alt: Github stars + +.. |forks| image:: https://img.shields.io/github/forks/giampaolo/psutil.svg + :target: https://github.com/giampaolo/psutil/network/members + :alt: Github forks + +.. |contributors| image:: https://img.shields.io/github/contributors/giampaolo/psutil.svg + :target: https://github.com/giampaolo/psutil/graphs/contributors + :alt: Contributors + +.. |github-actions-wheels| image:: https://img.shields.io/github/actions/workflow/status/giampaolo/psutil/.github/workflows/build.yml.svg?label=Linux%2C%20macOS%2C%20Windows + :target: https://github.com/giampaolo/psutil/actions?query=workflow%3Abuild + :alt: Linux, macOS, Windows + +.. |github-actions-bsd| image:: https://img.shields.io/github/actions/workflow/status/giampaolo/psutil/.github/workflows/bsd.yml.svg?label=FreeBSD,%20NetBSD,%20OpenBSD + :target: https://github.com/giampaolo/psutil/actions?query=workflow%3Absd-tests + :alt: FreeBSD, NetBSD, OpenBSD + +.. |coverage| image:: https://coveralls.io/repos/github/giampaolo/psutil/badge.svg?branch=master + :target: https://coveralls.io/github/giampaolo/psutil?branch=master + :alt: Test coverage (coverall.io) + +.. |doc| image:: https://readthedocs.org/projects/psutil/badge/?version=latest + :target: https://psutil.readthedocs.io/en/latest/ + :alt: Documentation Status + +.. |version| image:: https://img.shields.io/pypi/v/psutil.svg?label=pypi + :target: https://pypi.org/project/psutil + :alt: Latest version + +.. |py-versions| image:: https://img.shields.io/pypi/pyversions/psutil.svg + :alt: Supported Python versions + +.. |packages| image:: https://repology.org/badge/tiny-repos/python:psutil.svg + :target: https://repology.org/metapackage/python:psutil/versions + :alt: Binary packages + +.. |license| image:: https://img.shields.io/pypi/l/psutil.svg + :target: https://github.com/giampaolo/psutil/blob/master/LICENSE + :alt: License + +.. |twitter| image:: https://img.shields.io/twitter/follow/grodola.svg?label=follow&style=flat&logo=twitter&logoColor=4FADFF + :target: https://twitter.com/grodola + :alt: Twitter Follow + +.. |tidelift| image:: https://tidelift.com/badges/github/giampaolo/psutil?style=flat + :target: https://tidelift.com/subscription/pkg/pypi-psutil?utm_source=pypi-psutil&utm_medium=referral&utm_campaign=readme + :alt: Tidelift + +----- + +Quick links +=========== + +- `Home page `_ +- `Install `_ +- `Documentation `_ +- `Download `_ +- `Forum `_ +- `StackOverflow `_ +- `Blog `_ +- `What's new `_ + + +Summary +======= + +psutil (process and system utilities) is a cross-platform library for +retrieving information on **running processes** and **system utilization** +(CPU, memory, disks, network, sensors) in Python. +It is useful mainly for **system monitoring**, **profiling and limiting process +resources** and **management of running processes**. +It implements many functionalities offered by classic UNIX command line tools +such as *ps, top, iotop, lsof, netstat, ifconfig, free* and others. +psutil currently supports the following platforms: + +- **Linux** +- **Windows** +- **macOS** +- **FreeBSD, OpenBSD**, **NetBSD** +- **Sun Solaris** +- **AIX** + +Supported Python versions are cPython 3.6+ and `PyPy `__. +Latest psutil version supporting Python 2.7 is +`psutil 6.1.1 `__. + +Funding +======= + +While psutil is free software and will always be, the project would benefit +immensely from some funding. +Keeping up with bug reports and maintenance has become hardly sustainable for +me alone in terms of time. +If you're a company that's making significant use of psutil you can consider +becoming a sponsor via `GitHub Sponsors `__, +`Open Collective `__ or +`PayPal `__ +and have your logo displayed in here and psutil `doc `__. + +Sponsors +======== + +.. image:: https://github.com/giampaolo/psutil/raw/master/docs/_static/tidelift-logo.png + :width: 200 + :alt: Alternative text + +`Add your logo `__. + +Example usages +============== + +This represents pretty much the whole psutil API. + +CPU +--- + +.. code-block:: python + + >>> import psutil + >>> + >>> psutil.cpu_times() + scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, guest_nice=0.0) + >>> + >>> for x in range(3): + ... psutil.cpu_percent(interval=1) + ... + 4.0 + 5.9 + 3.8 + >>> + >>> for x in range(3): + ... psutil.cpu_percent(interval=1, percpu=True) + ... + [4.0, 6.9, 3.7, 9.2] + [7.0, 8.5, 2.4, 2.1] + [1.2, 9.0, 9.9, 7.2] + >>> + >>> for x in range(3): + ... psutil.cpu_times_percent(interval=1, percpu=False) + ... + scputimes(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0) + scputimes(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0) + scputimes(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0) + >>> + >>> psutil.cpu_count() + 4 + >>> psutil.cpu_count(logical=False) + 2 + >>> + >>> psutil.cpu_stats() + scpustats(ctx_switches=20455687, interrupts=6598984, soft_interrupts=2134212, syscalls=0) + >>> + >>> psutil.cpu_freq() + scpufreq(current=931.42925, min=800.0, max=3500.0) + >>> + >>> psutil.getloadavg() # also on Windows (emulated) + (3.14, 3.89, 4.67) + +Memory +------ + +.. code-block:: python + + >>> psutil.virtual_memory() + svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304) + >>> psutil.swap_memory() + sswap(total=2097147904, used=296128512, free=1801019392, percent=14.1, sin=304193536, sout=677842944) + >>> + +Disks +----- + +.. code-block:: python + + >>> psutil.disk_partitions() + [sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'), + sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext', opts='rw')] + >>> + >>> psutil.disk_usage('/') + sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5) + >>> + >>> psutil.disk_io_counters(perdisk=False) + sdiskio(read_count=719566, write_count=1082197, read_bytes=18626220032, write_bytes=24081764352, read_time=5023392, write_time=63199568, read_merged_count=619166, write_merged_count=812396, busy_time=4523412) + >>> + +Network +------- + +.. code-block:: python + + >>> psutil.net_io_counters(pernic=True) + {'eth0': netio(bytes_sent=485291293, bytes_recv=6004858642, packets_sent=3251564, packets_recv=4787798, errin=0, errout=0, dropin=0, dropout=0), + 'lo': netio(bytes_sent=2838627, bytes_recv=2838627, packets_sent=30567, packets_recv=30567, errin=0, errout=0, dropin=0, dropout=0)} + >>> + >>> psutil.net_connections(kind='tcp') + [sconn(fd=115, family=, type=, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED', pid=1254), + sconn(fd=117, family=, type=, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING', pid=2987), + ...] + >>> + >>> psutil.net_if_addrs() + {'lo': [snicaddr(family=, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None), + snicaddr(family=, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None), + snicaddr(family=, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)], + 'wlan0': [snicaddr(family=, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None), + snicaddr(family=, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), + snicaddr(family=, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]} + >>> + >>> psutil.net_if_stats() + {'lo': snicstats(isup=True, duplex=, speed=0, mtu=65536, flags='up,loopback,running'), + 'wlan0': snicstats(isup=True, duplex=, speed=100, mtu=1500, flags='up,broadcast,running,multicast')} + >>> + +Sensors +------- + +.. code-block:: python + + >>> import psutil + >>> psutil.sensors_temperatures() + {'acpitz': [shwtemp(label='', current=47.0, high=103.0, critical=103.0)], + 'asus': [shwtemp(label='', current=47.0, high=None, critical=None)], + 'coretemp': [shwtemp(label='Physical id 0', current=52.0, high=100.0, critical=100.0), + shwtemp(label='Core 0', current=45.0, high=100.0, critical=100.0)]} + >>> + >>> psutil.sensors_fans() + {'asus': [sfan(label='cpu_fan', current=3200)]} + >>> + >>> psutil.sensors_battery() + sbattery(percent=93, secsleft=16628, power_plugged=False) + >>> + +Other system info +----------------- + +.. code-block:: python + + >>> import psutil + >>> psutil.users() + [suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0, pid=1352), + suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0, pid=1788)] + >>> + >>> psutil.boot_time() + 1365519115.0 + >>> + +Process management +------------------ + +.. code-block:: python + + >>> import psutil + >>> psutil.pids() + [1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224, 268, 1215, + 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355, 2637, 2774, 3932, + 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245, 4263, 4282, 4306, 4311, + 4312, 4313, 4314, 4337, 4339, 4357, 4358, 4363, 4383, 4395, 4408, 4433, + 4443, 4445, 4446, 5167, 5234, 5235, 5252, 5318, 5424, 5644, 6987, 7054, + 7055, 7071] + >>> + >>> p = psutil.Process(7055) + >>> p + psutil.Process(pid=7055, name='python3', status='running', started='09:04:44') + >>> p.pid + 7055 + >>> p.name() + 'python3' + >>> p.exe() + '/usr/bin/python3' + >>> p.cwd() + '/home/giampaolo' + >>> p.cmdline() + ['/usr/bin/python3', 'main.py'] + >>> + >>> p.ppid() + 7054 + >>> p.parent() + psutil.Process(pid=4699, name='bash', status='sleeping', started='09:06:44') + >>> p.parents() + [psutil.Process(pid=4699, name='bash', started='09:06:44'), + psutil.Process(pid=4689, name='gnome-terminal-server', status='sleeping', started='0:06:44'), + psutil.Process(pid=1, name='systemd', status='sleeping', started='05:56:55')] + >>> p.children(recursive=True) + [psutil.Process(pid=29835, name='python3', status='sleeping', started='11:45:38'), + psutil.Process(pid=29836, name='python3', status='waking', started='11:43:39')] + >>> + >>> p.status() + 'running' + >>> p.create_time() + 1267551141.5019531 + >>> p.terminal() + '/dev/pts/0' + >>> + >>> p.username() + 'giampaolo' + >>> p.uids() + puids(real=1000, effective=1000, saved=1000) + >>> p.gids() + pgids(real=1000, effective=1000, saved=1000) + >>> + >>> p.cpu_times() + pcputimes(user=1.02, system=0.31, children_user=0.32, children_system=0.1, iowait=0.0) + >>> p.cpu_percent(interval=1.0) + 12.1 + >>> p.cpu_affinity() + [0, 1, 2, 3] + >>> p.cpu_affinity([0, 1]) # set + >>> p.cpu_num() + 1 + >>> + >>> p.memory_info() + pmem(rss=10915840, vms=67608576, shared=3313664, text=2310144, lib=0, data=7262208, dirty=0) + >>> p.memory_full_info() # "real" USS memory usage (Linux, macOS, Win only) + pfullmem(rss=10199040, vms=52133888, shared=3887104, text=2867200, lib=0, data=5967872, dirty=0, uss=6545408, pss=6872064, swap=0) + >>> p.memory_percent() + 0.7823 + >>> p.memory_maps() + [pmmap_grouped(path='/lib/x8664-linux-gnu/libutil-2.15.so', rss=32768, size=2125824, pss=32768, shared_clean=0, shared_dirty=0, private_clean=20480, private_dirty=12288, referenced=32768, anonymous=12288, swap=0), + pmmap_grouped(path='/lib/x8664-linux-gnu/libc-2.15.so', rss=3821568, size=3842048, pss=3821568, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=3821568, referenced=3575808, anonymous=3821568, swap=0), + pmmap_grouped(path='[heap]', rss=32768, size=139264, pss=32768, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=32768, referenced=32768, anonymous=32768, swap=0), + pmmap_grouped(path='[stack]', rss=2465792, size=2494464, pss=2465792, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=2465792, referenced=2277376, anonymous=2465792, swap=0), + ...] + >>> + >>> p.io_counters() + pio(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632, read_chars=456232, write_chars=517543) + >>> + >>> p.open_files() + [popenfile(path='/home/giampaolo/monit.py', fd=3, position=0, mode='r', flags=32768), + popenfile(path='/var/log/monit.log', fd=4, position=235542, mode='a', flags=33793)] + >>> + >>> p.net_connections(kind='tcp') + [pconn(fd=115, family=, type=, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED'), + pconn(fd=117, family=, type=, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING')] + >>> + >>> p.threads() + [pthread(id=5234, user_time=22.5, system_time=9.2891), + pthread(id=5237, user_time=0.0707, system_time=1.1)] + >>> + >>> p.num_threads() + 4 + >>> p.num_fds() + 8 + >>> p.num_ctx_switches() + pctxsw(voluntary=78, involuntary=19) + >>> + >>> p.nice() + 0 + >>> p.nice(10) # set + >>> + >>> p.ionice(psutil.IOPRIO_CLASS_IDLE) # IO priority (Win and Linux only) + >>> p.ionice() + pionice(ioclass=, value=0) + >>> + >>> p.rlimit(psutil.RLIMIT_NOFILE, (5, 5)) # set resource limits (Linux only) + >>> p.rlimit(psutil.RLIMIT_NOFILE) + (5, 5) + >>> + >>> p.environ() + {'LC_PAPER': 'it_IT.UTF-8', 'SHELL': '/bin/bash', 'GREP_OPTIONS': '--color=auto', + 'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg', + ...} + >>> + >>> p.as_dict() + {'status': 'running', 'num_ctx_switches': pctxsw(voluntary=63, involuntary=1), 'pid': 5457, ...} + >>> p.is_running() + True + >>> p.suspend() + >>> p.resume() + >>> + >>> p.terminate() + >>> p.kill() + >>> p.wait(timeout=3) + + >>> + >>> psutil.test() + USER PID %CPU %MEM VSZ RSS TTY START TIME COMMAND + root 1 0.0 0.0 24584 2240 Jun17 00:00 init + root 2 0.0 0.0 0 0 Jun17 00:00 kthreadd + ... + giampaolo 31475 0.0 0.0 20760 3024 /dev/pts/0 Jun19 00:00 python2.4 + giampaolo 31721 0.0 2.2 773060 181896 00:04 10:30 chrome + root 31763 0.0 0.0 0 0 00:05 00:00 kworker/0:1 + >>> + +Further process APIs +-------------------- + +.. code-block:: python + + >>> import psutil + >>> for proc in psutil.process_iter(['pid', 'name']): + ... print(proc.info) + ... + {'pid': 1, 'name': 'systemd'} + {'pid': 2, 'name': 'kthreadd'} + {'pid': 3, 'name': 'ksoftirqd/0'} + ... + >>> + >>> psutil.pid_exists(3) + True + >>> + >>> def on_terminate(proc): + ... print("process {} terminated".format(proc)) + ... + >>> # waits for multiple processes to terminate + >>> gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate) + >>> + +Windows services +---------------- + +.. code-block:: python + + >>> list(psutil.win_service_iter()) + [, + , + , + , + ...] + >>> s = psutil.win_service_get('alg') + >>> s.as_dict() + {'binpath': 'C:\\Windows\\System32\\alg.exe', + 'description': 'Provides support for 3rd party protocol plug-ins for Internet Connection Sharing', + 'display_name': 'Application Layer Gateway Service', + 'name': 'alg', + 'pid': None, + 'start_type': 'manual', + 'status': 'stopped', + 'username': 'NT AUTHORITY\\LocalService'} + +Projects using psutil +===================== + +Here's some I find particularly interesting: + +- https://github.com/google/grr +- https://github.com/facebook/osquery/ +- https://github.com/nicolargo/glances +- https://github.com/aristocratos/bpytop +- https://github.com/Jahaja/psdash +- https://github.com/ajenti/ajenti +- https://github.com/home-assistant/home-assistant/ + +Portings +======== + +- Go: https://github.com/shirou/gopsutil +- C: https://github.com/hamon-in/cpslib +- Rust: https://github.com/rust-psutil/rust-psutil +- Nim: https://github.com/johnscillieri/psutil-nim + + + diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..43ea09357e0f9589582e8e990c322c338ac08e6d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/RECORD @@ -0,0 +1,65 @@ +psutil-7.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +psutil-7.0.0.dist-info/LICENSE,sha256=uJwGOzeG4o4MCjjxkx22H-015p3SopZvvs_-4PRsjRA,1548 +psutil-7.0.0.dist-info/METADATA,sha256=BFPkVTphhSTYAB4vZKg7HCRBmCbKuHv2tzTmcj04PIk,22315 +psutil-7.0.0.dist-info/RECORD,, +psutil-7.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +psutil-7.0.0.dist-info/WHEEL,sha256=rgpVBmjjvbINeGKCkWEGd3f40VHMTsDkQj1Lgil82zE,221 +psutil-7.0.0.dist-info/top_level.txt,sha256=gCNhn57wzksDjSAISmgMJ0aiXzQulk0GJhb2-BAyYgw,7 +psutil/__init__.py,sha256=tPSkFUoX9EGtvKiDzRcSMYhUbHlIdFbCw57a4ysNzLE,86668 +psutil/__pycache__/__init__.cpython-310.pyc,, +psutil/__pycache__/_common.cpython-310.pyc,, +psutil/__pycache__/_psaix.cpython-310.pyc,, +psutil/__pycache__/_psbsd.cpython-310.pyc,, +psutil/__pycache__/_pslinux.cpython-310.pyc,, +psutil/__pycache__/_psosx.cpython-310.pyc,, +psutil/__pycache__/_psposix.cpython-310.pyc,, +psutil/__pycache__/_pssunos.cpython-310.pyc,, +psutil/__pycache__/_pswindows.cpython-310.pyc,, +psutil/_common.py,sha256=0V6pk_6dqkaIMB2fbdlxERWV0jIt8m1yLxMPCqsVzAo,28642 +psutil/_psaix.py,sha256=5haK5IsqogH7ws-uikbh7LJywqsQTL4ihV-KT3CJ-f8,18252 +psutil/_psbsd.py,sha256=3pdjaz9QVPj2OeCRQSXXXGf89is9Fijt328dNIi8Jng,31756 +psutil/_pslinux.py,sha256=29sX7gw6tLXwp8eSLZ_NcVqa42glkZlGGonckWWlTrc,86028 +psutil/_psosx.py,sha256=O0HA58WMQMfMw6SrjyCn2Q3oN3GpQzC66BK9826w038,15877 +psutil/_psposix.py,sha256=kHwIVJ0J3aLvtNJrcs4h0OFMRVFKRtVmGMUvBhZwaRU,7142 +psutil/_pssunos.py,sha256=_N0t0vKPv4hl-rbVkROieAWgWP_pPUBsNO29me7xgc4,24920 +psutil/_psutil_linux.abi3.so,sha256=bC66whE5AHQQCAgRoBXCSe1vsvIHsaZOAY5HrhkXQIE,115336 +psutil/_psutil_posix.abi3.so,sha256=Kl35Rx_zW8_N1mNhs4OH_y4ZR3tq9P2eHCBUWSu6kcA,71640 +psutil/_pswindows.py,sha256=12fUxO7XxwHO0-IVCsWflc2CXbXg8NzfvgHptgTr4nI,35949 +psutil/tests/__init__.py,sha256=naU3g4k4xVCBqXZel9nHJEMoJkQKltxbKyfjDE-6HwM,64104 +psutil/tests/__main__.py,sha256=GYT-hlMnWDtybkJ76DqQcjXPr0jnLeZDTe0lVVeDb7o,309 +psutil/tests/__pycache__/__init__.cpython-310.pyc,, +psutil/tests/__pycache__/__main__.cpython-310.pyc,, +psutil/tests/__pycache__/test_aix.cpython-310.pyc,, +psutil/tests/__pycache__/test_bsd.cpython-310.pyc,, +psutil/tests/__pycache__/test_connections.cpython-310.pyc,, +psutil/tests/__pycache__/test_contracts.cpython-310.pyc,, +psutil/tests/__pycache__/test_linux.cpython-310.pyc,, +psutil/tests/__pycache__/test_memleaks.cpython-310.pyc,, +psutil/tests/__pycache__/test_misc.cpython-310.pyc,, +psutil/tests/__pycache__/test_osx.cpython-310.pyc,, +psutil/tests/__pycache__/test_posix.cpython-310.pyc,, +psutil/tests/__pycache__/test_process.cpython-310.pyc,, +psutil/tests/__pycache__/test_process_all.cpython-310.pyc,, +psutil/tests/__pycache__/test_scripts.cpython-310.pyc,, +psutil/tests/__pycache__/test_sunos.cpython-310.pyc,, +psutil/tests/__pycache__/test_system.cpython-310.pyc,, +psutil/tests/__pycache__/test_testutils.cpython-310.pyc,, +psutil/tests/__pycache__/test_unicode.cpython-310.pyc,, +psutil/tests/__pycache__/test_windows.cpython-310.pyc,, +psutil/tests/test_aix.py,sha256=O5IqMAU3qw1NXvI-nhNb9v1LbNHb1q3iFRe5OkqgpoI,4408 +psutil/tests/test_bsd.py,sha256=wALt2KBsv8LmuSbADGnXx3h3AL7dTheCmPBB9_iwE38,20191 +psutil/tests/test_connections.py,sha256=nL8675MBoPLoWc35ujR7QvMGRWtZjh6u3CmnwLTmts8,21157 +psutil/tests/test_contracts.py,sha256=ffPNOZ1nK4xV7gKYxJs1nOjORkM0WL-PSSxPQvq8pnI,12001 +psutil/tests/test_linux.py,sha256=Vw1hwyn2mGXQ1DYSksBWzfBBAynaiyWhXKRMWF_-3Sg,88895 +psutil/tests/test_memleaks.py,sha256=hC0Ra6v3ZwhMmLuJoCTeLUCJuh5wa0ER8UvHVSVTsio,15121 +psutil/tests/test_misc.py,sha256=PTelE-5fdcmL_49kz46966JNl8VB3-PowwmkwcIyodc,29672 +psutil/tests/test_osx.py,sha256=ysb3dSwJfzo07ElnFJThoJKmwquqQoUsaKeL1sz8zf8,6315 +psutil/tests/test_posix.py,sha256=bNQFfIrgLYNSFxbep9Qsqej46EG7yzH69_tlbpz3odY,17187 +psutil/tests/test_process.py,sha256=7g0vLr5ZdIj_sEzWkdSIpdBlRlcxTGI2UtUDa6KufUE,59881 +psutil/tests/test_process_all.py,sha256=kbe6Hq0UNGuHCx0T9jLok8O-E7RDQi5RLBZyCU_we5Q,18347 +psutil/tests/test_scripts.py,sha256=K--xQZrcNv4ABtax76ADBU_DjWK17cceTPg-jFoGpbI,7725 +psutil/tests/test_sunos.py,sha256=78nUq_4I2ALidWLiOGRjgP7ykFiGm8eGV3JNAiIoOVs,1190 +psutil/tests/test_system.py,sha256=UhmDw0psTdmAgfNmlS176Hv7hOwUl7F148vc7qH19GE,36107 +psutil/tests/test_testutils.py,sha256=2enHiV8mMapwrLwadIj04V3Z4M1OsyH49Hhg5bf3VxU,18338 +psutil/tests/test_unicode.py,sha256=Cv2pp9qS5iQJ8RMPKRow9--QoHsP1Q9ng6aKvbJnSWs,10392 +psutil/tests/test_windows.py,sha256=OESmHBNsYCwfpcqeloFmkvRfAzJf-nV75a0b0ztPUcE,33214 diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/REQUESTED b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..cd914569da29261e4b9b92baa594300a56d49711 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/WHEEL @@ -0,0 +1,8 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.1) +Root-Is-Purelib: false +Tag: cp36-abi3-manylinux_2_12_x86_64 +Tag: cp36-abi3-manylinux2010_x86_64 +Tag: cp36-abi3-manylinux_2_17_x86_64 +Tag: cp36-abi3-manylinux2014_x86_64 + diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a4d92cc08db6a0d8bfedbbbd620d1fb11f84677b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil-7.0.0.dist-info/top_level.txt @@ -0,0 +1 @@ +psutil diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__init__.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cf4a58057f9cd86df47159f5778cff467a391e36 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__init__.py @@ -0,0 +1,2407 @@ +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""psutil is a cross-platform library for retrieving information on +running processes and system utilization (CPU, memory, disks, network, +sensors) in Python. Supported platforms: + + - Linux + - Windows + - macOS + - FreeBSD + - OpenBSD + - NetBSD + - Sun Solaris + - AIX + +Supported Python versions are cPython 3.6+ and PyPy. +""" + +import collections +import contextlib +import datetime +import functools +import os +import signal +import socket +import subprocess +import sys +import threading +import time + + +try: + import pwd +except ImportError: + pwd = None + +from . import _common +from ._common import AIX +from ._common import BSD +from ._common import CONN_CLOSE +from ._common import CONN_CLOSE_WAIT +from ._common import CONN_CLOSING +from ._common import CONN_ESTABLISHED +from ._common import CONN_FIN_WAIT1 +from ._common import CONN_FIN_WAIT2 +from ._common import CONN_LAST_ACK +from ._common import CONN_LISTEN +from ._common import CONN_NONE +from ._common import CONN_SYN_RECV +from ._common import CONN_SYN_SENT +from ._common import CONN_TIME_WAIT +from ._common import FREEBSD +from ._common import LINUX +from ._common import MACOS +from ._common import NETBSD +from ._common import NIC_DUPLEX_FULL +from ._common import NIC_DUPLEX_HALF +from ._common import NIC_DUPLEX_UNKNOWN +from ._common import OPENBSD +from ._common import OSX # deprecated alias +from ._common import POSIX +from ._common import POWER_TIME_UNKNOWN +from ._common import POWER_TIME_UNLIMITED +from ._common import STATUS_DEAD +from ._common import STATUS_DISK_SLEEP +from ._common import STATUS_IDLE +from ._common import STATUS_LOCKED +from ._common import STATUS_PARKED +from ._common import STATUS_RUNNING +from ._common import STATUS_SLEEPING +from ._common import STATUS_STOPPED +from ._common import STATUS_TRACING_STOP +from ._common import STATUS_WAITING +from ._common import STATUS_WAKING +from ._common import STATUS_ZOMBIE +from ._common import SUNOS +from ._common import WINDOWS +from ._common import AccessDenied +from ._common import Error +from ._common import NoSuchProcess +from ._common import TimeoutExpired +from ._common import ZombieProcess +from ._common import debug +from ._common import memoize_when_activated +from ._common import wrap_numbers as _wrap_numbers + + +if LINUX: + # This is public API and it will be retrieved from _pslinux.py + # via sys.modules. + PROCFS_PATH = "/proc" + + from . import _pslinux as _psplatform + from ._pslinux import IOPRIO_CLASS_BE # noqa: F401 + from ._pslinux import IOPRIO_CLASS_IDLE # noqa: F401 + from ._pslinux import IOPRIO_CLASS_NONE # noqa: F401 + from ._pslinux import IOPRIO_CLASS_RT # noqa: F401 + +elif WINDOWS: + from . import _pswindows as _psplatform + from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS # noqa: F401 + from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS # noqa: F401 + from ._psutil_windows import HIGH_PRIORITY_CLASS # noqa: F401 + from ._psutil_windows import IDLE_PRIORITY_CLASS # noqa: F401 + from ._psutil_windows import NORMAL_PRIORITY_CLASS # noqa: F401 + from ._psutil_windows import REALTIME_PRIORITY_CLASS # noqa: F401 + from ._pswindows import CONN_DELETE_TCB # noqa: F401 + from ._pswindows import IOPRIO_HIGH # noqa: F401 + from ._pswindows import IOPRIO_LOW # noqa: F401 + from ._pswindows import IOPRIO_NORMAL # noqa: F401 + from ._pswindows import IOPRIO_VERYLOW # noqa: F401 + +elif MACOS: + from . import _psosx as _psplatform + +elif BSD: + from . import _psbsd as _psplatform + +elif SUNOS: + from . import _pssunos as _psplatform + from ._pssunos import CONN_BOUND # noqa: F401 + from ._pssunos import CONN_IDLE # noqa: F401 + + # This is public writable API which is read from _pslinux.py and + # _pssunos.py via sys.modules. + PROCFS_PATH = "/proc" + +elif AIX: + from . import _psaix as _psplatform + + # This is public API and it will be retrieved from _pslinux.py + # via sys.modules. + PROCFS_PATH = "/proc" + +else: # pragma: no cover + msg = f"platform {sys.platform} is not supported" + raise NotImplementedError(msg) + + +# fmt: off +__all__ = [ + # exceptions + "Error", "NoSuchProcess", "ZombieProcess", "AccessDenied", + "TimeoutExpired", + + # constants + "version_info", "__version__", + + "STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP", + "STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD", + "STATUS_WAKING", "STATUS_LOCKED", "STATUS_WAITING", "STATUS_LOCKED", + "STATUS_PARKED", + + "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1", + "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT", + "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", "CONN_NONE", + # "CONN_IDLE", "CONN_BOUND", + + "AF_LINK", + + "NIC_DUPLEX_FULL", "NIC_DUPLEX_HALF", "NIC_DUPLEX_UNKNOWN", + + "POWER_TIME_UNKNOWN", "POWER_TIME_UNLIMITED", + + "BSD", "FREEBSD", "LINUX", "NETBSD", "OPENBSD", "MACOS", "OSX", "POSIX", + "SUNOS", "WINDOWS", "AIX", + + # "RLIM_INFINITY", "RLIMIT_AS", "RLIMIT_CORE", "RLIMIT_CPU", "RLIMIT_DATA", + # "RLIMIT_FSIZE", "RLIMIT_LOCKS", "RLIMIT_MEMLOCK", "RLIMIT_NOFILE", + # "RLIMIT_NPROC", "RLIMIT_RSS", "RLIMIT_STACK", "RLIMIT_MSGQUEUE", + # "RLIMIT_NICE", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", "RLIMIT_SIGPENDING", + + # classes + "Process", "Popen", + + # functions + "pid_exists", "pids", "process_iter", "wait_procs", # proc + "virtual_memory", "swap_memory", # memory + "cpu_times", "cpu_percent", "cpu_times_percent", "cpu_count", # cpu + "cpu_stats", # "cpu_freq", "getloadavg" + "net_io_counters", "net_connections", "net_if_addrs", # network + "net_if_stats", + "disk_io_counters", "disk_partitions", "disk_usage", # disk + # "sensors_temperatures", "sensors_battery", "sensors_fans" # sensors + "users", "boot_time", # others +] +# fmt: on + + +__all__.extend(_psplatform.__extra__all__) + +# Linux, FreeBSD +if hasattr(_psplatform.Process, "rlimit"): + # Populate global namespace with RLIM* constants. + from . import _psutil_posix + + _globals = globals() + _name = None + for _name in dir(_psutil_posix): + if _name.startswith('RLIM') and _name.isupper(): + _globals[_name] = getattr(_psutil_posix, _name) + __all__.append(_name) + del _globals, _name + +AF_LINK = _psplatform.AF_LINK + +__author__ = "Giampaolo Rodola'" +__version__ = "7.0.0" +version_info = tuple(int(num) for num in __version__.split('.')) + +_timer = getattr(time, 'monotonic', time.time) +_TOTAL_PHYMEM = None +_LOWEST_PID = None +_SENTINEL = object() + +# Sanity check in case the user messed up with psutil installation +# or did something weird with sys.path. In this case we might end +# up importing a python module using a C extension module which +# was compiled for a different version of psutil. +# We want to prevent that by failing sooner rather than later. +# See: https://github.com/giampaolo/psutil/issues/564 +if int(__version__.replace('.', '')) != getattr( + _psplatform.cext, 'version', None +): + msg = f"version conflict: {_psplatform.cext.__file__!r} C extension " + msg += "module was built for another version of psutil" + if hasattr(_psplatform.cext, 'version'): + v = ".".join(list(str(_psplatform.cext.version))) + msg += f" ({v} instead of {__version__})" + else: + msg += f" (different than {__version__})" + what = getattr( + _psplatform.cext, + "__file__", + "the existing psutil install directory", + ) + msg += f"; you may try to 'pip uninstall psutil', manually remove {what}" + msg += " or clean the virtual env somehow, then reinstall" + raise ImportError(msg) + + +# ===================================================================== +# --- Utils +# ===================================================================== + + +if hasattr(_psplatform, 'ppid_map'): + # Faster version (Windows and Linux). + _ppid_map = _psplatform.ppid_map +else: # pragma: no cover + + def _ppid_map(): + """Return a {pid: ppid, ...} dict for all running processes in + one shot. Used to speed up Process.children(). + """ + ret = {} + for pid in pids(): + try: + ret[pid] = _psplatform.Process(pid).ppid() + except (NoSuchProcess, ZombieProcess): + pass + return ret + + +def _pprint_secs(secs): + """Format seconds in a human readable form.""" + now = time.time() + secs_ago = int(now - secs) + fmt = "%H:%M:%S" if secs_ago < 60 * 60 * 24 else "%Y-%m-%d %H:%M:%S" + return datetime.datetime.fromtimestamp(secs).strftime(fmt) + + +def _check_conn_kind(kind): + """Check net_connections()'s `kind` parameter.""" + kinds = tuple(_common.conn_tmap) + if kind not in kinds: + msg = f"invalid kind argument {kind!r}; valid ones are: {kinds}" + raise ValueError(msg) + + +# ===================================================================== +# --- Process class +# ===================================================================== + + +class Process: + """Represents an OS process with the given PID. + If PID is omitted current process PID (os.getpid()) is used. + Raise NoSuchProcess if PID does not exist. + + Note that most of the methods of this class do not make sure that + the PID of the process being queried has been reused. That means + that you may end up retrieving information for another process. + + The only exceptions for which process identity is pre-emptively + checked and guaranteed are: + + - parent() + - children() + - nice() (set) + - ionice() (set) + - rlimit() (set) + - cpu_affinity (set) + - suspend() + - resume() + - send_signal() + - terminate() + - kill() + + To prevent this problem for all other methods you can use + is_running() before querying the process. + """ + + def __init__(self, pid=None): + self._init(pid) + + def _init(self, pid, _ignore_nsp=False): + if pid is None: + pid = os.getpid() + else: + if pid < 0: + msg = f"pid must be a positive integer (got {pid})" + raise ValueError(msg) + try: + _psplatform.cext.check_pid_range(pid) + except OverflowError as err: + msg = "process PID out of range" + raise NoSuchProcess(pid, msg=msg) from err + + self._pid = pid + self._name = None + self._exe = None + self._create_time = None + self._gone = False + self._pid_reused = False + self._hash = None + self._lock = threading.RLock() + # used for caching on Windows only (on POSIX ppid may change) + self._ppid = None + # platform-specific modules define an _psplatform.Process + # implementation class + self._proc = _psplatform.Process(pid) + self._last_sys_cpu_times = None + self._last_proc_cpu_times = None + self._exitcode = _SENTINEL + self._ident = (self.pid, None) + try: + self._ident = self._get_ident() + except AccessDenied: + # This should happen on Windows only, since we use the fast + # create time method. AFAIK, on all other platforms we are + # able to get create time for all PIDs. + pass + except ZombieProcess: + # Zombies can still be queried by this class (although + # not always) and pids() return them so just go on. + pass + except NoSuchProcess: + if not _ignore_nsp: + msg = "process PID not found" + raise NoSuchProcess(pid, msg=msg) from None + self._gone = True + + def _get_ident(self): + """Return a (pid, uid) tuple which is supposed to identify a + Process instance univocally over time. The PID alone is not + enough, as it can be assigned to a new process after this one + terminates, so we add process creation time to the mix. We need + this in order to prevent killing the wrong process later on. + This is also known as PID reuse or PID recycling problem. + + The reliability of this strategy mostly depends on + create_time() precision, which is 0.01 secs on Linux. The + assumption is that, after a process terminates, the kernel + won't reuse the same PID after such a short period of time + (0.01 secs). Technically this is inherently racy, but + practically it should be good enough. + """ + if WINDOWS: + # Use create_time() fast method in order to speedup + # `process_iter()`. This means we'll get AccessDenied for + # most ADMIN processes, but that's fine since it means + # we'll also get AccessDenied on kill(). + # https://github.com/giampaolo/psutil/issues/2366#issuecomment-2381646555 + self._create_time = self._proc.create_time(fast_only=True) + return (self.pid, self._create_time) + else: + return (self.pid, self.create_time()) + + def __str__(self): + info = collections.OrderedDict() + info["pid"] = self.pid + if self._name: + info['name'] = self._name + with self.oneshot(): + if self._pid_reused: + info["status"] = "terminated + PID reused" + else: + try: + info["name"] = self.name() + info["status"] = self.status() + except ZombieProcess: + info["status"] = "zombie" + except NoSuchProcess: + info["status"] = "terminated" + except AccessDenied: + pass + + if self._exitcode not in {_SENTINEL, None}: + info["exitcode"] = self._exitcode + if self._create_time is not None: + info['started'] = _pprint_secs(self._create_time) + + return "{}.{}({})".format( + self.__class__.__module__, + self.__class__.__name__, + ", ".join([f"{k}={v!r}" for k, v in info.items()]), + ) + + __repr__ = __str__ + + def __eq__(self, other): + # Test for equality with another Process object based + # on PID and creation time. + if not isinstance(other, Process): + return NotImplemented + if OPENBSD or NETBSD: # pragma: no cover + # Zombie processes on Open/NetBSD have a creation time of + # 0.0. This covers the case when a process started normally + # (so it has a ctime), then it turned into a zombie. It's + # important to do this because is_running() depends on + # __eq__. + pid1, ident1 = self._ident + pid2, ident2 = other._ident + if pid1 == pid2: + if ident1 and not ident2: + try: + return self.status() == STATUS_ZOMBIE + except Error: + pass + return self._ident == other._ident + + def __ne__(self, other): + return not self == other + + def __hash__(self): + if self._hash is None: + self._hash = hash(self._ident) + return self._hash + + def _raise_if_pid_reused(self): + """Raises NoSuchProcess in case process PID has been reused.""" + if self._pid_reused or (not self.is_running() and self._pid_reused): + # We may directly raise NSP in here already if PID is just + # not running, but I prefer NSP to be raised naturally by + # the actual Process API call. This way unit tests will tell + # us if the API is broken (aka don't raise NSP when it + # should). We also remain consistent with all other "get" + # APIs which don't use _raise_if_pid_reused(). + msg = "process no longer exists and its PID has been reused" + raise NoSuchProcess(self.pid, self._name, msg=msg) + + @property + def pid(self): + """The process PID.""" + return self._pid + + # --- utility methods + + @contextlib.contextmanager + def oneshot(self): + """Utility context manager which considerably speeds up the + retrieval of multiple process information at the same time. + + Internally different process info (e.g. name, ppid, uids, + gids, ...) may be fetched by using the same routine, but + only one information is returned and the others are discarded. + When using this context manager the internal routine is + executed once (in the example below on name()) and the + other info are cached. + + The cache is cleared when exiting the context manager block. + The advice is to use this every time you retrieve more than + one information about the process. If you're lucky, you'll + get a hell of a speedup. + + >>> import psutil + >>> p = psutil.Process() + >>> with p.oneshot(): + ... p.name() # collect multiple info + ... p.cpu_times() # return cached value + ... p.cpu_percent() # return cached value + ... p.create_time() # return cached value + ... + >>> + """ + with self._lock: + if hasattr(self, "_cache"): + # NOOP: this covers the use case where the user enters the + # context twice: + # + # >>> with p.oneshot(): + # ... with p.oneshot(): + # ... + # + # Also, since as_dict() internally uses oneshot() + # I expect that the code below will be a pretty common + # "mistake" that the user will make, so let's guard + # against that: + # + # >>> with p.oneshot(): + # ... p.as_dict() + # ... + yield + else: + try: + # cached in case cpu_percent() is used + self.cpu_times.cache_activate(self) + # cached in case memory_percent() is used + self.memory_info.cache_activate(self) + # cached in case parent() is used + self.ppid.cache_activate(self) + # cached in case username() is used + if POSIX: + self.uids.cache_activate(self) + # specific implementation cache + self._proc.oneshot_enter() + yield + finally: + self.cpu_times.cache_deactivate(self) + self.memory_info.cache_deactivate(self) + self.ppid.cache_deactivate(self) + if POSIX: + self.uids.cache_deactivate(self) + self._proc.oneshot_exit() + + def as_dict(self, attrs=None, ad_value=None): + """Utility method returning process information as a + hashable dictionary. + If *attrs* is specified it must be a list of strings + reflecting available Process class' attribute names + (e.g. ['cpu_times', 'name']) else all public (read + only) attributes are assumed. + *ad_value* is the value which gets assigned in case + AccessDenied or ZombieProcess exception is raised when + retrieving that particular process information. + """ + valid_names = _as_dict_attrnames + if attrs is not None: + if not isinstance(attrs, (list, tuple, set, frozenset)): + msg = f"invalid attrs type {type(attrs)}" + raise TypeError(msg) + attrs = set(attrs) + invalid_names = attrs - valid_names + if invalid_names: + msg = "invalid attr name{} {}".format( + "s" if len(invalid_names) > 1 else "", + ", ".join(map(repr, invalid_names)), + ) + raise ValueError(msg) + + retdict = {} + ls = attrs or valid_names + with self.oneshot(): + for name in ls: + try: + if name == 'pid': + ret = self.pid + else: + meth = getattr(self, name) + ret = meth() + except (AccessDenied, ZombieProcess): + ret = ad_value + except NotImplementedError: + # in case of not implemented functionality (may happen + # on old or exotic systems) we want to crash only if + # the user explicitly asked for that particular attr + if attrs: + raise + continue + retdict[name] = ret + return retdict + + def parent(self): + """Return the parent process as a Process object pre-emptively + checking whether PID has been reused. + If no parent is known return None. + """ + lowest_pid = _LOWEST_PID if _LOWEST_PID is not None else pids()[0] + if self.pid == lowest_pid: + return None + ppid = self.ppid() + if ppid is not None: + ctime = self.create_time() + try: + parent = Process(ppid) + if parent.create_time() <= ctime: + return parent + # ...else ppid has been reused by another process + except NoSuchProcess: + pass + + def parents(self): + """Return the parents of this process as a list of Process + instances. If no parents are known return an empty list. + """ + parents = [] + proc = self.parent() + while proc is not None: + parents.append(proc) + proc = proc.parent() + return parents + + def is_running(self): + """Return whether this process is running. + + It also checks if PID has been reused by another process, in + which case it will remove the process from `process_iter()` + internal cache and return False. + """ + if self._gone or self._pid_reused: + return False + try: + # Checking if PID is alive is not enough as the PID might + # have been reused by another process. Process identity / + # uniqueness over time is guaranteed by (PID + creation + # time) and that is verified in __eq__. + self._pid_reused = self != Process(self.pid) + if self._pid_reused: + _pids_reused.add(self.pid) + raise NoSuchProcess(self.pid) + return True + except ZombieProcess: + # We should never get here as it's already handled in + # Process.__init__; here just for extra safety. + return True + except NoSuchProcess: + self._gone = True + return False + + # --- actual API + + @memoize_when_activated + def ppid(self): + """The process parent PID. + On Windows the return value is cached after first call. + """ + # On POSIX we don't want to cache the ppid as it may unexpectedly + # change to 1 (init) in case this process turns into a zombie: + # https://github.com/giampaolo/psutil/issues/321 + # http://stackoverflow.com/questions/356722/ + + # XXX should we check creation time here rather than in + # Process.parent()? + self._raise_if_pid_reused() + if POSIX: + return self._proc.ppid() + else: # pragma: no cover + self._ppid = self._ppid or self._proc.ppid() + return self._ppid + + def name(self): + """The process name. The return value is cached after first call.""" + # Process name is only cached on Windows as on POSIX it may + # change, see: + # https://github.com/giampaolo/psutil/issues/692 + if WINDOWS and self._name is not None: + return self._name + name = self._proc.name() + if POSIX and len(name) >= 15: + # On UNIX the name gets truncated to the first 15 characters. + # If it matches the first part of the cmdline we return that + # one instead because it's usually more explicative. + # Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon". + try: + cmdline = self.cmdline() + except (AccessDenied, ZombieProcess): + # Just pass and return the truncated name: it's better + # than nothing. Note: there are actual cases where a + # zombie process can return a name() but not a + # cmdline(), see: + # https://github.com/giampaolo/psutil/issues/2239 + pass + else: + if cmdline: + extended_name = os.path.basename(cmdline[0]) + if extended_name.startswith(name): + name = extended_name + self._name = name + self._proc._name = name + return name + + def exe(self): + """The process executable as an absolute path. + May also be an empty string. + The return value is cached after first call. + """ + + def guess_it(fallback): + # try to guess exe from cmdline[0] in absence of a native + # exe representation + cmdline = self.cmdline() + if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'): + exe = cmdline[0] # the possible exe + # Attempt to guess only in case of an absolute path. + # It is not safe otherwise as the process might have + # changed cwd. + if ( + os.path.isabs(exe) + and os.path.isfile(exe) + and os.access(exe, os.X_OK) + ): + return exe + if isinstance(fallback, AccessDenied): + raise fallback + return fallback + + if self._exe is None: + try: + exe = self._proc.exe() + except AccessDenied as err: + return guess_it(fallback=err) + else: + if not exe: + # underlying implementation can legitimately return an + # empty string; if that's the case we don't want to + # raise AD while guessing from the cmdline + try: + exe = guess_it(fallback=exe) + except AccessDenied: + pass + self._exe = exe + return self._exe + + def cmdline(self): + """The command line this process has been called with.""" + return self._proc.cmdline() + + def status(self): + """The process current status as a STATUS_* constant.""" + try: + return self._proc.status() + except ZombieProcess: + return STATUS_ZOMBIE + + def username(self): + """The name of the user that owns the process. + On UNIX this is calculated by using *real* process uid. + """ + if POSIX: + if pwd is None: + # might happen if python was installed from sources + msg = "requires pwd module shipped with standard python" + raise ImportError(msg) + real_uid = self.uids().real + try: + return pwd.getpwuid(real_uid).pw_name + except KeyError: + # the uid can't be resolved by the system + return str(real_uid) + else: + return self._proc.username() + + def create_time(self): + """The process creation time as a floating point number + expressed in seconds since the epoch. + The return value is cached after first call. + """ + if self._create_time is None: + self._create_time = self._proc.create_time() + return self._create_time + + def cwd(self): + """Process current working directory as an absolute path.""" + return self._proc.cwd() + + def nice(self, value=None): + """Get or set process niceness (priority).""" + if value is None: + return self._proc.nice_get() + else: + self._raise_if_pid_reused() + self._proc.nice_set(value) + + if POSIX: + + @memoize_when_activated + def uids(self): + """Return process UIDs as a (real, effective, saved) + namedtuple. + """ + return self._proc.uids() + + def gids(self): + """Return process GIDs as a (real, effective, saved) + namedtuple. + """ + return self._proc.gids() + + def terminal(self): + """The terminal associated with this process, if any, + else None. + """ + return self._proc.terminal() + + def num_fds(self): + """Return the number of file descriptors opened by this + process (POSIX only). + """ + return self._proc.num_fds() + + # Linux, BSD, AIX and Windows only + if hasattr(_psplatform.Process, "io_counters"): + + def io_counters(self): + """Return process I/O statistics as a + (read_count, write_count, read_bytes, write_bytes) + namedtuple. + Those are the number of read/write calls performed and the + amount of bytes read and written by the process. + """ + return self._proc.io_counters() + + # Linux and Windows + if hasattr(_psplatform.Process, "ionice_get"): + + def ionice(self, ioclass=None, value=None): + """Get or set process I/O niceness (priority). + + On Linux *ioclass* is one of the IOPRIO_CLASS_* constants. + *value* is a number which goes from 0 to 7. The higher the + value, the lower the I/O priority of the process. + + On Windows only *ioclass* is used and it can be set to 2 + (normal), 1 (low) or 0 (very low). + + Available on Linux and Windows > Vista only. + """ + if ioclass is None: + if value is not None: + msg = "'ioclass' argument must be specified" + raise ValueError(msg) + return self._proc.ionice_get() + else: + self._raise_if_pid_reused() + return self._proc.ionice_set(ioclass, value) + + # Linux / FreeBSD only + if hasattr(_psplatform.Process, "rlimit"): + + def rlimit(self, resource, limits=None): + """Get or set process resource limits as a (soft, hard) + tuple. + + *resource* is one of the RLIMIT_* constants. + *limits* is supposed to be a (soft, hard) tuple. + + See "man prlimit" for further info. + Available on Linux and FreeBSD only. + """ + if limits is not None: + self._raise_if_pid_reused() + return self._proc.rlimit(resource, limits) + + # Windows, Linux and FreeBSD only + if hasattr(_psplatform.Process, "cpu_affinity_get"): + + def cpu_affinity(self, cpus=None): + """Get or set process CPU affinity. + If specified, *cpus* must be a list of CPUs for which you + want to set the affinity (e.g. [0, 1]). + If an empty list is passed, all egible CPUs are assumed + (and set). + (Windows, Linux and BSD only). + """ + if cpus is None: + return sorted(set(self._proc.cpu_affinity_get())) + else: + self._raise_if_pid_reused() + if not cpus: + if hasattr(self._proc, "_get_eligible_cpus"): + cpus = self._proc._get_eligible_cpus() + else: + cpus = tuple(range(len(cpu_times(percpu=True)))) + self._proc.cpu_affinity_set(list(set(cpus))) + + # Linux, FreeBSD, SunOS + if hasattr(_psplatform.Process, "cpu_num"): + + def cpu_num(self): + """Return what CPU this process is currently running on. + The returned number should be <= psutil.cpu_count() + and <= len(psutil.cpu_percent(percpu=True)). + It may be used in conjunction with + psutil.cpu_percent(percpu=True) to observe the system + workload distributed across CPUs. + """ + return self._proc.cpu_num() + + # All platforms has it, but maybe not in the future. + if hasattr(_psplatform.Process, "environ"): + + def environ(self): + """The environment variables of the process as a dict. Note: this + might not reflect changes made after the process started. + """ + return self._proc.environ() + + if WINDOWS: + + def num_handles(self): + """Return the number of handles opened by this process + (Windows only). + """ + return self._proc.num_handles() + + def num_ctx_switches(self): + """Return the number of voluntary and involuntary context + switches performed by this process. + """ + return self._proc.num_ctx_switches() + + def num_threads(self): + """Return the number of threads used by this process.""" + return self._proc.num_threads() + + if hasattr(_psplatform.Process, "threads"): + + def threads(self): + """Return threads opened by process as a list of + (id, user_time, system_time) namedtuples representing + thread id and thread CPU times (user/system). + On OpenBSD this method requires root access. + """ + return self._proc.threads() + + def children(self, recursive=False): + """Return the children of this process as a list of Process + instances, pre-emptively checking whether PID has been reused. + If *recursive* is True return all the parent descendants. + + Example (A == this process): + + A ─┐ + │ + ├─ B (child) ─┐ + │ └─ X (grandchild) ─┐ + │ └─ Y (great grandchild) + ├─ C (child) + └─ D (child) + + >>> import psutil + >>> p = psutil.Process() + >>> p.children() + B, C, D + >>> p.children(recursive=True) + B, X, Y, C, D + + Note that in the example above if process X disappears + process Y won't be listed as the reference to process A + is lost. + """ + self._raise_if_pid_reused() + ppid_map = _ppid_map() + ret = [] + if not recursive: + for pid, ppid in ppid_map.items(): + if ppid == self.pid: + try: + child = Process(pid) + # if child happens to be older than its parent + # (self) it means child's PID has been reused + if self.create_time() <= child.create_time(): + ret.append(child) + except (NoSuchProcess, ZombieProcess): + pass + else: + # Construct a {pid: [child pids]} dict + reverse_ppid_map = collections.defaultdict(list) + for pid, ppid in ppid_map.items(): + reverse_ppid_map[ppid].append(pid) + # Recursively traverse that dict, starting from self.pid, + # such that we only call Process() on actual children + seen = set() + stack = [self.pid] + while stack: + pid = stack.pop() + if pid in seen: + # Since pids can be reused while the ppid_map is + # constructed, there may be rare instances where + # there's a cycle in the recorded process "tree". + continue + seen.add(pid) + for child_pid in reverse_ppid_map[pid]: + try: + child = Process(child_pid) + # if child happens to be older than its parent + # (self) it means child's PID has been reused + intime = self.create_time() <= child.create_time() + if intime: + ret.append(child) + stack.append(child_pid) + except (NoSuchProcess, ZombieProcess): + pass + return ret + + def cpu_percent(self, interval=None): + """Return a float representing the current process CPU + utilization as a percentage. + + When *interval* is 0.0 or None (default) compares process times + to system CPU times elapsed since last call, returning + immediately (non-blocking). That means that the first time + this is called it will return a meaningful 0.0 value. + + When *interval* is > 0.0 compares process times to system CPU + times elapsed before and after the interval (blocking). + + In this case is recommended for accuracy that this function + be called with at least 0.1 seconds between calls. + + A value > 100.0 can be returned in case of processes running + multiple threads on different CPU cores. + + The returned value is explicitly NOT split evenly between + all available logical CPUs. This means that a busy loop process + running on a system with 2 logical CPUs will be reported as + having 100% CPU utilization instead of 50%. + + Examples: + + >>> import psutil + >>> p = psutil.Process(os.getpid()) + >>> # blocking + >>> p.cpu_percent(interval=1) + 2.0 + >>> # non-blocking (percentage since last call) + >>> p.cpu_percent(interval=None) + 2.9 + >>> + """ + blocking = interval is not None and interval > 0.0 + if interval is not None and interval < 0: + msg = f"interval is not positive (got {interval!r})" + raise ValueError(msg) + num_cpus = cpu_count() or 1 + + def timer(): + return _timer() * num_cpus + + if blocking: + st1 = timer() + pt1 = self._proc.cpu_times() + time.sleep(interval) + st2 = timer() + pt2 = self._proc.cpu_times() + else: + st1 = self._last_sys_cpu_times + pt1 = self._last_proc_cpu_times + st2 = timer() + pt2 = self._proc.cpu_times() + if st1 is None or pt1 is None: + self._last_sys_cpu_times = st2 + self._last_proc_cpu_times = pt2 + return 0.0 + + delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system) + delta_time = st2 - st1 + # reset values for next call in case of interval == None + self._last_sys_cpu_times = st2 + self._last_proc_cpu_times = pt2 + + try: + # This is the utilization split evenly between all CPUs. + # E.g. a busy loop process on a 2-CPU-cores system at this + # point is reported as 50% instead of 100%. + overall_cpus_percent = (delta_proc / delta_time) * 100 + except ZeroDivisionError: + # interval was too low + return 0.0 + else: + # Note 1: + # in order to emulate "top" we multiply the value for the num + # of CPU cores. This way the busy process will be reported as + # having 100% (or more) usage. + # + # Note 2: + # taskmgr.exe on Windows differs in that it will show 50% + # instead. + # + # Note 3: + # a percentage > 100 is legitimate as it can result from a + # process with multiple threads running on different CPU + # cores (top does the same), see: + # http://stackoverflow.com/questions/1032357 + # https://github.com/giampaolo/psutil/issues/474 + single_cpu_percent = overall_cpus_percent * num_cpus + return round(single_cpu_percent, 1) + + @memoize_when_activated + def cpu_times(self): + """Return a (user, system, children_user, children_system) + namedtuple representing the accumulated process time, in + seconds. + This is similar to os.times() but per-process. + On macOS and Windows children_user and children_system are + always set to 0. + """ + return self._proc.cpu_times() + + @memoize_when_activated + def memory_info(self): + """Return a namedtuple with variable fields depending on the + platform, representing memory information about the process. + + The "portable" fields available on all platforms are `rss` and `vms`. + + All numbers are expressed in bytes. + """ + return self._proc.memory_info() + + def memory_full_info(self): + """This method returns the same information as memory_info(), + plus, on some platform (Linux, macOS, Windows), also provides + additional metrics (USS, PSS and swap). + The additional metrics provide a better representation of actual + process memory usage. + + Namely USS is the memory which is unique to a process and which + would be freed if the process was terminated right now. + + It does so by passing through the whole process address. + As such it usually requires higher user privileges than + memory_info() and is considerably slower. + """ + return self._proc.memory_full_info() + + def memory_percent(self, memtype="rss"): + """Compare process memory to total physical system memory and + calculate process memory utilization as a percentage. + *memtype* argument is a string that dictates what type of + process memory you want to compare against (defaults to "rss"). + The list of available strings can be obtained like this: + + >>> psutil.Process().memory_info()._fields + ('rss', 'vms', 'shared', 'text', 'lib', 'data', 'dirty', 'uss', 'pss') + """ + valid_types = list(_psplatform.pfullmem._fields) + if memtype not in valid_types: + msg = ( + f"invalid memtype {memtype!r}; valid types are" + f" {tuple(valid_types)!r}" + ) + raise ValueError(msg) + fun = ( + self.memory_info + if memtype in _psplatform.pmem._fields + else self.memory_full_info + ) + metrics = fun() + value = getattr(metrics, memtype) + + # use cached value if available + total_phymem = _TOTAL_PHYMEM or virtual_memory().total + if not total_phymem > 0: + # we should never get here + msg = ( + "can't calculate process memory percent because total physical" + f" system memory is not positive ({total_phymem!r})" + ) + raise ValueError(msg) + return (value / float(total_phymem)) * 100 + + if hasattr(_psplatform.Process, "memory_maps"): + + def memory_maps(self, grouped=True): + """Return process' mapped memory regions as a list of namedtuples + whose fields are variable depending on the platform. + + If *grouped* is True the mapped regions with the same 'path' + are grouped together and the different memory fields are summed. + + If *grouped* is False every mapped region is shown as a single + entity and the namedtuple will also include the mapped region's + address space ('addr') and permission set ('perms'). + """ + it = self._proc.memory_maps() + if grouped: + d = {} + for tupl in it: + path = tupl[2] + nums = tupl[3:] + try: + d[path] = list(map(lambda x, y: x + y, d[path], nums)) + except KeyError: + d[path] = nums + nt = _psplatform.pmmap_grouped + return [nt(path, *d[path]) for path in d] + else: + nt = _psplatform.pmmap_ext + return [nt(*x) for x in it] + + def open_files(self): + """Return files opened by process as a list of + (path, fd) namedtuples including the absolute file name + and file descriptor number. + """ + return self._proc.open_files() + + def net_connections(self, kind='inet'): + """Return socket connections opened by process as a list of + (fd, family, type, laddr, raddr, status) namedtuples. + The *kind* parameter filters for connections that match the + following criteria: + + +------------+----------------------------------------------------+ + | Kind Value | Connections using | + +------------+----------------------------------------------------+ + | inet | IPv4 and IPv6 | + | inet4 | IPv4 | + | inet6 | IPv6 | + | tcp | TCP | + | tcp4 | TCP over IPv4 | + | tcp6 | TCP over IPv6 | + | udp | UDP | + | udp4 | UDP over IPv4 | + | udp6 | UDP over IPv6 | + | unix | UNIX socket (both UDP and TCP protocols) | + | all | the sum of all the possible families and protocols | + +------------+----------------------------------------------------+ + """ + _check_conn_kind(kind) + return self._proc.net_connections(kind) + + @_common.deprecated_method(replacement="net_connections") + def connections(self, kind="inet"): + return self.net_connections(kind=kind) + + # --- signals + + if POSIX: + + def _send_signal(self, sig): + assert not self.pid < 0, self.pid + self._raise_if_pid_reused() + + pid, ppid, name = self.pid, self._ppid, self._name + if pid == 0: + # see "man 2 kill" + msg = ( + "preventing sending signal to process with PID 0 as it " + "would affect every process in the process group of the " + "calling process (os.getpid()) instead of PID 0" + ) + raise ValueError(msg) + try: + os.kill(pid, sig) + except ProcessLookupError as err: + if OPENBSD and pid_exists(pid): + # We do this because os.kill() lies in case of + # zombie processes. + raise ZombieProcess(pid, name, ppid) from err + self._gone = True + raise NoSuchProcess(pid, name) from err + except PermissionError as err: + raise AccessDenied(pid, name) from err + + def send_signal(self, sig): + """Send a signal *sig* to process pre-emptively checking + whether PID has been reused (see signal module constants) . + On Windows only SIGTERM is valid and is treated as an alias + for kill(). + """ + if POSIX: + self._send_signal(sig) + else: # pragma: no cover + self._raise_if_pid_reused() + if sig != signal.SIGTERM and not self.is_running(): + msg = "process no longer exists" + raise NoSuchProcess(self.pid, self._name, msg=msg) + self._proc.send_signal(sig) + + def suspend(self): + """Suspend process execution with SIGSTOP pre-emptively checking + whether PID has been reused. + On Windows this has the effect of suspending all process threads. + """ + if POSIX: + self._send_signal(signal.SIGSTOP) + else: # pragma: no cover + self._raise_if_pid_reused() + self._proc.suspend() + + def resume(self): + """Resume process execution with SIGCONT pre-emptively checking + whether PID has been reused. + On Windows this has the effect of resuming all process threads. + """ + if POSIX: + self._send_signal(signal.SIGCONT) + else: # pragma: no cover + self._raise_if_pid_reused() + self._proc.resume() + + def terminate(self): + """Terminate the process with SIGTERM pre-emptively checking + whether PID has been reused. + On Windows this is an alias for kill(). + """ + if POSIX: + self._send_signal(signal.SIGTERM) + else: # pragma: no cover + self._raise_if_pid_reused() + self._proc.kill() + + def kill(self): + """Kill the current process with SIGKILL pre-emptively checking + whether PID has been reused. + """ + if POSIX: + self._send_signal(signal.SIGKILL) + else: # pragma: no cover + self._raise_if_pid_reused() + self._proc.kill() + + def wait(self, timeout=None): + """Wait for process to terminate and, if process is a children + of os.getpid(), also return its exit code, else None. + On Windows there's no such limitation (exit code is always + returned). + + If the process is already terminated immediately return None + instead of raising NoSuchProcess. + + If *timeout* (in seconds) is specified and process is still + alive raise TimeoutExpired. + + To wait for multiple Process(es) use psutil.wait_procs(). + """ + if timeout is not None and not timeout >= 0: + msg = "timeout must be a positive integer" + raise ValueError(msg) + if self._exitcode is not _SENTINEL: + return self._exitcode + self._exitcode = self._proc.wait(timeout) + return self._exitcode + + +# The valid attr names which can be processed by Process.as_dict(). +# fmt: off +_as_dict_attrnames = { + x for x in dir(Process) if not x.startswith("_") and x not in + {'send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait', + 'is_running', 'as_dict', 'parent', 'parents', 'children', 'rlimit', + 'connections', 'oneshot'} +} +# fmt: on + + +# ===================================================================== +# --- Popen class +# ===================================================================== + + +class Popen(Process): + """Same as subprocess.Popen, but in addition it provides all + psutil.Process methods in a single class. + For the following methods which are common to both classes, psutil + implementation takes precedence: + + * send_signal() + * terminate() + * kill() + + This is done in order to avoid killing another process in case its + PID has been reused, fixing BPO-6973. + + >>> import psutil + >>> from subprocess import PIPE + >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE) + >>> p.name() + 'python' + >>> p.uids() + user(real=1000, effective=1000, saved=1000) + >>> p.username() + 'giampaolo' + >>> p.communicate() + ('hi', None) + >>> p.terminate() + >>> p.wait(timeout=2) + 0 + >>> + """ + + def __init__(self, *args, **kwargs): + # Explicitly avoid to raise NoSuchProcess in case the process + # spawned by subprocess.Popen terminates too quickly, see: + # https://github.com/giampaolo/psutil/issues/193 + self.__subproc = subprocess.Popen(*args, **kwargs) + self._init(self.__subproc.pid, _ignore_nsp=True) + + def __dir__(self): + return sorted(set(dir(Popen) + dir(subprocess.Popen))) + + def __enter__(self): + if hasattr(self.__subproc, '__enter__'): + self.__subproc.__enter__() + return self + + def __exit__(self, *args, **kwargs): + if hasattr(self.__subproc, '__exit__'): + return self.__subproc.__exit__(*args, **kwargs) + else: + if self.stdout: + self.stdout.close() + if self.stderr: + self.stderr.close() + try: + # Flushing a BufferedWriter may raise an error. + if self.stdin: + self.stdin.close() + finally: + # Wait for the process to terminate, to avoid zombies. + self.wait() + + def __getattribute__(self, name): + try: + return object.__getattribute__(self, name) + except AttributeError: + try: + return object.__getattribute__(self.__subproc, name) + except AttributeError: + msg = f"{self.__class__!r} has no attribute {name!r}" + raise AttributeError(msg) from None + + def wait(self, timeout=None): + if self.__subproc.returncode is not None: + return self.__subproc.returncode + ret = super().wait(timeout) + self.__subproc.returncode = ret + return ret + + +# ===================================================================== +# --- system processes related functions +# ===================================================================== + + +def pids(): + """Return a list of current running PIDs.""" + global _LOWEST_PID + ret = sorted(_psplatform.pids()) + _LOWEST_PID = ret[0] + return ret + + +def pid_exists(pid): + """Return True if given PID exists in the current process list. + This is faster than doing "pid in psutil.pids()" and + should be preferred. + """ + if pid < 0: + return False + elif pid == 0 and POSIX: + # On POSIX we use os.kill() to determine PID existence. + # According to "man 2 kill" PID 0 has a special meaning + # though: it refers to <> and that is not we want + # to do here. + return pid in pids() + else: + return _psplatform.pid_exists(pid) + + +_pmap = {} +_pids_reused = set() + + +def process_iter(attrs=None, ad_value=None): + """Return a generator yielding a Process instance for all + running processes. + + Every new Process instance is only created once and then cached + into an internal table which is updated every time this is used. + Cache can optionally be cleared via `process_iter.clear_cache()`. + + The sorting order in which processes are yielded is based on + their PIDs. + + *attrs* and *ad_value* have the same meaning as in + Process.as_dict(). If *attrs* is specified as_dict() is called + and the resulting dict is stored as a 'info' attribute attached + to returned Process instance. + If *attrs* is an empty list it will retrieve all process info + (slow). + """ + global _pmap + + def add(pid): + proc = Process(pid) + pmap[proc.pid] = proc + return proc + + def remove(pid): + pmap.pop(pid, None) + + pmap = _pmap.copy() + a = set(pids()) + b = set(pmap.keys()) + new_pids = a - b + gone_pids = b - a + for pid in gone_pids: + remove(pid) + while _pids_reused: + pid = _pids_reused.pop() + debug(f"refreshing Process instance for reused PID {pid}") + remove(pid) + try: + ls = sorted(list(pmap.items()) + list(dict.fromkeys(new_pids).items())) + for pid, proc in ls: + try: + if proc is None: # new process + proc = add(pid) + if attrs is not None: + proc.info = proc.as_dict(attrs=attrs, ad_value=ad_value) + yield proc + except NoSuchProcess: + remove(pid) + finally: + _pmap = pmap + + +process_iter.cache_clear = lambda: _pmap.clear() # noqa: PLW0108 +process_iter.cache_clear.__doc__ = "Clear process_iter() internal cache." + + +def wait_procs(procs, timeout=None, callback=None): + """Convenience function which waits for a list of processes to + terminate. + + Return a (gone, alive) tuple indicating which processes + are gone and which ones are still alive. + + The gone ones will have a new *returncode* attribute indicating + process exit status (may be None). + + *callback* is a function which gets called every time a process + terminates (a Process instance is passed as callback argument). + + Function will return as soon as all processes terminate or when + *timeout* occurs. + Differently from Process.wait() it will not raise TimeoutExpired if + *timeout* occurs. + + Typical use case is: + + - send SIGTERM to a list of processes + - give them some time to terminate + - send SIGKILL to those ones which are still alive + + Example: + + >>> def on_terminate(proc): + ... print("process {} terminated".format(proc)) + ... + >>> for p in procs: + ... p.terminate() + ... + >>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate) + >>> for p in alive: + ... p.kill() + """ + + def check_gone(proc, timeout): + try: + returncode = proc.wait(timeout=timeout) + except (TimeoutExpired, subprocess.TimeoutExpired): + pass + else: + if returncode is not None or not proc.is_running(): + # Set new Process instance attribute. + proc.returncode = returncode + gone.add(proc) + if callback is not None: + callback(proc) + + if timeout is not None and not timeout >= 0: + msg = f"timeout must be a positive integer, got {timeout}" + raise ValueError(msg) + gone = set() + alive = set(procs) + if callback is not None and not callable(callback): + msg = f"callback {callback!r} is not a callable" + raise TypeError(msg) + if timeout is not None: + deadline = _timer() + timeout + + while alive: + if timeout is not None and timeout <= 0: + break + for proc in alive: + # Make sure that every complete iteration (all processes) + # will last max 1 sec. + # We do this because we don't want to wait too long on a + # single process: in case it terminates too late other + # processes may disappear in the meantime and their PID + # reused. + max_timeout = 1.0 / len(alive) + if timeout is not None: + timeout = min((deadline - _timer()), max_timeout) + if timeout <= 0: + break + check_gone(proc, timeout) + else: + check_gone(proc, max_timeout) + alive = alive - gone # noqa: PLR6104 + + if alive: + # Last attempt over processes survived so far. + # timeout == 0 won't make this function wait any further. + for proc in alive: + check_gone(proc, 0) + alive = alive - gone # noqa: PLR6104 + + return (list(gone), list(alive)) + + +# ===================================================================== +# --- CPU related functions +# ===================================================================== + + +def cpu_count(logical=True): + """Return the number of logical CPUs in the system (same as + os.cpu_count()). + + If *logical* is False return the number of physical cores only + (e.g. hyper thread CPUs are excluded). + + Return None if undetermined. + + The return value is cached after first call. + If desired cache can be cleared like this: + + >>> psutil.cpu_count.cache_clear() + """ + if logical: + ret = _psplatform.cpu_count_logical() + else: + ret = _psplatform.cpu_count_cores() + if ret is not None and ret < 1: + ret = None + return ret + + +def cpu_times(percpu=False): + """Return system-wide CPU times as a namedtuple. + Every CPU time represents the seconds the CPU has spent in the + given mode. The namedtuple's fields availability varies depending on the + platform: + + - user + - system + - idle + - nice (UNIX) + - iowait (Linux) + - irq (Linux, FreeBSD) + - softirq (Linux) + - steal (Linux >= 2.6.11) + - guest (Linux >= 2.6.24) + - guest_nice (Linux >= 3.2.0) + + When *percpu* is True return a list of namedtuples for each CPU. + First element of the list refers to first CPU, second element + to second CPU and so on. + The order of the list is consistent across calls. + """ + if not percpu: + return _psplatform.cpu_times() + else: + return _psplatform.per_cpu_times() + + +try: + _last_cpu_times = {threading.current_thread().ident: cpu_times()} +except Exception: # noqa: BLE001 + # Don't want to crash at import time. + _last_cpu_times = {} + +try: + _last_per_cpu_times = { + threading.current_thread().ident: cpu_times(percpu=True) + } +except Exception: # noqa: BLE001 + # Don't want to crash at import time. + _last_per_cpu_times = {} + + +def _cpu_tot_time(times): + """Given a cpu_time() ntuple calculates the total CPU time + (including idle time). + """ + tot = sum(times) + if LINUX: + # On Linux guest times are already accounted in "user" or + # "nice" times, so we subtract them from total. + # Htop does the same. References: + # https://github.com/giampaolo/psutil/pull/940 + # http://unix.stackexchange.com/questions/178045 + # https://github.com/torvalds/linux/blob/ + # 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/ + # cputime.c#L158 + tot -= getattr(times, "guest", 0) # Linux 2.6.24+ + tot -= getattr(times, "guest_nice", 0) # Linux 3.2.0+ + return tot + + +def _cpu_busy_time(times): + """Given a cpu_time() ntuple calculates the busy CPU time. + We do so by subtracting all idle CPU times. + """ + busy = _cpu_tot_time(times) + busy -= times.idle + # Linux: "iowait" is time during which the CPU does not do anything + # (waits for IO to complete). On Linux IO wait is *not* accounted + # in "idle" time so we subtract it. Htop does the same. + # References: + # https://github.com/torvalds/linux/blob/ + # 447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244 + busy -= getattr(times, "iowait", 0) + return busy + + +def _cpu_times_deltas(t1, t2): + assert t1._fields == t2._fields, (t1, t2) + field_deltas = [] + for field in _psplatform.scputimes._fields: + field_delta = getattr(t2, field) - getattr(t1, field) + # CPU times are always supposed to increase over time + # or at least remain the same and that's because time + # cannot go backwards. + # Surprisingly sometimes this might not be the case (at + # least on Windows and Linux), see: + # https://github.com/giampaolo/psutil/issues/392 + # https://github.com/giampaolo/psutil/issues/645 + # https://github.com/giampaolo/psutil/issues/1210 + # Trim negative deltas to zero to ignore decreasing fields. + # top does the same. Reference: + # https://gitlab.com/procps-ng/procps/blob/v3.3.12/top/top.c#L5063 + field_delta = max(0, field_delta) + field_deltas.append(field_delta) + return _psplatform.scputimes(*field_deltas) + + +def cpu_percent(interval=None, percpu=False): + """Return a float representing the current system-wide CPU + utilization as a percentage. + + When *interval* is > 0.0 compares system CPU times elapsed before + and after the interval (blocking). + + When *interval* is 0.0 or None compares system CPU times elapsed + since last call or module import, returning immediately (non + blocking). That means the first time this is called it will + return a meaningless 0.0 value which you should ignore. + In this case is recommended for accuracy that this function be + called with at least 0.1 seconds between calls. + + When *percpu* is True returns a list of floats representing the + utilization as a percentage for each CPU. + First element of the list refers to first CPU, second element + to second CPU and so on. + The order of the list is consistent across calls. + + Examples: + + >>> # blocking, system-wide + >>> psutil.cpu_percent(interval=1) + 2.0 + >>> + >>> # blocking, per-cpu + >>> psutil.cpu_percent(interval=1, percpu=True) + [2.0, 1.0] + >>> + >>> # non-blocking (percentage since last call) + >>> psutil.cpu_percent(interval=None) + 2.9 + >>> + """ + tid = threading.current_thread().ident + blocking = interval is not None and interval > 0.0 + if interval is not None and interval < 0: + msg = f"interval is not positive (got {interval})" + raise ValueError(msg) + + def calculate(t1, t2): + times_delta = _cpu_times_deltas(t1, t2) + all_delta = _cpu_tot_time(times_delta) + busy_delta = _cpu_busy_time(times_delta) + + try: + busy_perc = (busy_delta / all_delta) * 100 + except ZeroDivisionError: + return 0.0 + else: + return round(busy_perc, 1) + + # system-wide usage + if not percpu: + if blocking: + t1 = cpu_times() + time.sleep(interval) + else: + t1 = _last_cpu_times.get(tid) or cpu_times() + _last_cpu_times[tid] = cpu_times() + return calculate(t1, _last_cpu_times[tid]) + # per-cpu usage + else: + ret = [] + if blocking: + tot1 = cpu_times(percpu=True) + time.sleep(interval) + else: + tot1 = _last_per_cpu_times.get(tid) or cpu_times(percpu=True) + _last_per_cpu_times[tid] = cpu_times(percpu=True) + for t1, t2 in zip(tot1, _last_per_cpu_times[tid]): + ret.append(calculate(t1, t2)) + return ret + + +# Use a separate dict for cpu_times_percent(), so it's independent from +# cpu_percent() and they can both be used within the same program. +_last_cpu_times_2 = _last_cpu_times.copy() +_last_per_cpu_times_2 = _last_per_cpu_times.copy() + + +def cpu_times_percent(interval=None, percpu=False): + """Same as cpu_percent() but provides utilization percentages + for each specific CPU time as is returned by cpu_times(). + For instance, on Linux we'll get: + + >>> cpu_times_percent() + cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0, + irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0) + >>> + + *interval* and *percpu* arguments have the same meaning as in + cpu_percent(). + """ + tid = threading.current_thread().ident + blocking = interval is not None and interval > 0.0 + if interval is not None and interval < 0: + msg = f"interval is not positive (got {interval!r})" + raise ValueError(msg) + + def calculate(t1, t2): + nums = [] + times_delta = _cpu_times_deltas(t1, t2) + all_delta = _cpu_tot_time(times_delta) + # "scale" is the value to multiply each delta with to get percentages. + # We use "max" to avoid division by zero (if all_delta is 0, then all + # fields are 0 so percentages will be 0 too. all_delta cannot be a + # fraction because cpu times are integers) + scale = 100.0 / max(1, all_delta) + for field_delta in times_delta: + field_perc = field_delta * scale + field_perc = round(field_perc, 1) + # make sure we don't return negative values or values over 100% + field_perc = min(max(0.0, field_perc), 100.0) + nums.append(field_perc) + return _psplatform.scputimes(*nums) + + # system-wide usage + if not percpu: + if blocking: + t1 = cpu_times() + time.sleep(interval) + else: + t1 = _last_cpu_times_2.get(tid) or cpu_times() + _last_cpu_times_2[tid] = cpu_times() + return calculate(t1, _last_cpu_times_2[tid]) + # per-cpu usage + else: + ret = [] + if blocking: + tot1 = cpu_times(percpu=True) + time.sleep(interval) + else: + tot1 = _last_per_cpu_times_2.get(tid) or cpu_times(percpu=True) + _last_per_cpu_times_2[tid] = cpu_times(percpu=True) + for t1, t2 in zip(tot1, _last_per_cpu_times_2[tid]): + ret.append(calculate(t1, t2)) + return ret + + +def cpu_stats(): + """Return CPU statistics.""" + return _psplatform.cpu_stats() + + +if hasattr(_psplatform, "cpu_freq"): + + def cpu_freq(percpu=False): + """Return CPU frequency as a namedtuple including current, + min and max frequency expressed in Mhz. + + If *percpu* is True and the system supports per-cpu frequency + retrieval (Linux only) a list of frequencies is returned for + each CPU. If not a list with one element is returned. + """ + ret = _psplatform.cpu_freq() + if percpu: + return ret + else: + num_cpus = float(len(ret)) + if num_cpus == 0: + return None + elif num_cpus == 1: + return ret[0] + else: + currs, mins, maxs = 0.0, 0.0, 0.0 + set_none = False + for cpu in ret: + currs += cpu.current + # On Linux if /proc/cpuinfo is used min/max are set + # to None. + if LINUX and cpu.min is None: + set_none = True + continue + mins += cpu.min + maxs += cpu.max + + current = currs / num_cpus + + if set_none: + min_ = max_ = None + else: + min_ = mins / num_cpus + max_ = maxs / num_cpus + + return _common.scpufreq(current, min_, max_) + + __all__.append("cpu_freq") + + +if hasattr(os, "getloadavg") or hasattr(_psplatform, "getloadavg"): + # Perform this hasattr check once on import time to either use the + # platform based code or proxy straight from the os module. + if hasattr(os, "getloadavg"): + getloadavg = os.getloadavg + else: + getloadavg = _psplatform.getloadavg + + __all__.append("getloadavg") + + +# ===================================================================== +# --- system memory related functions +# ===================================================================== + + +def virtual_memory(): + """Return statistics about system memory usage as a namedtuple + including the following fields, expressed in bytes: + + - total: + total physical memory available. + + - available: + the memory that can be given instantly to processes without the + system going into swap. + This is calculated by summing different memory values depending + on the platform and it is supposed to be used to monitor actual + memory usage in a cross platform fashion. + + - percent: + the percentage usage calculated as (total - available) / total * 100 + + - used: + memory used, calculated differently depending on the platform and + designed for informational purposes only: + macOS: active + wired + BSD: active + wired + cached + Linux: total - free + + - free: + memory not being used at all (zeroed) that is readily available; + note that this doesn't reflect the actual memory available + (use 'available' instead) + + Platform-specific fields: + + - active (UNIX): + memory currently in use or very recently used, and so it is in RAM. + + - inactive (UNIX): + memory that is marked as not used. + + - buffers (BSD, Linux): + cache for things like file system metadata. + + - cached (BSD, macOS): + cache for various things. + + - wired (macOS, BSD): + memory that is marked to always stay in RAM. It is never moved to disk. + + - shared (BSD): + memory that may be simultaneously accessed by multiple processes. + + The sum of 'used' and 'available' does not necessarily equal total. + On Windows 'available' and 'free' are the same. + """ + global _TOTAL_PHYMEM + ret = _psplatform.virtual_memory() + # cached for later use in Process.memory_percent() + _TOTAL_PHYMEM = ret.total + return ret + + +def swap_memory(): + """Return system swap memory statistics as a namedtuple including + the following fields: + + - total: total swap memory in bytes + - used: used swap memory in bytes + - free: free swap memory in bytes + - percent: the percentage usage + - sin: no. of bytes the system has swapped in from disk (cumulative) + - sout: no. of bytes the system has swapped out from disk (cumulative) + + 'sin' and 'sout' on Windows are meaningless and always set to 0. + """ + return _psplatform.swap_memory() + + +# ===================================================================== +# --- disks/partitions related functions +# ===================================================================== + + +def disk_usage(path): + """Return disk usage statistics about the given *path* as a + namedtuple including total, used and free space expressed in bytes + plus the percentage usage. + """ + return _psplatform.disk_usage(path) + + +def disk_partitions(all=False): + """Return mounted partitions as a list of + (device, mountpoint, fstype, opts) namedtuple. + 'opts' field is a raw string separated by commas indicating mount + options which may vary depending on the platform. + + If *all* parameter is False return physical devices only and ignore + all others. + """ + return _psplatform.disk_partitions(all) + + +def disk_io_counters(perdisk=False, nowrap=True): + """Return system disk I/O statistics as a namedtuple including + the following fields: + + - read_count: number of reads + - write_count: number of writes + - read_bytes: number of bytes read + - write_bytes: number of bytes written + - read_time: time spent reading from disk (in ms) + - write_time: time spent writing to disk (in ms) + + Platform specific: + + - busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms) + - read_merged_count (Linux): number of merged reads + - write_merged_count (Linux): number of merged writes + + If *perdisk* is True return the same information for every + physical disk installed on the system as a dictionary + with partition names as the keys and the namedtuple + described above as the values. + + If *nowrap* is True it detects and adjust the numbers which overflow + and wrap (restart from 0) and add "old value" to "new value" so that + the returned numbers will always be increasing or remain the same, + but never decrease. + "disk_io_counters.cache_clear()" can be used to invalidate the + cache. + + On recent Windows versions 'diskperf -y' command may need to be + executed first otherwise this function won't find any disk. + """ + kwargs = dict(perdisk=perdisk) if LINUX else {} + rawdict = _psplatform.disk_io_counters(**kwargs) + if not rawdict: + return {} if perdisk else None + if nowrap: + rawdict = _wrap_numbers(rawdict, 'psutil.disk_io_counters') + nt = getattr(_psplatform, "sdiskio", _common.sdiskio) + if perdisk: + for disk, fields in rawdict.items(): + rawdict[disk] = nt(*fields) + return rawdict + else: + return nt(*(sum(x) for x in zip(*rawdict.values()))) + + +disk_io_counters.cache_clear = functools.partial( + _wrap_numbers.cache_clear, 'psutil.disk_io_counters' +) +disk_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache" + + +# ===================================================================== +# --- network related functions +# ===================================================================== + + +def net_io_counters(pernic=False, nowrap=True): + """Return network I/O statistics as a namedtuple including + the following fields: + + - bytes_sent: number of bytes sent + - bytes_recv: number of bytes received + - packets_sent: number of packets sent + - packets_recv: number of packets received + - errin: total number of errors while receiving + - errout: total number of errors while sending + - dropin: total number of incoming packets which were dropped + - dropout: total number of outgoing packets which were dropped + (always 0 on macOS and BSD) + + If *pernic* is True return the same information for every + network interface installed on the system as a dictionary + with network interface names as the keys and the namedtuple + described above as the values. + + If *nowrap* is True it detects and adjust the numbers which overflow + and wrap (restart from 0) and add "old value" to "new value" so that + the returned numbers will always be increasing or remain the same, + but never decrease. + "net_io_counters.cache_clear()" can be used to invalidate the + cache. + """ + rawdict = _psplatform.net_io_counters() + if not rawdict: + return {} if pernic else None + if nowrap: + rawdict = _wrap_numbers(rawdict, 'psutil.net_io_counters') + if pernic: + for nic, fields in rawdict.items(): + rawdict[nic] = _common.snetio(*fields) + return rawdict + else: + return _common.snetio(*[sum(x) for x in zip(*rawdict.values())]) + + +net_io_counters.cache_clear = functools.partial( + _wrap_numbers.cache_clear, 'psutil.net_io_counters' +) +net_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache" + + +def net_connections(kind='inet'): + """Return system-wide socket connections as a list of + (fd, family, type, laddr, raddr, status, pid) namedtuples. + In case of limited privileges 'fd' and 'pid' may be set to -1 + and None respectively. + The *kind* parameter filters for connections that fit the + following criteria: + + +------------+----------------------------------------------------+ + | Kind Value | Connections using | + +------------+----------------------------------------------------+ + | inet | IPv4 and IPv6 | + | inet4 | IPv4 | + | inet6 | IPv6 | + | tcp | TCP | + | tcp4 | TCP over IPv4 | + | tcp6 | TCP over IPv6 | + | udp | UDP | + | udp4 | UDP over IPv4 | + | udp6 | UDP over IPv6 | + | unix | UNIX socket (both UDP and TCP protocols) | + | all | the sum of all the possible families and protocols | + +------------+----------------------------------------------------+ + + On macOS this function requires root privileges. + """ + _check_conn_kind(kind) + return _psplatform.net_connections(kind) + + +def net_if_addrs(): + """Return the addresses associated to each NIC (network interface + card) installed on the system as a dictionary whose keys are the + NIC names and value is a list of namedtuples for each address + assigned to the NIC. Each namedtuple includes 5 fields: + + - family: can be either socket.AF_INET, socket.AF_INET6 or + psutil.AF_LINK, which refers to a MAC address. + - address: is the primary address and it is always set. + - netmask: and 'broadcast' and 'ptp' may be None. + - ptp: stands for "point to point" and references the + destination address on a point to point interface + (typically a VPN). + - broadcast: and *ptp* are mutually exclusive. + + Note: you can have more than one address of the same family + associated with each interface. + """ + rawlist = _psplatform.net_if_addrs() + rawlist.sort(key=lambda x: x[1]) # sort by family + ret = collections.defaultdict(list) + for name, fam, addr, mask, broadcast, ptp in rawlist: + try: + fam = socket.AddressFamily(fam) + except ValueError: + if WINDOWS and fam == -1: + fam = _psplatform.AF_LINK + elif ( + hasattr(_psplatform, "AF_LINK") and fam == _psplatform.AF_LINK + ): + # Linux defines AF_LINK as an alias for AF_PACKET. + # We re-set the family here so that repr(family) + # will show AF_LINK rather than AF_PACKET + fam = _psplatform.AF_LINK + + if fam == _psplatform.AF_LINK: + # The underlying C function may return an incomplete MAC + # address in which case we fill it with null bytes, see: + # https://github.com/giampaolo/psutil/issues/786 + separator = ":" if POSIX else "-" + while addr.count(separator) < 5: + addr += f"{separator}00" + + nt = _common.snicaddr(fam, addr, mask, broadcast, ptp) + + # On Windows broadcast is None, so we determine it via + # ipaddress module. + if WINDOWS and fam in {socket.AF_INET, socket.AF_INET6}: + try: + broadcast = _common.broadcast_addr(nt) + except Exception as err: # noqa: BLE001 + debug(err) + else: + if broadcast is not None: + nt._replace(broadcast=broadcast) + + ret[name].append(nt) + + return dict(ret) + + +def net_if_stats(): + """Return information about each NIC (network interface card) + installed on the system as a dictionary whose keys are the + NIC names and value is a namedtuple with the following fields: + + - isup: whether the interface is up (bool) + - duplex: can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or + NIC_DUPLEX_UNKNOWN + - speed: the NIC speed expressed in mega bits (MB); if it can't + be determined (e.g. 'localhost') it will be set to 0. + - mtu: the maximum transmission unit expressed in bytes. + """ + return _psplatform.net_if_stats() + + +# ===================================================================== +# --- sensors +# ===================================================================== + + +# Linux, macOS +if hasattr(_psplatform, "sensors_temperatures"): + + def sensors_temperatures(fahrenheit=False): + """Return hardware temperatures. Each entry is a namedtuple + representing a certain hardware sensor (it may be a CPU, an + hard disk or something else, depending on the OS and its + configuration). + All temperatures are expressed in celsius unless *fahrenheit* + is set to True. + """ + + def convert(n): + if n is not None: + return (float(n) * 9 / 5) + 32 if fahrenheit else n + + ret = collections.defaultdict(list) + rawdict = _psplatform.sensors_temperatures() + + for name, values in rawdict.items(): + while values: + label, current, high, critical = values.pop(0) + current = convert(current) + high = convert(high) + critical = convert(critical) + + if high and not critical: + critical = high + elif critical and not high: + high = critical + + ret[name].append( + _common.shwtemp(label, current, high, critical) + ) + + return dict(ret) + + __all__.append("sensors_temperatures") + + +# Linux +if hasattr(_psplatform, "sensors_fans"): + + def sensors_fans(): + """Return fans speed. Each entry is a namedtuple + representing a certain hardware sensor. + All speed are expressed in RPM (rounds per minute). + """ + return _psplatform.sensors_fans() + + __all__.append("sensors_fans") + + +# Linux, Windows, FreeBSD, macOS +if hasattr(_psplatform, "sensors_battery"): + + def sensors_battery(): + """Return battery information. If no battery is installed + returns None. + + - percent: battery power left as a percentage. + - secsleft: a rough approximation of how many seconds are left + before the battery runs out of power. May be + POWER_TIME_UNLIMITED or POWER_TIME_UNLIMITED. + - power_plugged: True if the AC power cable is connected. + """ + return _psplatform.sensors_battery() + + __all__.append("sensors_battery") + + +# ===================================================================== +# --- other system related functions +# ===================================================================== + + +def boot_time(): + """Return the system boot time expressed in seconds since the epoch.""" + # Note: we are not caching this because it is subject to + # system clock updates. + return _psplatform.boot_time() + + +def users(): + """Return users currently connected on the system as a list of + namedtuples including the following fields. + + - user: the name of the user + - terminal: the tty or pseudo-tty associated with the user, if any. + - host: the host name associated with the entry, if any. + - started: the creation time as a floating point number expressed in + seconds since the epoch. + """ + return _psplatform.users() + + +# ===================================================================== +# --- Windows services +# ===================================================================== + + +if WINDOWS: + + def win_service_iter(): + """Return a generator yielding a WindowsService instance for all + Windows services installed. + """ + return _psplatform.win_service_iter() + + def win_service_get(name): + """Get a Windows service by *name*. + Raise NoSuchProcess if no service with such name exists. + """ + return _psplatform.win_service_get(name) + + +# ===================================================================== + + +def _set_debug(value): + """Enable or disable PSUTIL_DEBUG option, which prints debugging + messages to stderr. + """ + import psutil._common + + psutil._common.PSUTIL_DEBUG = bool(value) + _psplatform.cext.set_debug(bool(value)) + + +del memoize_when_activated diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3162cfe1a64c33d6a7911342c460e44598df9c8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_common.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ffab57c18062a48e086bb03f36e81a8bb7ac405 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_common.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psaix.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psaix.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24e7d25adc76fffb0d6d45c58fb8365d70a85472 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psaix.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psbsd.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psbsd.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcba31e92016830590d518692dc2c47003033c72 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psbsd.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_pslinux.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_pslinux.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a51bed8b56dcb3c57ef3ab3d8cbf3d719a397dee Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_pslinux.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psosx.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psosx.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5f3a6acb796ae4a212938451d4b3bc9d5635839 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psosx.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psposix.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psposix.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97b30ad0b36487e2f43e85d2b4e256804480008e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_psposix.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_pssunos.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_pssunos.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec6d8ce712d437e1f84e895805763fe4340c9be7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_pssunos.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_pswindows.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_pswindows.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8036456a444625eb99daf3fb97815e7170756d37 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/__pycache__/_pswindows.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_common.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..4096c0a18c8f8d665cba842d6898bac51bd48f0b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_common.py @@ -0,0 +1,950 @@ +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Common objects shared by __init__.py and _ps*.py modules. + +Note: this module is imported by setup.py, so it should not import +psutil or third-party modules. +""" + +import collections +import enum +import functools +import os +import socket +import stat +import sys +import threading +import warnings +from collections import namedtuple +from socket import AF_INET +from socket import SOCK_DGRAM +from socket import SOCK_STREAM + + +try: + from socket import AF_INET6 +except ImportError: + AF_INET6 = None +try: + from socket import AF_UNIX +except ImportError: + AF_UNIX = None + + +PSUTIL_DEBUG = bool(os.getenv('PSUTIL_DEBUG')) +_DEFAULT = object() + +# fmt: off +__all__ = [ + # OS constants + 'FREEBSD', 'BSD', 'LINUX', 'NETBSD', 'OPENBSD', 'MACOS', 'OSX', 'POSIX', + 'SUNOS', 'WINDOWS', + # connection constants + 'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED', + 'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN', + 'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT', + # net constants + 'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN', # noqa: F822 + # process status constants + 'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED', + 'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_SUSPENDED', + 'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKE_KILL', + 'STATUS_WAKING', 'STATUS_ZOMBIE', 'STATUS_PARKED', + # other constants + 'ENCODING', 'ENCODING_ERRS', 'AF_INET6', + # named tuples + 'pconn', 'pcputimes', 'pctxsw', 'pgids', 'pio', 'pionice', 'popenfile', + 'pthread', 'puids', 'sconn', 'scpustats', 'sdiskio', 'sdiskpart', + 'sdiskusage', 'snetio', 'snicaddr', 'snicstats', 'sswap', 'suser', + # utility functions + 'conn_tmap', 'deprecated_method', 'isfile_strict', 'memoize', + 'parse_environ_block', 'path_exists_strict', 'usage_percent', + 'supports_ipv6', 'sockfam_to_enum', 'socktype_to_enum', "wrap_numbers", + 'open_text', 'open_binary', 'cat', 'bcat', + 'bytes2human', 'conn_to_ntuple', 'debug', + # shell utils + 'hilite', 'term_supports_colors', 'print_color', +] +# fmt: on + + +# =================================================================== +# --- OS constants +# =================================================================== + + +POSIX = os.name == "posix" +WINDOWS = os.name == "nt" +LINUX = sys.platform.startswith("linux") +MACOS = sys.platform.startswith("darwin") +OSX = MACOS # deprecated alias +FREEBSD = sys.platform.startswith(("freebsd", "midnightbsd")) +OPENBSD = sys.platform.startswith("openbsd") +NETBSD = sys.platform.startswith("netbsd") +BSD = FREEBSD or OPENBSD or NETBSD +SUNOS = sys.platform.startswith(("sunos", "solaris")) +AIX = sys.platform.startswith("aix") + + +# =================================================================== +# --- API constants +# =================================================================== + + +# Process.status() +STATUS_RUNNING = "running" +STATUS_SLEEPING = "sleeping" +STATUS_DISK_SLEEP = "disk-sleep" +STATUS_STOPPED = "stopped" +STATUS_TRACING_STOP = "tracing-stop" +STATUS_ZOMBIE = "zombie" +STATUS_DEAD = "dead" +STATUS_WAKE_KILL = "wake-kill" +STATUS_WAKING = "waking" +STATUS_IDLE = "idle" # Linux, macOS, FreeBSD +STATUS_LOCKED = "locked" # FreeBSD +STATUS_WAITING = "waiting" # FreeBSD +STATUS_SUSPENDED = "suspended" # NetBSD +STATUS_PARKED = "parked" # Linux + +# Process.net_connections() and psutil.net_connections() +CONN_ESTABLISHED = "ESTABLISHED" +CONN_SYN_SENT = "SYN_SENT" +CONN_SYN_RECV = "SYN_RECV" +CONN_FIN_WAIT1 = "FIN_WAIT1" +CONN_FIN_WAIT2 = "FIN_WAIT2" +CONN_TIME_WAIT = "TIME_WAIT" +CONN_CLOSE = "CLOSE" +CONN_CLOSE_WAIT = "CLOSE_WAIT" +CONN_LAST_ACK = "LAST_ACK" +CONN_LISTEN = "LISTEN" +CONN_CLOSING = "CLOSING" +CONN_NONE = "NONE" + + +# net_if_stats() +class NicDuplex(enum.IntEnum): + NIC_DUPLEX_FULL = 2 + NIC_DUPLEX_HALF = 1 + NIC_DUPLEX_UNKNOWN = 0 + + +globals().update(NicDuplex.__members__) + + +# sensors_battery() +class BatteryTime(enum.IntEnum): + POWER_TIME_UNKNOWN = -1 + POWER_TIME_UNLIMITED = -2 + + +globals().update(BatteryTime.__members__) + +# --- others + +ENCODING = sys.getfilesystemencoding() +ENCODING_ERRS = sys.getfilesystemencodeerrors() + + +# =================================================================== +# --- namedtuples +# =================================================================== + +# --- for system functions + +# fmt: off +# psutil.swap_memory() +sswap = namedtuple('sswap', ['total', 'used', 'free', 'percent', 'sin', + 'sout']) +# psutil.disk_usage() +sdiskusage = namedtuple('sdiskusage', ['total', 'used', 'free', 'percent']) +# psutil.disk_io_counters() +sdiskio = namedtuple('sdiskio', ['read_count', 'write_count', + 'read_bytes', 'write_bytes', + 'read_time', 'write_time']) +# psutil.disk_partitions() +sdiskpart = namedtuple('sdiskpart', ['device', 'mountpoint', 'fstype', 'opts']) +# psutil.net_io_counters() +snetio = namedtuple('snetio', ['bytes_sent', 'bytes_recv', + 'packets_sent', 'packets_recv', + 'errin', 'errout', + 'dropin', 'dropout']) +# psutil.users() +suser = namedtuple('suser', ['name', 'terminal', 'host', 'started', 'pid']) +# psutil.net_connections() +sconn = namedtuple('sconn', ['fd', 'family', 'type', 'laddr', 'raddr', + 'status', 'pid']) +# psutil.net_if_addrs() +snicaddr = namedtuple('snicaddr', + ['family', 'address', 'netmask', 'broadcast', 'ptp']) +# psutil.net_if_stats() +snicstats = namedtuple('snicstats', + ['isup', 'duplex', 'speed', 'mtu', 'flags']) +# psutil.cpu_stats() +scpustats = namedtuple( + 'scpustats', ['ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls']) +# psutil.cpu_freq() +scpufreq = namedtuple('scpufreq', ['current', 'min', 'max']) +# psutil.sensors_temperatures() +shwtemp = namedtuple( + 'shwtemp', ['label', 'current', 'high', 'critical']) +# psutil.sensors_battery() +sbattery = namedtuple('sbattery', ['percent', 'secsleft', 'power_plugged']) +# psutil.sensors_fans() +sfan = namedtuple('sfan', ['label', 'current']) +# fmt: on + +# --- for Process methods + +# psutil.Process.cpu_times() +pcputimes = namedtuple( + 'pcputimes', ['user', 'system', 'children_user', 'children_system'] +) +# psutil.Process.open_files() +popenfile = namedtuple('popenfile', ['path', 'fd']) +# psutil.Process.threads() +pthread = namedtuple('pthread', ['id', 'user_time', 'system_time']) +# psutil.Process.uids() +puids = namedtuple('puids', ['real', 'effective', 'saved']) +# psutil.Process.gids() +pgids = namedtuple('pgids', ['real', 'effective', 'saved']) +# psutil.Process.io_counters() +pio = namedtuple( + 'pio', ['read_count', 'write_count', 'read_bytes', 'write_bytes'] +) +# psutil.Process.ionice() +pionice = namedtuple('pionice', ['ioclass', 'value']) +# psutil.Process.ctx_switches() +pctxsw = namedtuple('pctxsw', ['voluntary', 'involuntary']) +# psutil.Process.net_connections() +pconn = namedtuple( + 'pconn', ['fd', 'family', 'type', 'laddr', 'raddr', 'status'] +) + +# psutil.net_connections() and psutil.Process.net_connections() +addr = namedtuple('addr', ['ip', 'port']) + + +# =================================================================== +# --- Process.net_connections() 'kind' parameter mapping +# =================================================================== + + +conn_tmap = { + "all": ([AF_INET, AF_INET6, AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]), + "tcp": ([AF_INET, AF_INET6], [SOCK_STREAM]), + "tcp4": ([AF_INET], [SOCK_STREAM]), + "udp": ([AF_INET, AF_INET6], [SOCK_DGRAM]), + "udp4": ([AF_INET], [SOCK_DGRAM]), + "inet": ([AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM]), + "inet4": ([AF_INET], [SOCK_STREAM, SOCK_DGRAM]), + "inet6": ([AF_INET6], [SOCK_STREAM, SOCK_DGRAM]), +} + +if AF_INET6 is not None: + conn_tmap.update({ + "tcp6": ([AF_INET6], [SOCK_STREAM]), + "udp6": ([AF_INET6], [SOCK_DGRAM]), + }) + +if AF_UNIX is not None and not SUNOS: + conn_tmap.update({"unix": ([AF_UNIX], [SOCK_STREAM, SOCK_DGRAM])}) + + +# ===================================================================== +# --- Exceptions +# ===================================================================== + + +class Error(Exception): + """Base exception class. All other psutil exceptions inherit + from this one. + """ + + __module__ = 'psutil' + + def _infodict(self, attrs): + info = collections.OrderedDict() + for name in attrs: + value = getattr(self, name, None) + if value or (name == "pid" and value == 0): + info[name] = value + return info + + def __str__(self): + # invoked on `raise Error` + info = self._infodict(("pid", "ppid", "name")) + if info: + details = "({})".format( + ", ".join([f"{k}={v!r}" for k, v in info.items()]) + ) + else: + details = None + return " ".join([x for x in (getattr(self, "msg", ""), details) if x]) + + def __repr__(self): + # invoked on `repr(Error)` + info = self._infodict(("pid", "ppid", "name", "seconds", "msg")) + details = ", ".join([f"{k}={v!r}" for k, v in info.items()]) + return f"psutil.{self.__class__.__name__}({details})" + + +class NoSuchProcess(Error): + """Exception raised when a process with a certain PID doesn't + or no longer exists. + """ + + __module__ = 'psutil' + + def __init__(self, pid, name=None, msg=None): + Error.__init__(self) + self.pid = pid + self.name = name + self.msg = msg or "process no longer exists" + + def __reduce__(self): + return (self.__class__, (self.pid, self.name, self.msg)) + + +class ZombieProcess(NoSuchProcess): + """Exception raised when querying a zombie process. This is + raised on macOS, BSD and Solaris only, and not always: depending + on the query the OS may be able to succeed anyway. + On Linux all zombie processes are querable (hence this is never + raised). Windows doesn't have zombie processes. + """ + + __module__ = 'psutil' + + def __init__(self, pid, name=None, ppid=None, msg=None): + NoSuchProcess.__init__(self, pid, name, msg) + self.ppid = ppid + self.msg = msg or "PID still exists but it's a zombie" + + def __reduce__(self): + return (self.__class__, (self.pid, self.name, self.ppid, self.msg)) + + +class AccessDenied(Error): + """Exception raised when permission to perform an action is denied.""" + + __module__ = 'psutil' + + def __init__(self, pid=None, name=None, msg=None): + Error.__init__(self) + self.pid = pid + self.name = name + self.msg = msg or "" + + def __reduce__(self): + return (self.__class__, (self.pid, self.name, self.msg)) + + +class TimeoutExpired(Error): + """Raised on Process.wait(timeout) if timeout expires and process + is still alive. + """ + + __module__ = 'psutil' + + def __init__(self, seconds, pid=None, name=None): + Error.__init__(self) + self.seconds = seconds + self.pid = pid + self.name = name + self.msg = f"timeout after {seconds} seconds" + + def __reduce__(self): + return (self.__class__, (self.seconds, self.pid, self.name)) + + +# =================================================================== +# --- utils +# =================================================================== + + +def usage_percent(used, total, round_=None): + """Calculate percentage usage of 'used' against 'total'.""" + try: + ret = (float(used) / total) * 100 + except ZeroDivisionError: + return 0.0 + else: + if round_ is not None: + ret = round(ret, round_) + return ret + + +def memoize(fun): + """A simple memoize decorator for functions supporting (hashable) + positional arguments. + It also provides a cache_clear() function for clearing the cache: + + >>> @memoize + ... def foo() + ... return 1 + ... + >>> foo() + 1 + >>> foo.cache_clear() + >>> + + It supports: + - functions + - classes (acts as a @singleton) + - staticmethods + - classmethods + + It does NOT support: + - methods + """ + + @functools.wraps(fun) + def wrapper(*args, **kwargs): + key = (args, frozenset(sorted(kwargs.items()))) + try: + return cache[key] + except KeyError: + try: + ret = cache[key] = fun(*args, **kwargs) + except Exception as err: # noqa: BLE001 + raise err from None + return ret + + def cache_clear(): + """Clear cache.""" + cache.clear() + + cache = {} + wrapper.cache_clear = cache_clear + return wrapper + + +def memoize_when_activated(fun): + """A memoize decorator which is disabled by default. It can be + activated and deactivated on request. + For efficiency reasons it can be used only against class methods + accepting no arguments. + + >>> class Foo: + ... @memoize + ... def foo() + ... print(1) + ... + >>> f = Foo() + >>> # deactivated (default) + >>> foo() + 1 + >>> foo() + 1 + >>> + >>> # activated + >>> foo.cache_activate(self) + >>> foo() + 1 + >>> foo() + >>> foo() + >>> + """ + + @functools.wraps(fun) + def wrapper(self): + try: + # case 1: we previously entered oneshot() ctx + ret = self._cache[fun] + except AttributeError: + # case 2: we never entered oneshot() ctx + try: + return fun(self) + except Exception as err: # noqa: BLE001 + raise err from None + except KeyError: + # case 3: we entered oneshot() ctx but there's no cache + # for this entry yet + try: + ret = fun(self) + except Exception as err: # noqa: BLE001 + raise err from None + try: + self._cache[fun] = ret + except AttributeError: + # multi-threading race condition, see: + # https://github.com/giampaolo/psutil/issues/1948 + pass + return ret + + def cache_activate(proc): + """Activate cache. Expects a Process instance. Cache will be + stored as a "_cache" instance attribute. + """ + proc._cache = {} + + def cache_deactivate(proc): + """Deactivate and clear cache.""" + try: + del proc._cache + except AttributeError: + pass + + wrapper.cache_activate = cache_activate + wrapper.cache_deactivate = cache_deactivate + return wrapper + + +def isfile_strict(path): + """Same as os.path.isfile() but does not swallow EACCES / EPERM + exceptions, see: + http://mail.python.org/pipermail/python-dev/2012-June/120787.html. + """ + try: + st = os.stat(path) + except PermissionError: + raise + except OSError: + return False + else: + return stat.S_ISREG(st.st_mode) + + +def path_exists_strict(path): + """Same as os.path.exists() but does not swallow EACCES / EPERM + exceptions. See: + http://mail.python.org/pipermail/python-dev/2012-June/120787.html. + """ + try: + os.stat(path) + except PermissionError: + raise + except OSError: + return False + else: + return True + + +@memoize +def supports_ipv6(): + """Return True if IPv6 is supported on this platform.""" + if not socket.has_ipv6 or AF_INET6 is None: + return False + try: + with socket.socket(AF_INET6, socket.SOCK_STREAM) as sock: + sock.bind(("::1", 0)) + return True + except OSError: + return False + + +def parse_environ_block(data): + """Parse a C environ block of environment variables into a dictionary.""" + # The block is usually raw data from the target process. It might contain + # trailing garbage and lines that do not look like assignments. + ret = {} + pos = 0 + + # localize global variable to speed up access. + WINDOWS_ = WINDOWS + while True: + next_pos = data.find("\0", pos) + # nul byte at the beginning or double nul byte means finish + if next_pos <= pos: + break + # there might not be an equals sign + equal_pos = data.find("=", pos, next_pos) + if equal_pos > pos: + key = data[pos:equal_pos] + value = data[equal_pos + 1 : next_pos] + # Windows expects environment variables to be uppercase only + if WINDOWS_: + key = key.upper() + ret[key] = value + pos = next_pos + 1 + + return ret + + +def sockfam_to_enum(num): + """Convert a numeric socket family value to an IntEnum member. + If it's not a known member, return the numeric value itself. + """ + try: + return socket.AddressFamily(num) + except ValueError: + return num + + +def socktype_to_enum(num): + """Convert a numeric socket type value to an IntEnum member. + If it's not a known member, return the numeric value itself. + """ + try: + return socket.SocketKind(num) + except ValueError: + return num + + +def conn_to_ntuple(fd, fam, type_, laddr, raddr, status, status_map, pid=None): + """Convert a raw connection tuple to a proper ntuple.""" + if fam in {socket.AF_INET, AF_INET6}: + if laddr: + laddr = addr(*laddr) + if raddr: + raddr = addr(*raddr) + if type_ == socket.SOCK_STREAM and fam in {AF_INET, AF_INET6}: + status = status_map.get(status, CONN_NONE) + else: + status = CONN_NONE # ignore whatever C returned to us + fam = sockfam_to_enum(fam) + type_ = socktype_to_enum(type_) + if pid is None: + return pconn(fd, fam, type_, laddr, raddr, status) + else: + return sconn(fd, fam, type_, laddr, raddr, status, pid) + + +def broadcast_addr(addr): + """Given the address ntuple returned by ``net_if_addrs()`` + calculates the broadcast address. + """ + import ipaddress + + if not addr.address or not addr.netmask: + return None + if addr.family == socket.AF_INET: + return str( + ipaddress.IPv4Network( + f"{addr.address}/{addr.netmask}", strict=False + ).broadcast_address + ) + if addr.family == socket.AF_INET6: + return str( + ipaddress.IPv6Network( + f"{addr.address}/{addr.netmask}", strict=False + ).broadcast_address + ) + + +def deprecated_method(replacement): + """A decorator which can be used to mark a method as deprecated + 'replcement' is the method name which will be called instead. + """ + + def outer(fun): + msg = ( + f"{fun.__name__}() is deprecated and will be removed; use" + f" {replacement}() instead" + ) + if fun.__doc__ is None: + fun.__doc__ = msg + + @functools.wraps(fun) + def inner(self, *args, **kwargs): + warnings.warn(msg, category=DeprecationWarning, stacklevel=2) + return getattr(self, replacement)(*args, **kwargs) + + return inner + + return outer + + +class _WrapNumbers: + """Watches numbers so that they don't overflow and wrap + (reset to zero). + """ + + def __init__(self): + self.lock = threading.Lock() + self.cache = {} + self.reminders = {} + self.reminder_keys = {} + + def _add_dict(self, input_dict, name): + assert name not in self.cache + assert name not in self.reminders + assert name not in self.reminder_keys + self.cache[name] = input_dict + self.reminders[name] = collections.defaultdict(int) + self.reminder_keys[name] = collections.defaultdict(set) + + def _remove_dead_reminders(self, input_dict, name): + """In case the number of keys changed between calls (e.g. a + disk disappears) this removes the entry from self.reminders. + """ + old_dict = self.cache[name] + gone_keys = set(old_dict.keys()) - set(input_dict.keys()) + for gone_key in gone_keys: + for remkey in self.reminder_keys[name][gone_key]: + del self.reminders[name][remkey] + del self.reminder_keys[name][gone_key] + + def run(self, input_dict, name): + """Cache dict and sum numbers which overflow and wrap. + Return an updated copy of `input_dict`. + """ + if name not in self.cache: + # This was the first call. + self._add_dict(input_dict, name) + return input_dict + + self._remove_dead_reminders(input_dict, name) + + old_dict = self.cache[name] + new_dict = {} + for key in input_dict: + input_tuple = input_dict[key] + try: + old_tuple = old_dict[key] + except KeyError: + # The input dict has a new key (e.g. a new disk or NIC) + # which didn't exist in the previous call. + new_dict[key] = input_tuple + continue + + bits = [] + for i in range(len(input_tuple)): + input_value = input_tuple[i] + old_value = old_tuple[i] + remkey = (key, i) + if input_value < old_value: + # it wrapped! + self.reminders[name][remkey] += old_value + self.reminder_keys[name][key].add(remkey) + bits.append(input_value + self.reminders[name][remkey]) + + new_dict[key] = tuple(bits) + + self.cache[name] = input_dict + return new_dict + + def cache_clear(self, name=None): + """Clear the internal cache, optionally only for function 'name'.""" + with self.lock: + if name is None: + self.cache.clear() + self.reminders.clear() + self.reminder_keys.clear() + else: + self.cache.pop(name, None) + self.reminders.pop(name, None) + self.reminder_keys.pop(name, None) + + def cache_info(self): + """Return internal cache dicts as a tuple of 3 elements.""" + with self.lock: + return (self.cache, self.reminders, self.reminder_keys) + + +def wrap_numbers(input_dict, name): + """Given an `input_dict` and a function `name`, adjust the numbers + which "wrap" (restart from zero) across different calls by adding + "old value" to "new value" and return an updated dict. + """ + with _wn.lock: + return _wn.run(input_dict, name) + + +_wn = _WrapNumbers() +wrap_numbers.cache_clear = _wn.cache_clear +wrap_numbers.cache_info = _wn.cache_info + + +# The read buffer size for open() builtin. This (also) dictates how +# much data we read(2) when iterating over file lines as in: +# >>> with open(file) as f: +# ... for line in f: +# ... ... +# Default per-line buffer size for binary files is 1K. For text files +# is 8K. We use a bigger buffer (32K) in order to have more consistent +# results when reading /proc pseudo files on Linux, see: +# https://github.com/giampaolo/psutil/issues/2050 +# https://github.com/giampaolo/psutil/issues/708 +FILE_READ_BUFFER_SIZE = 32 * 1024 + + +def open_binary(fname): + return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE) + + +def open_text(fname): + """Open a file in text mode by using the proper FS encoding and + en/decoding error handlers. + """ + # See: + # https://github.com/giampaolo/psutil/issues/675 + # https://github.com/giampaolo/psutil/pull/733 + fobj = open( # noqa: SIM115 + fname, + buffering=FILE_READ_BUFFER_SIZE, + encoding=ENCODING, + errors=ENCODING_ERRS, + ) + try: + # Dictates per-line read(2) buffer size. Defaults is 8k. See: + # https://github.com/giampaolo/psutil/issues/2050#issuecomment-1013387546 + fobj._CHUNK_SIZE = FILE_READ_BUFFER_SIZE + except AttributeError: + pass + except Exception: + fobj.close() + raise + + return fobj + + +def cat(fname, fallback=_DEFAULT, _open=open_text): + """Read entire file content and return it as a string. File is + opened in text mode. If specified, `fallback` is the value + returned in case of error, either if the file does not exist or + it can't be read(). + """ + if fallback is _DEFAULT: + with _open(fname) as f: + return f.read() + else: + try: + with _open(fname) as f: + return f.read() + except OSError: + return fallback + + +def bcat(fname, fallback=_DEFAULT): + """Same as above but opens file in binary mode.""" + return cat(fname, fallback=fallback, _open=open_binary) + + +def bytes2human(n, format="%(value).1f%(symbol)s"): + """Used by various scripts. See: https://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/?in=user-4178764. + + >>> bytes2human(10000) + '9.8K' + >>> bytes2human(100001221) + '95.4M' + """ + symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') + prefix = {} + for i, s in enumerate(symbols[1:]): + prefix[s] = 1 << (i + 1) * 10 + for symbol in reversed(symbols[1:]): + if abs(n) >= prefix[symbol]: + value = float(n) / prefix[symbol] + return format % locals() + return format % dict(symbol=symbols[0], value=n) + + +def get_procfs_path(): + """Return updated psutil.PROCFS_PATH constant.""" + return sys.modules['psutil'].PROCFS_PATH + + +def decode(s): + return s.decode(encoding=ENCODING, errors=ENCODING_ERRS) + + +# ===================================================================== +# --- shell utils +# ===================================================================== + + +@memoize +def term_supports_colors(file=sys.stdout): # pragma: no cover + if os.name == 'nt': + return True + try: + import curses + + assert file.isatty() + curses.setupterm() + assert curses.tigetnum("colors") > 0 + except Exception: # noqa: BLE001 + return False + else: + return True + + +def hilite(s, color=None, bold=False): # pragma: no cover + """Return an highlighted version of 'string'.""" + if not term_supports_colors(): + return s + attr = [] + colors = dict( + blue='34', + brown='33', + darkgrey='30', + green='32', + grey='37', + lightblue='36', + red='91', + violet='35', + yellow='93', + ) + colors[None] = '29' + try: + color = colors[color] + except KeyError: + msg = f"invalid color {color!r}; choose amongst {list(colors.keys())}" + raise ValueError(msg) from None + attr.append(color) + if bold: + attr.append('1') + return f"\x1b[{';'.join(attr)}m{s}\x1b[0m" + + +def print_color( + s, color=None, bold=False, file=sys.stdout +): # pragma: no cover + """Print a colorized version of string.""" + if not term_supports_colors(): + print(s, file=file) + elif POSIX: + print(hilite(s, color, bold), file=file) + else: + import ctypes + + DEFAULT_COLOR = 7 + GetStdHandle = ctypes.windll.Kernel32.GetStdHandle + SetConsoleTextAttribute = ( + ctypes.windll.Kernel32.SetConsoleTextAttribute + ) + + colors = dict(green=2, red=4, brown=6, yellow=6) + colors[None] = DEFAULT_COLOR + try: + color = colors[color] + except KeyError: + msg = ( + f"invalid color {color!r}; choose between" + f" {list(colors.keys())!r}" + ) + raise ValueError(msg) from None + if bold and color <= 7: + color += 8 + + handle_id = -12 if file is sys.stderr else -11 + GetStdHandle.restype = ctypes.c_ulong + handle = GetStdHandle(handle_id) + SetConsoleTextAttribute(handle, color) + try: + print(s, file=file) + finally: + SetConsoleTextAttribute(handle, DEFAULT_COLOR) + + +def debug(msg): + """If PSUTIL_DEBUG env var is set, print a debug message to stderr.""" + if PSUTIL_DEBUG: + import inspect + + fname, lineno, _, _lines, _index = inspect.getframeinfo( + inspect.currentframe().f_back + ) + if isinstance(msg, Exception): + if isinstance(msg, OSError): + # ...because str(exc) may contain info about the file name + msg = f"ignoring {msg}" + else: + msg = f"ignoring {msg!r}" + print( # noqa: T201 + f"psutil-debug [{fname}:{lineno}]> {msg}", file=sys.stderr + ) diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psaix.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psaix.py new file mode 100644 index 0000000000000000000000000000000000000000..ba2725fdc10d38532e9784f1efe80fed2210983c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psaix.py @@ -0,0 +1,565 @@ +# Copyright (c) 2009, Giampaolo Rodola' +# Copyright (c) 2017, Arnon Yaari +# All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""AIX platform implementation.""" + +import functools +import glob +import os +import re +import subprocess +import sys +from collections import namedtuple + +from . import _common +from . import _psposix +from . import _psutil_aix as cext +from . import _psutil_posix as cext_posix +from ._common import NIC_DUPLEX_FULL +from ._common import NIC_DUPLEX_HALF +from ._common import NIC_DUPLEX_UNKNOWN +from ._common import AccessDenied +from ._common import NoSuchProcess +from ._common import ZombieProcess +from ._common import conn_to_ntuple +from ._common import get_procfs_path +from ._common import memoize_when_activated +from ._common import usage_percent + + +__extra__all__ = ["PROCFS_PATH"] + + +# ===================================================================== +# --- globals +# ===================================================================== + + +HAS_THREADS = hasattr(cext, "proc_threads") +HAS_NET_IO_COUNTERS = hasattr(cext, "net_io_counters") +HAS_PROC_IO_COUNTERS = hasattr(cext, "proc_io_counters") + +PAGE_SIZE = cext_posix.getpagesize() +AF_LINK = cext_posix.AF_LINK + +PROC_STATUSES = { + cext.SIDL: _common.STATUS_IDLE, + cext.SZOMB: _common.STATUS_ZOMBIE, + cext.SACTIVE: _common.STATUS_RUNNING, + cext.SSWAP: _common.STATUS_RUNNING, # TODO what status is this? + cext.SSTOP: _common.STATUS_STOPPED, +} + +TCP_STATUSES = { + cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED, + cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT, + cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV, + cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1, + cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2, + cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT, + cext.TCPS_CLOSED: _common.CONN_CLOSE, + cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, + cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK, + cext.TCPS_LISTEN: _common.CONN_LISTEN, + cext.TCPS_CLOSING: _common.CONN_CLOSING, + cext.PSUTIL_CONN_NONE: _common.CONN_NONE, +} + +proc_info_map = dict( + ppid=0, + rss=1, + vms=2, + create_time=3, + nice=4, + num_threads=5, + status=6, + ttynr=7, +) + + +# ===================================================================== +# --- named tuples +# ===================================================================== + + +# psutil.Process.memory_info() +pmem = namedtuple('pmem', ['rss', 'vms']) +# psutil.Process.memory_full_info() +pfullmem = pmem +# psutil.Process.cpu_times() +scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait']) +# psutil.virtual_memory() +svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free']) + + +# ===================================================================== +# --- memory +# ===================================================================== + + +def virtual_memory(): + total, avail, free, _pinned, inuse = cext.virtual_mem() + percent = usage_percent((total - avail), total, round_=1) + return svmem(total, avail, percent, inuse, free) + + +def swap_memory(): + """Swap system memory as a (total, used, free, sin, sout) tuple.""" + total, free, sin, sout = cext.swap_mem() + used = total - free + percent = usage_percent(used, total, round_=1) + return _common.sswap(total, used, free, percent, sin, sout) + + +# ===================================================================== +# --- CPU +# ===================================================================== + + +def cpu_times(): + """Return system-wide CPU times as a named tuple.""" + ret = cext.per_cpu_times() + return scputimes(*[sum(x) for x in zip(*ret)]) + + +def per_cpu_times(): + """Return system per-CPU times as a list of named tuples.""" + ret = cext.per_cpu_times() + return [scputimes(*x) for x in ret] + + +def cpu_count_logical(): + """Return the number of logical CPUs in the system.""" + try: + return os.sysconf("SC_NPROCESSORS_ONLN") + except ValueError: + # mimic os.cpu_count() behavior + return None + + +def cpu_count_cores(): + cmd = ["lsdev", "-Cc", "processor"] + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = p.communicate() + stdout, stderr = (x.decode(sys.stdout.encoding) for x in (stdout, stderr)) + if p.returncode != 0: + msg = f"{cmd!r} command error\n{stderr}" + raise RuntimeError(msg) + processors = stdout.strip().splitlines() + return len(processors) or None + + +def cpu_stats(): + """Return various CPU stats as a named tuple.""" + ctx_switches, interrupts, soft_interrupts, syscalls = cext.cpu_stats() + return _common.scpustats( + ctx_switches, interrupts, soft_interrupts, syscalls + ) + + +# ===================================================================== +# --- disks +# ===================================================================== + + +disk_io_counters = cext.disk_io_counters +disk_usage = _psposix.disk_usage + + +def disk_partitions(all=False): + """Return system disk partitions.""" + # TODO - the filtering logic should be better checked so that + # it tries to reflect 'df' as much as possible + retlist = [] + partitions = cext.disk_partitions() + for partition in partitions: + device, mountpoint, fstype, opts = partition + if device == 'none': + device = '' + if not all: + # Differently from, say, Linux, we don't have a list of + # common fs types so the best we can do, AFAIK, is to + # filter by filesystem having a total size > 0. + if not disk_usage(mountpoint).total: + continue + ntuple = _common.sdiskpart(device, mountpoint, fstype, opts) + retlist.append(ntuple) + return retlist + + +# ===================================================================== +# --- network +# ===================================================================== + + +net_if_addrs = cext_posix.net_if_addrs + +if HAS_NET_IO_COUNTERS: + net_io_counters = cext.net_io_counters + + +def net_connections(kind, _pid=-1): + """Return socket connections. If pid == -1 return system-wide + connections (as opposed to connections opened by one process only). + """ + families, types = _common.conn_tmap[kind] + rawlist = cext.net_connections(_pid) + ret = [] + for item in rawlist: + fd, fam, type_, laddr, raddr, status, pid = item + if fam not in families: + continue + if type_ not in types: + continue + nt = conn_to_ntuple( + fd, + fam, + type_, + laddr, + raddr, + status, + TCP_STATUSES, + pid=pid if _pid == -1 else None, + ) + ret.append(nt) + return ret + + +def net_if_stats(): + """Get NIC stats (isup, duplex, speed, mtu).""" + duplex_map = {"Full": NIC_DUPLEX_FULL, "Half": NIC_DUPLEX_HALF} + names = {x[0] for x in net_if_addrs()} + ret = {} + for name in names: + mtu = cext_posix.net_if_mtu(name) + flags = cext_posix.net_if_flags(name) + + # try to get speed and duplex + # TODO: rewrite this in C (entstat forks, so use truss -f to follow. + # looks like it is using an undocumented ioctl?) + duplex = "" + speed = 0 + p = subprocess.Popen( + ["/usr/bin/entstat", "-d", name], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + stdout, stderr = p.communicate() + stdout, stderr = ( + x.decode(sys.stdout.encoding) for x in (stdout, stderr) + ) + if p.returncode == 0: + re_result = re.search( + r"Running: (\d+) Mbps.*?(\w+) Duplex", stdout + ) + if re_result is not None: + speed = int(re_result.group(1)) + duplex = re_result.group(2) + + output_flags = ','.join(flags) + isup = 'running' in flags + duplex = duplex_map.get(duplex, NIC_DUPLEX_UNKNOWN) + ret[name] = _common.snicstats(isup, duplex, speed, mtu, output_flags) + return ret + + +# ===================================================================== +# --- other system functions +# ===================================================================== + + +def boot_time(): + """The system boot time expressed in seconds since the epoch.""" + return cext.boot_time() + + +def users(): + """Return currently connected users as a list of namedtuples.""" + retlist = [] + rawlist = cext.users() + localhost = (':0.0', ':0') + for item in rawlist: + user, tty, hostname, tstamp, user_process, pid = item + # note: the underlying C function includes entries about + # system boot, run level and others. We might want + # to use them in the future. + if not user_process: + continue + if hostname in localhost: + hostname = 'localhost' + nt = _common.suser(user, tty, hostname, tstamp, pid) + retlist.append(nt) + return retlist + + +# ===================================================================== +# --- processes +# ===================================================================== + + +def pids(): + """Returns a list of PIDs currently running on the system.""" + return [int(x) for x in os.listdir(get_procfs_path()) if x.isdigit()] + + +def pid_exists(pid): + """Check for the existence of a unix pid.""" + return os.path.exists(os.path.join(get_procfs_path(), str(pid), "psinfo")) + + +def wrap_exceptions(fun): + """Call callable into a try/except clause and translate ENOENT, + EACCES and EPERM in NoSuchProcess or AccessDenied exceptions. + """ + + @functools.wraps(fun) + def wrapper(self, *args, **kwargs): + pid, ppid, name = self.pid, self._ppid, self._name + try: + return fun(self, *args, **kwargs) + except (FileNotFoundError, ProcessLookupError) as err: + # ENOENT (no such file or directory) gets raised on open(). + # ESRCH (no such process) can get raised on read() if + # process is gone in meantime. + if not pid_exists(pid): + raise NoSuchProcess(pid, name) from err + raise ZombieProcess(pid, name, ppid) from err + except PermissionError as err: + raise AccessDenied(pid, name) from err + + return wrapper + + +class Process: + """Wrapper class around underlying C implementation.""" + + __slots__ = ["_cache", "_name", "_ppid", "_procfs_path", "pid"] + + def __init__(self, pid): + self.pid = pid + self._name = None + self._ppid = None + self._procfs_path = get_procfs_path() + + def oneshot_enter(self): + self._proc_basic_info.cache_activate(self) + self._proc_cred.cache_activate(self) + + def oneshot_exit(self): + self._proc_basic_info.cache_deactivate(self) + self._proc_cred.cache_deactivate(self) + + @wrap_exceptions + @memoize_when_activated + def _proc_basic_info(self): + return cext.proc_basic_info(self.pid, self._procfs_path) + + @wrap_exceptions + @memoize_when_activated + def _proc_cred(self): + return cext.proc_cred(self.pid, self._procfs_path) + + @wrap_exceptions + def name(self): + if self.pid == 0: + return "swapper" + # note: max 16 characters + return cext.proc_name(self.pid, self._procfs_path).rstrip("\x00") + + @wrap_exceptions + def exe(self): + # there is no way to get executable path in AIX other than to guess, + # and guessing is more complex than what's in the wrapping class + cmdline = self.cmdline() + if not cmdline: + return '' + exe = cmdline[0] + if os.path.sep in exe: + # relative or absolute path + if not os.path.isabs(exe): + # if cwd has changed, we're out of luck - this may be wrong! + exe = os.path.abspath(os.path.join(self.cwd(), exe)) + if ( + os.path.isabs(exe) + and os.path.isfile(exe) + and os.access(exe, os.X_OK) + ): + return exe + # not found, move to search in PATH using basename only + exe = os.path.basename(exe) + # search for exe name PATH + for path in os.environ["PATH"].split(":"): + possible_exe = os.path.abspath(os.path.join(path, exe)) + if os.path.isfile(possible_exe) and os.access( + possible_exe, os.X_OK + ): + return possible_exe + return '' + + @wrap_exceptions + def cmdline(self): + return cext.proc_args(self.pid) + + @wrap_exceptions + def environ(self): + return cext.proc_environ(self.pid) + + @wrap_exceptions + def create_time(self): + return self._proc_basic_info()[proc_info_map['create_time']] + + @wrap_exceptions + def num_threads(self): + return self._proc_basic_info()[proc_info_map['num_threads']] + + if HAS_THREADS: + + @wrap_exceptions + def threads(self): + rawlist = cext.proc_threads(self.pid) + retlist = [] + for thread_id, utime, stime in rawlist: + ntuple = _common.pthread(thread_id, utime, stime) + retlist.append(ntuple) + # The underlying C implementation retrieves all OS threads + # and filters them by PID. At this point we can't tell whether + # an empty list means there were no connections for process or + # process is no longer active so we force NSP in case the PID + # is no longer there. + if not retlist: + # will raise NSP if process is gone + os.stat(f"{self._procfs_path}/{self.pid}") + return retlist + + @wrap_exceptions + def net_connections(self, kind='inet'): + ret = net_connections(kind, _pid=self.pid) + # The underlying C implementation retrieves all OS connections + # and filters them by PID. At this point we can't tell whether + # an empty list means there were no connections for process or + # process is no longer active so we force NSP in case the PID + # is no longer there. + if not ret: + # will raise NSP if process is gone + os.stat(f"{self._procfs_path}/{self.pid}") + return ret + + @wrap_exceptions + def nice_get(self): + return cext_posix.getpriority(self.pid) + + @wrap_exceptions + def nice_set(self, value): + return cext_posix.setpriority(self.pid, value) + + @wrap_exceptions + def ppid(self): + self._ppid = self._proc_basic_info()[proc_info_map['ppid']] + return self._ppid + + @wrap_exceptions + def uids(self): + real, effective, saved, _, _, _ = self._proc_cred() + return _common.puids(real, effective, saved) + + @wrap_exceptions + def gids(self): + _, _, _, real, effective, saved = self._proc_cred() + return _common.puids(real, effective, saved) + + @wrap_exceptions + def cpu_times(self): + t = cext.proc_cpu_times(self.pid, self._procfs_path) + return _common.pcputimes(*t) + + @wrap_exceptions + def terminal(self): + ttydev = self._proc_basic_info()[proc_info_map['ttynr']] + # convert from 64-bit dev_t to 32-bit dev_t and then map the device + ttydev = ((ttydev & 0x0000FFFF00000000) >> 16) | (ttydev & 0xFFFF) + # try to match rdev of /dev/pts/* files ttydev + for dev in glob.glob("/dev/**/*"): + if os.stat(dev).st_rdev == ttydev: + return dev + return None + + @wrap_exceptions + def cwd(self): + procfs_path = self._procfs_path + try: + result = os.readlink(f"{procfs_path}/{self.pid}/cwd") + return result.rstrip('/') + except FileNotFoundError: + os.stat(f"{procfs_path}/{self.pid}") # raise NSP or AD + return "" + + @wrap_exceptions + def memory_info(self): + ret = self._proc_basic_info() + rss = ret[proc_info_map['rss']] * 1024 + vms = ret[proc_info_map['vms']] * 1024 + return pmem(rss, vms) + + memory_full_info = memory_info + + @wrap_exceptions + def status(self): + code = self._proc_basic_info()[proc_info_map['status']] + # XXX is '?' legit? (we're not supposed to return it anyway) + return PROC_STATUSES.get(code, '?') + + def open_files(self): + # TODO rewrite without using procfiles (stat /proc/pid/fd/* and then + # find matching name of the inode) + p = subprocess.Popen( + ["/usr/bin/procfiles", "-n", str(self.pid)], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + stdout, stderr = p.communicate() + stdout, stderr = ( + x.decode(sys.stdout.encoding) for x in (stdout, stderr) + ) + if "no such process" in stderr.lower(): + raise NoSuchProcess(self.pid, self._name) + procfiles = re.findall(r"(\d+): S_IFREG.*name:(.*)\n", stdout) + retlist = [] + for fd, path in procfiles: + path = path.strip() + if path.startswith("//"): + path = path[1:] + if path.lower() == "cannot be retrieved": + continue + retlist.append(_common.popenfile(path, int(fd))) + return retlist + + @wrap_exceptions + def num_fds(self): + if self.pid == 0: # no /proc/0/fd + return 0 + return len(os.listdir(f"{self._procfs_path}/{self.pid}/fd")) + + @wrap_exceptions + def num_ctx_switches(self): + return _common.pctxsw(*cext.proc_num_ctx_switches(self.pid)) + + @wrap_exceptions + def wait(self, timeout=None): + return _psposix.wait_pid(self.pid, timeout, self._name) + + if HAS_PROC_IO_COUNTERS: + + @wrap_exceptions + def io_counters(self): + try: + rc, wc, rb, wb = cext.proc_io_counters(self.pid) + except OSError as err: + # if process is terminated, proc_io_counters returns OSError + # instead of NSP + if not pid_exists(self.pid): + raise NoSuchProcess(self.pid, self._name) from err + raise + return _common.pio(rc, wc, rb, wb) diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psbsd.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psbsd.py new file mode 100644 index 0000000000000000000000000000000000000000..13bd926fabf1740e0170b1ada1f4bf53bd3855dd --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psbsd.py @@ -0,0 +1,971 @@ +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""FreeBSD, OpenBSD and NetBSD platforms implementation.""" + +import contextlib +import errno +import functools +import os +from collections import defaultdict +from collections import namedtuple +from xml.etree import ElementTree # noqa: ICN001 + +from . import _common +from . import _psposix +from . import _psutil_bsd as cext +from . import _psutil_posix as cext_posix +from ._common import FREEBSD +from ._common import NETBSD +from ._common import OPENBSD +from ._common import AccessDenied +from ._common import NoSuchProcess +from ._common import ZombieProcess +from ._common import conn_tmap +from ._common import conn_to_ntuple +from ._common import debug +from ._common import memoize +from ._common import memoize_when_activated +from ._common import usage_percent + + +__extra__all__ = [] + + +# ===================================================================== +# --- globals +# ===================================================================== + + +if FREEBSD: + PROC_STATUSES = { + cext.SIDL: _common.STATUS_IDLE, + cext.SRUN: _common.STATUS_RUNNING, + cext.SSLEEP: _common.STATUS_SLEEPING, + cext.SSTOP: _common.STATUS_STOPPED, + cext.SZOMB: _common.STATUS_ZOMBIE, + cext.SWAIT: _common.STATUS_WAITING, + cext.SLOCK: _common.STATUS_LOCKED, + } +elif OPENBSD: + PROC_STATUSES = { + cext.SIDL: _common.STATUS_IDLE, + cext.SSLEEP: _common.STATUS_SLEEPING, + cext.SSTOP: _common.STATUS_STOPPED, + # According to /usr/include/sys/proc.h SZOMB is unused. + # test_zombie_process() shows that SDEAD is the right + # equivalent. Also it appears there's no equivalent of + # psutil.STATUS_DEAD. SDEAD really means STATUS_ZOMBIE. + # cext.SZOMB: _common.STATUS_ZOMBIE, + cext.SDEAD: _common.STATUS_ZOMBIE, + cext.SZOMB: _common.STATUS_ZOMBIE, + # From http://www.eecs.harvard.edu/~margo/cs161/videos/proc.h.txt + # OpenBSD has SRUN and SONPROC: SRUN indicates that a process + # is runnable but *not* yet running, i.e. is on a run queue. + # SONPROC indicates that the process is actually executing on + # a CPU, i.e. it is no longer on a run queue. + # As such we'll map SRUN to STATUS_WAKING and SONPROC to + # STATUS_RUNNING + cext.SRUN: _common.STATUS_WAKING, + cext.SONPROC: _common.STATUS_RUNNING, + } +elif NETBSD: + PROC_STATUSES = { + cext.SIDL: _common.STATUS_IDLE, + cext.SSLEEP: _common.STATUS_SLEEPING, + cext.SSTOP: _common.STATUS_STOPPED, + cext.SZOMB: _common.STATUS_ZOMBIE, + cext.SRUN: _common.STATUS_WAKING, + cext.SONPROC: _common.STATUS_RUNNING, + } + +TCP_STATUSES = { + cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED, + cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT, + cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV, + cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1, + cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2, + cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT, + cext.TCPS_CLOSED: _common.CONN_CLOSE, + cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, + cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK, + cext.TCPS_LISTEN: _common.CONN_LISTEN, + cext.TCPS_CLOSING: _common.CONN_CLOSING, + cext.PSUTIL_CONN_NONE: _common.CONN_NONE, +} + +PAGESIZE = cext_posix.getpagesize() +AF_LINK = cext_posix.AF_LINK + +HAS_PER_CPU_TIMES = hasattr(cext, "per_cpu_times") +HAS_PROC_NUM_THREADS = hasattr(cext, "proc_num_threads") +HAS_PROC_OPEN_FILES = hasattr(cext, 'proc_open_files') +HAS_PROC_NUM_FDS = hasattr(cext, 'proc_num_fds') + +kinfo_proc_map = dict( + ppid=0, + status=1, + real_uid=2, + effective_uid=3, + saved_uid=4, + real_gid=5, + effective_gid=6, + saved_gid=7, + ttynr=8, + create_time=9, + ctx_switches_vol=10, + ctx_switches_unvol=11, + read_io_count=12, + write_io_count=13, + user_time=14, + sys_time=15, + ch_user_time=16, + ch_sys_time=17, + rss=18, + vms=19, + memtext=20, + memdata=21, + memstack=22, + cpunum=23, + name=24, +) + + +# ===================================================================== +# --- named tuples +# ===================================================================== + + +# fmt: off +# psutil.virtual_memory() +svmem = namedtuple( + 'svmem', ['total', 'available', 'percent', 'used', 'free', + 'active', 'inactive', 'buffers', 'cached', 'shared', 'wired']) +# psutil.cpu_times() +scputimes = namedtuple( + 'scputimes', ['user', 'nice', 'system', 'idle', 'irq']) +# psutil.Process.memory_info() +pmem = namedtuple('pmem', ['rss', 'vms', 'text', 'data', 'stack']) +# psutil.Process.memory_full_info() +pfullmem = pmem +# psutil.Process.cpu_times() +pcputimes = namedtuple('pcputimes', + ['user', 'system', 'children_user', 'children_system']) +# psutil.Process.memory_maps(grouped=True) +pmmap_grouped = namedtuple( + 'pmmap_grouped', 'path rss, private, ref_count, shadow_count') +# psutil.Process.memory_maps(grouped=False) +pmmap_ext = namedtuple( + 'pmmap_ext', 'addr, perms path rss, private, ref_count, shadow_count') +# psutil.disk_io_counters() +if FREEBSD: + sdiskio = namedtuple('sdiskio', ['read_count', 'write_count', + 'read_bytes', 'write_bytes', + 'read_time', 'write_time', + 'busy_time']) +else: + sdiskio = namedtuple('sdiskio', ['read_count', 'write_count', + 'read_bytes', 'write_bytes']) +# fmt: on + + +# ===================================================================== +# --- memory +# ===================================================================== + + +def virtual_memory(): + mem = cext.virtual_mem() + if NETBSD: + total, free, active, inactive, wired, cached = mem + # On NetBSD buffers and shared mem is determined via /proc. + # The C ext set them to 0. + with open('/proc/meminfo', 'rb') as f: + for line in f: + if line.startswith(b'Buffers:'): + buffers = int(line.split()[1]) * 1024 + elif line.startswith(b'MemShared:'): + shared = int(line.split()[1]) * 1024 + # Before avail was calculated as (inactive + cached + free), + # same as zabbix, but it turned out it could exceed total (see + # #2233), so zabbix seems to be wrong. Htop calculates it + # differently, and the used value seem more realistic, so let's + # match htop. + # https://github.com/htop-dev/htop/blob/e7f447b/netbsd/NetBSDProcessList.c#L162 + # https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L135 + used = active + wired + avail = total - used + else: + total, free, active, inactive, wired, cached, buffers, shared = mem + # matches freebsd-memory CLI: + # * https://people.freebsd.org/~rse/dist/freebsd-memory + # * https://www.cyberciti.biz/files/scripts/freebsd-memory.pl.txt + # matches zabbix: + # * https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/freebsd/memory.c#L143 + avail = inactive + cached + free + used = active + wired + cached + + percent = usage_percent((total - avail), total, round_=1) + return svmem( + total, + avail, + percent, + used, + free, + active, + inactive, + buffers, + cached, + shared, + wired, + ) + + +def swap_memory(): + """System swap memory as (total, used, free, sin, sout) namedtuple.""" + total, used, free, sin, sout = cext.swap_mem() + percent = usage_percent(used, total, round_=1) + return _common.sswap(total, used, free, percent, sin, sout) + + +# ===================================================================== +# --- CPU +# ===================================================================== + + +def cpu_times(): + """Return system per-CPU times as a namedtuple.""" + user, nice, system, idle, irq = cext.cpu_times() + return scputimes(user, nice, system, idle, irq) + + +if HAS_PER_CPU_TIMES: + + def per_cpu_times(): + """Return system CPU times as a namedtuple.""" + ret = [] + for cpu_t in cext.per_cpu_times(): + user, nice, system, idle, irq = cpu_t + item = scputimes(user, nice, system, idle, irq) + ret.append(item) + return ret + +else: + # XXX + # Ok, this is very dirty. + # On FreeBSD < 8 we cannot gather per-cpu information, see: + # https://github.com/giampaolo/psutil/issues/226 + # If num cpus > 1, on first call we return single cpu times to avoid a + # crash at psutil import time. + # Next calls will fail with NotImplementedError + def per_cpu_times(): + """Return system CPU times as a namedtuple.""" + if cpu_count_logical() == 1: + return [cpu_times()] + if per_cpu_times.__called__: + msg = "supported only starting from FreeBSD 8" + raise NotImplementedError(msg) + per_cpu_times.__called__ = True + return [cpu_times()] + + per_cpu_times.__called__ = False + + +def cpu_count_logical(): + """Return the number of logical CPUs in the system.""" + return cext.cpu_count_logical() + + +if OPENBSD or NETBSD: + + def cpu_count_cores(): + # OpenBSD and NetBSD do not implement this. + return 1 if cpu_count_logical() == 1 else None + +else: + + def cpu_count_cores(): + """Return the number of CPU cores in the system.""" + # From the C module we'll get an XML string similar to this: + # http://manpages.ubuntu.com/manpages/precise/man4/smp.4freebsd.html + # We may get None in case "sysctl kern.sched.topology_spec" + # is not supported on this BSD version, in which case we'll mimic + # os.cpu_count() and return None. + ret = None + s = cext.cpu_topology() + if s is not None: + # get rid of padding chars appended at the end of the string + index = s.rfind("") + if index != -1: + s = s[: index + 9] + root = ElementTree.fromstring(s) + try: + ret = len(root.findall('group/children/group/cpu')) or None + finally: + # needed otherwise it will memleak + root.clear() + if not ret: + # If logical CPUs == 1 it's obvious we' have only 1 core. + if cpu_count_logical() == 1: + return 1 + return ret + + +def cpu_stats(): + """Return various CPU stats as a named tuple.""" + if FREEBSD: + # Note: the C ext is returning some metrics we are not exposing: + # traps. + ctxsw, intrs, soft_intrs, syscalls, _traps = cext.cpu_stats() + elif NETBSD: + # XXX + # Note about intrs: the C extension returns 0. intrs + # can be determined via /proc/stat; it has the same value as + # soft_intrs thought so the kernel is faking it (?). + # + # Note about syscalls: the C extension always sets it to 0 (?). + # + # Note: the C ext is returning some metrics we are not exposing: + # traps, faults and forks. + ctxsw, intrs, soft_intrs, syscalls, _traps, _faults, _forks = ( + cext.cpu_stats() + ) + with open('/proc/stat', 'rb') as f: + for line in f: + if line.startswith(b'intr'): + intrs = int(line.split()[1]) + elif OPENBSD: + # Note: the C ext is returning some metrics we are not exposing: + # traps, faults and forks. + ctxsw, intrs, soft_intrs, syscalls, _traps, _faults, _forks = ( + cext.cpu_stats() + ) + return _common.scpustats(ctxsw, intrs, soft_intrs, syscalls) + + +if FREEBSD: + + def cpu_freq(): + """Return frequency metrics for CPUs. As of Dec 2018 only + CPU 0 appears to be supported by FreeBSD and all other cores + match the frequency of CPU 0. + """ + ret = [] + num_cpus = cpu_count_logical() + for cpu in range(num_cpus): + try: + current, available_freq = cext.cpu_freq(cpu) + except NotImplementedError: + continue + if available_freq: + try: + min_freq = int(available_freq.split(" ")[-1].split("/")[0]) + except (IndexError, ValueError): + min_freq = None + try: + max_freq = int(available_freq.split(" ")[0].split("/")[0]) + except (IndexError, ValueError): + max_freq = None + ret.append(_common.scpufreq(current, min_freq, max_freq)) + return ret + +elif OPENBSD: + + def cpu_freq(): + curr = float(cext.cpu_freq()) + return [_common.scpufreq(curr, 0.0, 0.0)] + + +# ===================================================================== +# --- disks +# ===================================================================== + + +def disk_partitions(all=False): + """Return mounted disk partitions as a list of namedtuples. + 'all' argument is ignored, see: + https://github.com/giampaolo/psutil/issues/906. + """ + retlist = [] + partitions = cext.disk_partitions() + for partition in partitions: + device, mountpoint, fstype, opts = partition + ntuple = _common.sdiskpart(device, mountpoint, fstype, opts) + retlist.append(ntuple) + return retlist + + +disk_usage = _psposix.disk_usage +disk_io_counters = cext.disk_io_counters + + +# ===================================================================== +# --- network +# ===================================================================== + + +net_io_counters = cext.net_io_counters +net_if_addrs = cext_posix.net_if_addrs + + +def net_if_stats(): + """Get NIC stats (isup, duplex, speed, mtu).""" + names = net_io_counters().keys() + ret = {} + for name in names: + try: + mtu = cext_posix.net_if_mtu(name) + flags = cext_posix.net_if_flags(name) + duplex, speed = cext_posix.net_if_duplex_speed(name) + except OSError as err: + # https://github.com/giampaolo/psutil/issues/1279 + if err.errno != errno.ENODEV: + raise + else: + if hasattr(_common, 'NicDuplex'): + duplex = _common.NicDuplex(duplex) + output_flags = ','.join(flags) + isup = 'running' in flags + ret[name] = _common.snicstats( + isup, duplex, speed, mtu, output_flags + ) + return ret + + +def net_connections(kind): + """System-wide network connections.""" + families, types = conn_tmap[kind] + ret = set() + if OPENBSD: + rawlist = cext.net_connections(-1, families, types) + elif NETBSD: + rawlist = cext.net_connections(-1, kind) + else: # FreeBSD + rawlist = cext.net_connections(families, types) + + for item in rawlist: + fd, fam, type, laddr, raddr, status, pid = item + nt = conn_to_ntuple( + fd, fam, type, laddr, raddr, status, TCP_STATUSES, pid + ) + ret.add(nt) + return list(ret) + + +# ===================================================================== +# --- sensors +# ===================================================================== + + +if FREEBSD: + + def sensors_battery(): + """Return battery info.""" + try: + percent, minsleft, power_plugged = cext.sensors_battery() + except NotImplementedError: + # See: https://github.com/giampaolo/psutil/issues/1074 + return None + power_plugged = power_plugged == 1 + if power_plugged: + secsleft = _common.POWER_TIME_UNLIMITED + elif minsleft == -1: + secsleft = _common.POWER_TIME_UNKNOWN + else: + secsleft = minsleft * 60 + return _common.sbattery(percent, secsleft, power_plugged) + + def sensors_temperatures(): + """Return CPU cores temperatures if available, else an empty dict.""" + ret = defaultdict(list) + num_cpus = cpu_count_logical() + for cpu in range(num_cpus): + try: + current, high = cext.sensors_cpu_temperature(cpu) + if high <= 0: + high = None + name = f"Core {cpu}" + ret["coretemp"].append( + _common.shwtemp(name, current, high, high) + ) + except NotImplementedError: + pass + + return ret + + +# ===================================================================== +# --- other system functions +# ===================================================================== + + +def boot_time(): + """The system boot time expressed in seconds since the epoch.""" + return cext.boot_time() + + +def users(): + """Return currently connected users as a list of namedtuples.""" + retlist = [] + rawlist = cext.users() + for item in rawlist: + user, tty, hostname, tstamp, pid = item + if pid == -1: + assert OPENBSD + pid = None + if tty == '~': + continue # reboot or shutdown + nt = _common.suser(user, tty or None, hostname, tstamp, pid) + retlist.append(nt) + return retlist + + +# ===================================================================== +# --- processes +# ===================================================================== + + +@memoize +def _pid_0_exists(): + try: + Process(0).name() + except NoSuchProcess: + return False + except AccessDenied: + return True + else: + return True + + +def pids(): + """Returns a list of PIDs currently running on the system.""" + ret = cext.pids() + if OPENBSD and (0 not in ret) and _pid_0_exists(): + # On OpenBSD the kernel does not return PID 0 (neither does + # ps) but it's actually querable (Process(0) will succeed). + ret.insert(0, 0) + return ret + + +if NETBSD: + + def pid_exists(pid): + exists = _psposix.pid_exists(pid) + if not exists: + # We do this because _psposix.pid_exists() lies in case of + # zombie processes. + return pid in pids() + else: + return True + +elif OPENBSD: + + def pid_exists(pid): + exists = _psposix.pid_exists(pid) + if not exists: + return False + else: + # OpenBSD seems to be the only BSD platform where + # _psposix.pid_exists() returns True for thread IDs (tids), + # so we can't use it. + return pid in pids() + +else: # FreeBSD + pid_exists = _psposix.pid_exists + + +def is_zombie(pid): + try: + st = cext.proc_oneshot_info(pid)[kinfo_proc_map['status']] + return PROC_STATUSES.get(st) == _common.STATUS_ZOMBIE + except OSError: + return False + + +def wrap_exceptions(fun): + """Decorator which translates bare OSError exceptions into + NoSuchProcess and AccessDenied. + """ + + @functools.wraps(fun) + def wrapper(self, *args, **kwargs): + pid, ppid, name = self.pid, self._ppid, self._name + try: + return fun(self, *args, **kwargs) + except ProcessLookupError as err: + if is_zombie(pid): + raise ZombieProcess(pid, name, ppid) from err + raise NoSuchProcess(pid, name) from err + except PermissionError as err: + raise AccessDenied(pid, name) from err + except OSError as err: + if pid == 0 and 0 in pids(): + raise AccessDenied(pid, name) from err + raise + + return wrapper + + +@contextlib.contextmanager +def wrap_exceptions_procfs(inst): + """Same as above, for routines relying on reading /proc fs.""" + pid, name, ppid = inst.pid, inst._name, inst._ppid + try: + yield + except (ProcessLookupError, FileNotFoundError) as err: + # ENOENT (no such file or directory) gets raised on open(). + # ESRCH (no such process) can get raised on read() if + # process is gone in meantime. + if is_zombie(inst.pid): + raise ZombieProcess(pid, name, ppid) from err + else: + raise NoSuchProcess(pid, name) from err + except PermissionError as err: + raise AccessDenied(pid, name) from err + + +class Process: + """Wrapper class around underlying C implementation.""" + + __slots__ = ["_cache", "_name", "_ppid", "pid"] + + def __init__(self, pid): + self.pid = pid + self._name = None + self._ppid = None + + def _assert_alive(self): + """Raise NSP if the process disappeared on us.""" + # For those C function who do not raise NSP, possibly returning + # incorrect or incomplete result. + cext.proc_name(self.pid) + + @wrap_exceptions + @memoize_when_activated + def oneshot(self): + """Retrieves multiple process info in one shot as a raw tuple.""" + ret = cext.proc_oneshot_info(self.pid) + assert len(ret) == len(kinfo_proc_map) + return ret + + def oneshot_enter(self): + self.oneshot.cache_activate(self) + + def oneshot_exit(self): + self.oneshot.cache_deactivate(self) + + @wrap_exceptions + def name(self): + name = self.oneshot()[kinfo_proc_map['name']] + return name if name is not None else cext.proc_name(self.pid) + + @wrap_exceptions + def exe(self): + if FREEBSD: + if self.pid == 0: + return '' # else NSP + return cext.proc_exe(self.pid) + elif NETBSD: + if self.pid == 0: + # /proc/0 dir exists but /proc/0/exe doesn't + return "" + with wrap_exceptions_procfs(self): + return os.readlink(f"/proc/{self.pid}/exe") + else: + # OpenBSD: exe cannot be determined; references: + # https://chromium.googlesource.com/chromium/src/base/+/ + # master/base_paths_posix.cc + # We try our best guess by using which against the first + # cmdline arg (may return None). + import shutil + + cmdline = self.cmdline() + if cmdline: + return shutil.which(cmdline[0]) or "" + else: + return "" + + @wrap_exceptions + def cmdline(self): + if OPENBSD and self.pid == 0: + return [] # ...else it crashes + elif NETBSD: + # XXX - most of the times the underlying sysctl() call on + # NetBSD and OpenBSD returns a truncated string. Also + # /proc/pid/cmdline behaves the same so it looks like this + # is a kernel bug. + try: + return cext.proc_cmdline(self.pid) + except OSError as err: + if err.errno == errno.EINVAL: + pid, name, ppid = self.pid, self._name, self._ppid + if is_zombie(self.pid): + raise ZombieProcess(pid, name, ppid) from err + if not pid_exists(self.pid): + raise NoSuchProcess(pid, name, ppid) from err + # XXX: this happens with unicode tests. It means the C + # routine is unable to decode invalid unicode chars. + debug(f"ignoring {err!r} and returning an empty list") + return [] + else: + raise + else: + return cext.proc_cmdline(self.pid) + + @wrap_exceptions + def environ(self): + return cext.proc_environ(self.pid) + + @wrap_exceptions + def terminal(self): + tty_nr = self.oneshot()[kinfo_proc_map['ttynr']] + tmap = _psposix.get_terminal_map() + try: + return tmap[tty_nr] + except KeyError: + return None + + @wrap_exceptions + def ppid(self): + self._ppid = self.oneshot()[kinfo_proc_map['ppid']] + return self._ppid + + @wrap_exceptions + def uids(self): + rawtuple = self.oneshot() + return _common.puids( + rawtuple[kinfo_proc_map['real_uid']], + rawtuple[kinfo_proc_map['effective_uid']], + rawtuple[kinfo_proc_map['saved_uid']], + ) + + @wrap_exceptions + def gids(self): + rawtuple = self.oneshot() + return _common.pgids( + rawtuple[kinfo_proc_map['real_gid']], + rawtuple[kinfo_proc_map['effective_gid']], + rawtuple[kinfo_proc_map['saved_gid']], + ) + + @wrap_exceptions + def cpu_times(self): + rawtuple = self.oneshot() + return _common.pcputimes( + rawtuple[kinfo_proc_map['user_time']], + rawtuple[kinfo_proc_map['sys_time']], + rawtuple[kinfo_proc_map['ch_user_time']], + rawtuple[kinfo_proc_map['ch_sys_time']], + ) + + if FREEBSD: + + @wrap_exceptions + def cpu_num(self): + return self.oneshot()[kinfo_proc_map['cpunum']] + + @wrap_exceptions + def memory_info(self): + rawtuple = self.oneshot() + return pmem( + rawtuple[kinfo_proc_map['rss']], + rawtuple[kinfo_proc_map['vms']], + rawtuple[kinfo_proc_map['memtext']], + rawtuple[kinfo_proc_map['memdata']], + rawtuple[kinfo_proc_map['memstack']], + ) + + memory_full_info = memory_info + + @wrap_exceptions + def create_time(self): + return self.oneshot()[kinfo_proc_map['create_time']] + + @wrap_exceptions + def num_threads(self): + if HAS_PROC_NUM_THREADS: + # FreeBSD + return cext.proc_num_threads(self.pid) + else: + return len(self.threads()) + + @wrap_exceptions + def num_ctx_switches(self): + rawtuple = self.oneshot() + return _common.pctxsw( + rawtuple[kinfo_proc_map['ctx_switches_vol']], + rawtuple[kinfo_proc_map['ctx_switches_unvol']], + ) + + @wrap_exceptions + def threads(self): + # Note: on OpenSBD this (/dev/mem) requires root access. + rawlist = cext.proc_threads(self.pid) + retlist = [] + for thread_id, utime, stime in rawlist: + ntuple = _common.pthread(thread_id, utime, stime) + retlist.append(ntuple) + if OPENBSD: + self._assert_alive() + return retlist + + @wrap_exceptions + def net_connections(self, kind='inet'): + families, types = conn_tmap[kind] + ret = [] + + if NETBSD: + rawlist = cext.net_connections(self.pid, kind) + elif OPENBSD: + rawlist = cext.net_connections(self.pid, families, types) + else: + rawlist = cext.proc_net_connections(self.pid, families, types) + + for item in rawlist: + fd, fam, type, laddr, raddr, status = item[:6] + if FREEBSD: + if (fam not in families) or (type not in types): + continue + nt = conn_to_ntuple( + fd, fam, type, laddr, raddr, status, TCP_STATUSES + ) + ret.append(nt) + + self._assert_alive() + return ret + + @wrap_exceptions + def wait(self, timeout=None): + return _psposix.wait_pid(self.pid, timeout, self._name) + + @wrap_exceptions + def nice_get(self): + return cext_posix.getpriority(self.pid) + + @wrap_exceptions + def nice_set(self, value): + return cext_posix.setpriority(self.pid, value) + + @wrap_exceptions + def status(self): + code = self.oneshot()[kinfo_proc_map['status']] + # XXX is '?' legit? (we're not supposed to return it anyway) + return PROC_STATUSES.get(code, '?') + + @wrap_exceptions + def io_counters(self): + rawtuple = self.oneshot() + return _common.pio( + rawtuple[kinfo_proc_map['read_io_count']], + rawtuple[kinfo_proc_map['write_io_count']], + -1, + -1, + ) + + @wrap_exceptions + def cwd(self): + """Return process current working directory.""" + # sometimes we get an empty string, in which case we turn + # it into None + if OPENBSD and self.pid == 0: + return "" # ...else it would raise EINVAL + elif NETBSD or HAS_PROC_OPEN_FILES: + # FreeBSD < 8 does not support functions based on + # kinfo_getfile() and kinfo_getvmmap() + return cext.proc_cwd(self.pid) + else: + raise NotImplementedError( + "supported only starting from FreeBSD 8" if FREEBSD else "" + ) + + nt_mmap_grouped = namedtuple( + 'mmap', 'path rss, private, ref_count, shadow_count' + ) + nt_mmap_ext = namedtuple( + 'mmap', 'addr, perms path rss, private, ref_count, shadow_count' + ) + + def _not_implemented(self): + raise NotImplementedError + + # FreeBSD < 8 does not support functions based on kinfo_getfile() + # and kinfo_getvmmap() + if HAS_PROC_OPEN_FILES: + + @wrap_exceptions + def open_files(self): + """Return files opened by process as a list of namedtuples.""" + rawlist = cext.proc_open_files(self.pid) + return [_common.popenfile(path, fd) for path, fd in rawlist] + + else: + open_files = _not_implemented + + # FreeBSD < 8 does not support functions based on kinfo_getfile() + # and kinfo_getvmmap() + if HAS_PROC_NUM_FDS: + + @wrap_exceptions + def num_fds(self): + """Return the number of file descriptors opened by this process.""" + ret = cext.proc_num_fds(self.pid) + if NETBSD: + self._assert_alive() + return ret + + else: + num_fds = _not_implemented + + # --- FreeBSD only APIs + + if FREEBSD: + + @wrap_exceptions + def cpu_affinity_get(self): + return cext.proc_cpu_affinity_get(self.pid) + + @wrap_exceptions + def cpu_affinity_set(self, cpus): + # Pre-emptively check if CPUs are valid because the C + # function has a weird behavior in case of invalid CPUs, + # see: https://github.com/giampaolo/psutil/issues/586 + allcpus = set(range(len(per_cpu_times()))) + for cpu in cpus: + if cpu not in allcpus: + msg = f"invalid CPU {cpu!r} (choose between {allcpus})" + raise ValueError(msg) + try: + cext.proc_cpu_affinity_set(self.pid, cpus) + except OSError as err: + # 'man cpuset_setaffinity' about EDEADLK: + # <> + if err.errno in {errno.EINVAL, errno.EDEADLK}: + for cpu in cpus: + if cpu not in allcpus: + msg = ( + f"invalid CPU {cpu!r} (choose between" + f" {allcpus})" + ) + raise ValueError(msg) from err + raise + + @wrap_exceptions + def memory_maps(self): + return cext.proc_memory_maps(self.pid) + + @wrap_exceptions + def rlimit(self, resource, limits=None): + if limits is None: + return cext.proc_getrlimit(self.pid, resource) + else: + if len(limits) != 2: + msg = ( + "second argument must be a (soft, hard) tuple, got" + f" {limits!r}" + ) + raise ValueError(msg) + soft, hard = limits + return cext.proc_setrlimit(self.pid, resource, soft, hard) diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_pslinux.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_pslinux.py new file mode 100644 index 0000000000000000000000000000000000000000..8cc64e9a1000bddf5dde795868dcdcb782c35a1c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_pslinux.py @@ -0,0 +1,2295 @@ +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Linux platform implementation.""" + + +import base64 +import collections +import enum +import errno +import functools +import glob +import os +import re +import resource +import socket +import struct +import sys +import warnings +from collections import defaultdict +from collections import namedtuple + +from . import _common +from . import _psposix +from . import _psutil_linux as cext +from . import _psutil_posix as cext_posix +from ._common import ENCODING +from ._common import NIC_DUPLEX_FULL +from ._common import NIC_DUPLEX_HALF +from ._common import NIC_DUPLEX_UNKNOWN +from ._common import AccessDenied +from ._common import NoSuchProcess +from ._common import ZombieProcess +from ._common import bcat +from ._common import cat +from ._common import debug +from ._common import decode +from ._common import get_procfs_path +from ._common import isfile_strict +from ._common import memoize +from ._common import memoize_when_activated +from ._common import open_binary +from ._common import open_text +from ._common import parse_environ_block +from ._common import path_exists_strict +from ._common import supports_ipv6 +from ._common import usage_percent + + +# fmt: off +__extra__all__ = [ + 'PROCFS_PATH', + # io prio constants + "IOPRIO_CLASS_NONE", "IOPRIO_CLASS_RT", "IOPRIO_CLASS_BE", + "IOPRIO_CLASS_IDLE", + # connection status constants + "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1", + "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT", + "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", +] + +if hasattr(resource, "prlimit"): + __extra__all__.extend( + [x for x in dir(cext) if x.startswith('RLIM') and x.isupper()] + ) +# fmt: on + + +# ===================================================================== +# --- globals +# ===================================================================== + + +POWER_SUPPLY_PATH = "/sys/class/power_supply" +HAS_PROC_SMAPS = os.path.exists(f"/proc/{os.getpid()}/smaps") +HAS_PROC_SMAPS_ROLLUP = os.path.exists(f"/proc/{os.getpid()}/smaps_rollup") +HAS_PROC_IO_PRIORITY = hasattr(cext, "proc_ioprio_get") +HAS_CPU_AFFINITY = hasattr(cext, "proc_cpu_affinity_get") + +# Number of clock ticks per second +CLOCK_TICKS = os.sysconf("SC_CLK_TCK") +PAGESIZE = cext_posix.getpagesize() +BOOT_TIME = None # set later +LITTLE_ENDIAN = sys.byteorder == 'little' + +# "man iostat" states that sectors are equivalent with blocks and have +# a size of 512 bytes. Despite this value can be queried at runtime +# via /sys/block/{DISK}/queue/hw_sector_size and results may vary +# between 1k, 2k, or 4k... 512 appears to be a magic constant used +# throughout Linux source code: +# * https://stackoverflow.com/a/38136179/376587 +# * https://lists.gt.net/linux/kernel/2241060 +# * https://github.com/giampaolo/psutil/issues/1305 +# * https://github.com/torvalds/linux/blob/ +# 4f671fe2f9523a1ea206f63fe60a7c7b3a56d5c7/include/linux/bio.h#L99 +# * https://lkml.org/lkml/2015/8/17/234 +DISK_SECTOR_SIZE = 512 + +AddressFamily = enum.IntEnum( + 'AddressFamily', {'AF_LINK': int(socket.AF_PACKET)} +) +AF_LINK = AddressFamily.AF_LINK + + +# ioprio_* constants http://linux.die.net/man/2/ioprio_get +class IOPriority(enum.IntEnum): + IOPRIO_CLASS_NONE = 0 + IOPRIO_CLASS_RT = 1 + IOPRIO_CLASS_BE = 2 + IOPRIO_CLASS_IDLE = 3 + + +globals().update(IOPriority.__members__) + +# See: +# https://github.com/torvalds/linux/blame/master/fs/proc/array.c +# ...and (TASK_* constants): +# https://github.com/torvalds/linux/blob/master/include/linux/sched.h +PROC_STATUSES = { + "R": _common.STATUS_RUNNING, + "S": _common.STATUS_SLEEPING, + "D": _common.STATUS_DISK_SLEEP, + "T": _common.STATUS_STOPPED, + "t": _common.STATUS_TRACING_STOP, + "Z": _common.STATUS_ZOMBIE, + "X": _common.STATUS_DEAD, + "x": _common.STATUS_DEAD, + "K": _common.STATUS_WAKE_KILL, + "W": _common.STATUS_WAKING, + "I": _common.STATUS_IDLE, + "P": _common.STATUS_PARKED, +} + +# https://github.com/torvalds/linux/blob/master/include/net/tcp_states.h +TCP_STATUSES = { + "01": _common.CONN_ESTABLISHED, + "02": _common.CONN_SYN_SENT, + "03": _common.CONN_SYN_RECV, + "04": _common.CONN_FIN_WAIT1, + "05": _common.CONN_FIN_WAIT2, + "06": _common.CONN_TIME_WAIT, + "07": _common.CONN_CLOSE, + "08": _common.CONN_CLOSE_WAIT, + "09": _common.CONN_LAST_ACK, + "0A": _common.CONN_LISTEN, + "0B": _common.CONN_CLOSING, +} + + +# ===================================================================== +# --- named tuples +# ===================================================================== + + +# fmt: off +# psutil.virtual_memory() +svmem = namedtuple( + 'svmem', ['total', 'available', 'percent', 'used', 'free', + 'active', 'inactive', 'buffers', 'cached', 'shared', 'slab']) +# psutil.disk_io_counters() +sdiskio = namedtuple( + 'sdiskio', ['read_count', 'write_count', + 'read_bytes', 'write_bytes', + 'read_time', 'write_time', + 'read_merged_count', 'write_merged_count', + 'busy_time']) +# psutil.Process().open_files() +popenfile = namedtuple( + 'popenfile', ['path', 'fd', 'position', 'mode', 'flags']) +# psutil.Process().memory_info() +pmem = namedtuple('pmem', 'rss vms shared text lib data dirty') +# psutil.Process().memory_full_info() +pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', 'pss', 'swap')) +# psutil.Process().memory_maps(grouped=True) +pmmap_grouped = namedtuple( + 'pmmap_grouped', + ['path', 'rss', 'size', 'pss', 'shared_clean', 'shared_dirty', + 'private_clean', 'private_dirty', 'referenced', 'anonymous', 'swap']) +# psutil.Process().memory_maps(grouped=False) +pmmap_ext = namedtuple( + 'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields)) +# psutil.Process.io_counters() +pio = namedtuple('pio', ['read_count', 'write_count', + 'read_bytes', 'write_bytes', + 'read_chars', 'write_chars']) +# psutil.Process.cpu_times() +pcputimes = namedtuple('pcputimes', + ['user', 'system', 'children_user', 'children_system', + 'iowait']) +# fmt: on + + +# ===================================================================== +# --- utils +# ===================================================================== + + +def readlink(path): + """Wrapper around os.readlink().""" + assert isinstance(path, str), path + path = os.readlink(path) + # readlink() might return paths containing null bytes ('\x00') + # resulting in "TypeError: must be encoded string without NULL + # bytes, not str" errors when the string is passed to other + # fs-related functions (os.*, open(), ...). + # Apparently everything after '\x00' is garbage (we can have + # ' (deleted)', 'new' and possibly others), see: + # https://github.com/giampaolo/psutil/issues/717 + path = path.split('\x00')[0] + # Certain paths have ' (deleted)' appended. Usually this is + # bogus as the file actually exists. Even if it doesn't we + # don't care. + if path.endswith(' (deleted)') and not path_exists_strict(path): + path = path[:-10] + return path + + +def file_flags_to_mode(flags): + """Convert file's open() flags into a readable string. + Used by Process.open_files(). + """ + modes_map = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'} + mode = modes_map[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)] + if flags & os.O_APPEND: + mode = mode.replace('w', 'a', 1) + mode = mode.replace('w+', 'r+') + # possible values: r, w, a, r+, a+ + return mode + + +def is_storage_device(name): + """Return True if the given name refers to a root device (e.g. + "sda", "nvme0n1") as opposed to a logical partition (e.g. "sda1", + "nvme0n1p1"). If name is a virtual device (e.g. "loop1", "ram") + return True. + """ + # Re-adapted from iostat source code, see: + # https://github.com/sysstat/sysstat/blob/ + # 97912938cd476645b267280069e83b1c8dc0e1c7/common.c#L208 + # Some devices may have a slash in their name (e.g. cciss/c0d0...). + name = name.replace('/', '!') + including_virtual = True + if including_virtual: + path = f"/sys/block/{name}" + else: + path = f"/sys/block/{name}/device" + return os.access(path, os.F_OK) + + +@memoize +def set_scputimes_ntuple(procfs_path): + """Set a namedtuple of variable fields depending on the CPU times + available on this Linux kernel version which may be: + (user, nice, system, idle, iowait, irq, softirq, [steal, [guest, + [guest_nice]]]) + Used by cpu_times() function. + """ + global scputimes + with open_binary(f"{procfs_path}/stat") as f: + values = f.readline().split()[1:] + fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq'] + vlen = len(values) + if vlen >= 8: + # Linux >= 2.6.11 + fields.append('steal') + if vlen >= 9: + # Linux >= 2.6.24 + fields.append('guest') + if vlen >= 10: + # Linux >= 3.2.0 + fields.append('guest_nice') + scputimes = namedtuple('scputimes', fields) + + +try: + set_scputimes_ntuple("/proc") +except Exception as err: # noqa: BLE001 + # Don't want to crash at import time. + debug(f"ignoring exception on import: {err!r}") + scputimes = namedtuple('scputimes', 'user system idle')(0.0, 0.0, 0.0) + + +# ===================================================================== +# --- system memory +# ===================================================================== + + +def calculate_avail_vmem(mems): + """Fallback for kernels < 3.14 where /proc/meminfo does not provide + "MemAvailable", see: + https://blog.famzah.net/2014/09/24/. + + This code reimplements the algorithm outlined here: + https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/ + commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773 + + We use this function also when "MemAvailable" returns 0 (possibly a + kernel bug, see: https://github.com/giampaolo/psutil/issues/1915). + In that case this routine matches "free" CLI tool result ("available" + column). + + XXX: on recent kernels this calculation may differ by ~1.5% compared + to "MemAvailable:", as it's calculated slightly differently. + It is still way more realistic than doing (free + cached) though. + See: + * https://gitlab.com/procps-ng/procps/issues/42 + * https://github.com/famzah/linux-memavailable-procfs/issues/2 + """ + # Note about "fallback" value. According to: + # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/ + # commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773 + # ...long ago "available" memory was calculated as (free + cached), + # We use fallback when one of these is missing from /proc/meminfo: + # "Active(file)": introduced in 2.6.28 / Dec 2008 + # "Inactive(file)": introduced in 2.6.28 / Dec 2008 + # "SReclaimable": introduced in 2.6.19 / Nov 2006 + # /proc/zoneinfo: introduced in 2.6.13 / Aug 2005 + free = mems[b'MemFree:'] + fallback = free + mems.get(b"Cached:", 0) + try: + lru_active_file = mems[b'Active(file):'] + lru_inactive_file = mems[b'Inactive(file):'] + slab_reclaimable = mems[b'SReclaimable:'] + except KeyError as err: + debug( + f"{err.args[0]} is missing from /proc/meminfo; using an" + " approximation for calculating available memory" + ) + return fallback + try: + f = open_binary(f"{get_procfs_path()}/zoneinfo") + except OSError: + return fallback # kernel 2.6.13 + + watermark_low = 0 + with f: + for line in f: + line = line.strip() + if line.startswith(b'low'): + watermark_low += int(line.split()[1]) + watermark_low *= PAGESIZE + + avail = free - watermark_low + pagecache = lru_active_file + lru_inactive_file + pagecache -= min(pagecache / 2, watermark_low) + avail += pagecache + avail += slab_reclaimable - min(slab_reclaimable / 2.0, watermark_low) + return int(avail) + + +def virtual_memory(): + """Report virtual memory stats. + This implementation mimics procps-ng-3.3.12, aka "free" CLI tool: + https://gitlab.com/procps-ng/procps/blob/ + 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L778-791 + The returned values are supposed to match both "free" and "vmstat -s" + CLI tools. + """ + missing_fields = [] + mems = {} + with open_binary(f"{get_procfs_path()}/meminfo") as f: + for line in f: + fields = line.split() + mems[fields[0]] = int(fields[1]) * 1024 + + # /proc doc states that the available fields in /proc/meminfo vary + # by architecture and compile options, but these 3 values are also + # returned by sysinfo(2); as such we assume they are always there. + total = mems[b'MemTotal:'] + free = mems[b'MemFree:'] + try: + buffers = mems[b'Buffers:'] + except KeyError: + # https://github.com/giampaolo/psutil/issues/1010 + buffers = 0 + missing_fields.append('buffers') + try: + cached = mems[b"Cached:"] + except KeyError: + cached = 0 + missing_fields.append('cached') + else: + # "free" cmdline utility sums reclaimable to cached. + # Older versions of procps used to add slab memory instead. + # This got changed in: + # https://gitlab.com/procps-ng/procps/commit/ + # 05d751c4f076a2f0118b914c5e51cfbb4762ad8e + cached += mems.get(b"SReclaimable:", 0) # since kernel 2.6.19 + + try: + shared = mems[b'Shmem:'] # since kernel 2.6.32 + except KeyError: + try: + shared = mems[b'MemShared:'] # kernels 2.4 + except KeyError: + shared = 0 + missing_fields.append('shared') + + try: + active = mems[b"Active:"] + except KeyError: + active = 0 + missing_fields.append('active') + + try: + inactive = mems[b"Inactive:"] + except KeyError: + try: + inactive = ( + mems[b"Inact_dirty:"] + + mems[b"Inact_clean:"] + + mems[b"Inact_laundry:"] + ) + except KeyError: + inactive = 0 + missing_fields.append('inactive') + + try: + slab = mems[b"Slab:"] + except KeyError: + slab = 0 + + used = total - free - cached - buffers + if used < 0: + # May be symptomatic of running within a LCX container where such + # values will be dramatically distorted over those of the host. + used = total - free + + # - starting from 4.4.0 we match free's "available" column. + # Before 4.4.0 we calculated it as (free + buffers + cached) + # which matched htop. + # - free and htop available memory differs as per: + # http://askubuntu.com/a/369589 + # http://unix.stackexchange.com/a/65852/168884 + # - MemAvailable has been introduced in kernel 3.14 + try: + avail = mems[b'MemAvailable:'] + except KeyError: + avail = calculate_avail_vmem(mems) + else: + if avail == 0: + # Yes, it can happen (probably a kernel bug): + # https://github.com/giampaolo/psutil/issues/1915 + # In this case "free" CLI tool makes an estimate. We do the same, + # and it matches "free" CLI tool. + avail = calculate_avail_vmem(mems) + + if avail < 0: + avail = 0 + missing_fields.append('available') + elif avail > total: + # If avail is greater than total or our calculation overflows, + # that's symptomatic of running within a LCX container where such + # values will be dramatically distorted over those of the host. + # https://gitlab.com/procps-ng/procps/blob/ + # 24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L764 + avail = free + + percent = usage_percent((total - avail), total, round_=1) + + # Warn about missing metrics which are set to 0. + if missing_fields: + msg = "{} memory stats couldn't be determined and {} set to 0".format( + ", ".join(missing_fields), + "was" if len(missing_fields) == 1 else "were", + ) + warnings.warn(msg, RuntimeWarning, stacklevel=2) + + return svmem( + total, + avail, + percent, + used, + free, + active, + inactive, + buffers, + cached, + shared, + slab, + ) + + +def swap_memory(): + """Return swap memory metrics.""" + mems = {} + with open_binary(f"{get_procfs_path()}/meminfo") as f: + for line in f: + fields = line.split() + mems[fields[0]] = int(fields[1]) * 1024 + # We prefer /proc/meminfo over sysinfo() syscall so that + # psutil.PROCFS_PATH can be used in order to allow retrieval + # for linux containers, see: + # https://github.com/giampaolo/psutil/issues/1015 + try: + total = mems[b'SwapTotal:'] + free = mems[b'SwapFree:'] + except KeyError: + _, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo() + total *= unit_multiplier + free *= unit_multiplier + + used = total - free + percent = usage_percent(used, total, round_=1) + # get pgin/pgouts + try: + f = open_binary(f"{get_procfs_path()}/vmstat") + except OSError as err: + # see https://github.com/giampaolo/psutil/issues/722 + msg = ( + "'sin' and 'sout' swap memory stats couldn't " + f"be determined and were set to 0 ({err})" + ) + warnings.warn(msg, RuntimeWarning, stacklevel=2) + sin = sout = 0 + else: + with f: + sin = sout = None + for line in f: + # values are expressed in 4 kilo bytes, we want + # bytes instead + if line.startswith(b'pswpin'): + sin = int(line.split(b' ')[1]) * 4 * 1024 + elif line.startswith(b'pswpout'): + sout = int(line.split(b' ')[1]) * 4 * 1024 + if sin is not None and sout is not None: + break + else: + # we might get here when dealing with exotic Linux + # flavors, see: + # https://github.com/giampaolo/psutil/issues/313 + msg = "'sin' and 'sout' swap memory stats couldn't " + msg += "be determined and were set to 0" + warnings.warn(msg, RuntimeWarning, stacklevel=2) + sin = sout = 0 + return _common.sswap(total, used, free, percent, sin, sout) + + +# ===================================================================== +# --- CPU +# ===================================================================== + + +def cpu_times(): + """Return a named tuple representing the following system-wide + CPU times: + (user, nice, system, idle, iowait, irq, softirq [steal, [guest, + [guest_nice]]]) + Last 3 fields may not be available on all Linux kernel versions. + """ + procfs_path = get_procfs_path() + set_scputimes_ntuple(procfs_path) + with open_binary(f"{procfs_path}/stat") as f: + values = f.readline().split() + fields = values[1 : len(scputimes._fields) + 1] + fields = [float(x) / CLOCK_TICKS for x in fields] + return scputimes(*fields) + + +def per_cpu_times(): + """Return a list of namedtuple representing the CPU times + for every CPU available on the system. + """ + procfs_path = get_procfs_path() + set_scputimes_ntuple(procfs_path) + cpus = [] + with open_binary(f"{procfs_path}/stat") as f: + # get rid of the first line which refers to system wide CPU stats + f.readline() + for line in f: + if line.startswith(b'cpu'): + values = line.split() + fields = values[1 : len(scputimes._fields) + 1] + fields = [float(x) / CLOCK_TICKS for x in fields] + entry = scputimes(*fields) + cpus.append(entry) + return cpus + + +def cpu_count_logical(): + """Return the number of logical CPUs in the system.""" + try: + return os.sysconf("SC_NPROCESSORS_ONLN") + except ValueError: + # as a second fallback we try to parse /proc/cpuinfo + num = 0 + with open_binary(f"{get_procfs_path()}/cpuinfo") as f: + for line in f: + if line.lower().startswith(b'processor'): + num += 1 + + # unknown format (e.g. amrel/sparc architectures), see: + # https://github.com/giampaolo/psutil/issues/200 + # try to parse /proc/stat as a last resort + if num == 0: + search = re.compile(r'cpu\d') + with open_text(f"{get_procfs_path()}/stat") as f: + for line in f: + line = line.split(' ')[0] + if search.match(line): + num += 1 + + if num == 0: + # mimic os.cpu_count() + return None + return num + + +def cpu_count_cores(): + """Return the number of CPU cores in the system.""" + # Method #1 + ls = set() + # These 2 files are the same but */core_cpus_list is newer while + # */thread_siblings_list is deprecated and may disappear in the future. + # https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst + # https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964 + # https://lkml.org/lkml/2019/2/26/41 + p1 = "/sys/devices/system/cpu/cpu[0-9]*/topology/core_cpus_list" + p2 = "/sys/devices/system/cpu/cpu[0-9]*/topology/thread_siblings_list" + for path in glob.glob(p1) or glob.glob(p2): + with open_binary(path) as f: + ls.add(f.read().strip()) + result = len(ls) + if result != 0: + return result + + # Method #2 + mapping = {} + current_info = {} + with open_binary(f"{get_procfs_path()}/cpuinfo") as f: + for line in f: + line = line.strip().lower() + if not line: + # new section + try: + mapping[current_info[b'physical id']] = current_info[ + b'cpu cores' + ] + except KeyError: + pass + current_info = {} + elif line.startswith((b'physical id', b'cpu cores')): + # ongoing section + key, value = line.split(b'\t:', 1) + current_info[key] = int(value) + + result = sum(mapping.values()) + return result or None # mimic os.cpu_count() + + +def cpu_stats(): + """Return various CPU stats as a named tuple.""" + with open_binary(f"{get_procfs_path()}/stat") as f: + ctx_switches = None + interrupts = None + soft_interrupts = None + for line in f: + if line.startswith(b'ctxt'): + ctx_switches = int(line.split()[1]) + elif line.startswith(b'intr'): + interrupts = int(line.split()[1]) + elif line.startswith(b'softirq'): + soft_interrupts = int(line.split()[1]) + if ( + ctx_switches is not None + and soft_interrupts is not None + and interrupts is not None + ): + break + syscalls = 0 + return _common.scpustats( + ctx_switches, interrupts, soft_interrupts, syscalls + ) + + +def _cpu_get_cpuinfo_freq(): + """Return current CPU frequency from cpuinfo if available.""" + with open_binary(f"{get_procfs_path()}/cpuinfo") as f: + return [ + float(line.split(b':', 1)[1]) + for line in f + if line.lower().startswith(b'cpu mhz') + ] + + +if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or os.path.exists( + "/sys/devices/system/cpu/cpu0/cpufreq" +): + + def cpu_freq(): + """Return frequency metrics for all CPUs. + Contrarily to other OSes, Linux updates these values in + real-time. + """ + cpuinfo_freqs = _cpu_get_cpuinfo_freq() + paths = glob.glob( + "/sys/devices/system/cpu/cpufreq/policy[0-9]*" + ) or glob.glob("/sys/devices/system/cpu/cpu[0-9]*/cpufreq") + paths.sort(key=lambda x: int(re.search(r"[0-9]+", x).group())) + ret = [] + pjoin = os.path.join + for i, path in enumerate(paths): + if len(paths) == len(cpuinfo_freqs): + # take cached value from cpuinfo if available, see: + # https://github.com/giampaolo/psutil/issues/1851 + curr = cpuinfo_freqs[i] * 1000 + else: + curr = bcat(pjoin(path, "scaling_cur_freq"), fallback=None) + if curr is None: + # Likely an old RedHat, see: + # https://github.com/giampaolo/psutil/issues/1071 + curr = bcat(pjoin(path, "cpuinfo_cur_freq"), fallback=None) + if curr is None: + online_path = f"/sys/devices/system/cpu/cpu{i}/online" + # if cpu core is offline, set to all zeroes + if cat(online_path, fallback=None) == "0\n": + ret.append(_common.scpufreq(0.0, 0.0, 0.0)) + continue + msg = "can't find current frequency file" + raise NotImplementedError(msg) + curr = int(curr) / 1000 + max_ = int(bcat(pjoin(path, "scaling_max_freq"))) / 1000 + min_ = int(bcat(pjoin(path, "scaling_min_freq"))) / 1000 + ret.append(_common.scpufreq(curr, min_, max_)) + return ret + +else: + + def cpu_freq(): + """Alternate implementation using /proc/cpuinfo. + min and max frequencies are not available and are set to None. + """ + return [_common.scpufreq(x, 0.0, 0.0) for x in _cpu_get_cpuinfo_freq()] + + +# ===================================================================== +# --- network +# ===================================================================== + + +net_if_addrs = cext_posix.net_if_addrs + + +class _Ipv6UnsupportedError(Exception): + pass + + +class NetConnections: + """A wrapper on top of /proc/net/* files, retrieving per-process + and system-wide open connections (TCP, UDP, UNIX) similarly to + "netstat -an". + + Note: in case of UNIX sockets we're only able to determine the + local endpoint/path, not the one it's connected to. + According to [1] it would be possible but not easily. + + [1] http://serverfault.com/a/417946 + """ + + def __init__(self): + # The string represents the basename of the corresponding + # /proc/net/{proto_name} file. + tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM) + tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM) + udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM) + udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM) + unix = ("unix", socket.AF_UNIX, None) + self.tmap = { + "all": (tcp4, tcp6, udp4, udp6, unix), + "tcp": (tcp4, tcp6), + "tcp4": (tcp4,), + "tcp6": (tcp6,), + "udp": (udp4, udp6), + "udp4": (udp4,), + "udp6": (udp6,), + "unix": (unix,), + "inet": (tcp4, tcp6, udp4, udp6), + "inet4": (tcp4, udp4), + "inet6": (tcp6, udp6), + } + self._procfs_path = None + + def get_proc_inodes(self, pid): + inodes = defaultdict(list) + for fd in os.listdir(f"{self._procfs_path}/{pid}/fd"): + try: + inode = readlink(f"{self._procfs_path}/{pid}/fd/{fd}") + except (FileNotFoundError, ProcessLookupError): + # ENOENT == file which is gone in the meantime; + # os.stat(f"/proc/{self.pid}") will be done later + # to force NSP (if it's the case) + continue + except OSError as err: + if err.errno == errno.EINVAL: + # not a link + continue + if err.errno == errno.ENAMETOOLONG: + # file name too long + debug(err) + continue + raise + else: + if inode.startswith('socket:['): + # the process is using a socket + inode = inode[8:][:-1] + inodes[inode].append((pid, int(fd))) + return inodes + + def get_all_inodes(self): + inodes = {} + for pid in pids(): + try: + inodes.update(self.get_proc_inodes(pid)) + except (FileNotFoundError, ProcessLookupError, PermissionError): + # os.listdir() is gonna raise a lot of access denied + # exceptions in case of unprivileged user; that's fine + # as we'll just end up returning a connection with PID + # and fd set to None anyway. + # Both netstat -an and lsof does the same so it's + # unlikely we can do any better. + # ENOENT just means a PID disappeared on us. + continue + return inodes + + @staticmethod + def decode_address(addr, family): + """Accept an "ip:port" address as displayed in /proc/net/* + and convert it into a human readable form, like: + + "0500000A:0016" -> ("10.0.0.5", 22) + "0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521) + + The IP address portion is a little or big endian four-byte + hexadecimal number; that is, the least significant byte is listed + first, so we need to reverse the order of the bytes to convert it + to an IP address. + The port is represented as a two-byte hexadecimal number. + + Reference: + http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html + """ + ip, port = addr.split(':') + port = int(port, 16) + # this usually refers to a local socket in listen mode with + # no end-points connected + if not port: + return () + ip = ip.encode('ascii') + if family == socket.AF_INET: + # see: https://github.com/giampaolo/psutil/issues/201 + if LITTLE_ENDIAN: + ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1]) + else: + ip = socket.inet_ntop(family, base64.b16decode(ip)) + else: # IPv6 + ip = base64.b16decode(ip) + try: + # see: https://github.com/giampaolo/psutil/issues/201 + if LITTLE_ENDIAN: + ip = socket.inet_ntop( + socket.AF_INET6, + struct.pack('>4I', *struct.unpack('<4I', ip)), + ) + else: + ip = socket.inet_ntop( + socket.AF_INET6, + struct.pack('<4I', *struct.unpack('<4I', ip)), + ) + except ValueError: + # see: https://github.com/giampaolo/psutil/issues/623 + if not supports_ipv6(): + raise _Ipv6UnsupportedError from None + raise + return _common.addr(ip, port) + + @staticmethod + def process_inet(file, family, type_, inodes, filter_pid=None): + """Parse /proc/net/tcp* and /proc/net/udp* files.""" + if file.endswith('6') and not os.path.exists(file): + # IPv6 not supported + return + with open_text(file) as f: + f.readline() # skip the first line + for lineno, line in enumerate(f, 1): + try: + _, laddr, raddr, status, _, _, _, _, _, inode = ( + line.split()[:10] + ) + except ValueError: + msg = ( + f"error while parsing {file}; malformed line" + f" {lineno} {line!r}" + ) + raise RuntimeError(msg) from None + if inode in inodes: + # # We assume inet sockets are unique, so we error + # # out if there are multiple references to the + # # same inode. We won't do this for UNIX sockets. + # if len(inodes[inode]) > 1 and family != socket.AF_UNIX: + # raise ValueError("ambiguous inode with multiple " + # "PIDs references") + pid, fd = inodes[inode][0] + else: + pid, fd = None, -1 + if filter_pid is not None and filter_pid != pid: + continue + else: + if type_ == socket.SOCK_STREAM: + status = TCP_STATUSES[status] + else: + status = _common.CONN_NONE + try: + laddr = NetConnections.decode_address(laddr, family) + raddr = NetConnections.decode_address(raddr, family) + except _Ipv6UnsupportedError: + continue + yield (fd, family, type_, laddr, raddr, status, pid) + + @staticmethod + def process_unix(file, family, inodes, filter_pid=None): + """Parse /proc/net/unix files.""" + with open_text(file) as f: + f.readline() # skip the first line + for line in f: + tokens = line.split() + try: + _, _, _, _, type_, _, inode = tokens[0:7] + except ValueError: + if ' ' not in line: + # see: https://github.com/giampaolo/psutil/issues/766 + continue + msg = ( + f"error while parsing {file}; malformed line {line!r}" + ) + raise RuntimeError(msg) # noqa: B904 + if inode in inodes: # noqa: SIM108 + # With UNIX sockets we can have a single inode + # referencing many file descriptors. + pairs = inodes[inode] + else: + pairs = [(None, -1)] + for pid, fd in pairs: + if filter_pid is not None and filter_pid != pid: + continue + else: + path = tokens[-1] if len(tokens) == 8 else '' + type_ = _common.socktype_to_enum(int(type_)) + # XXX: determining the remote endpoint of a + # UNIX socket on Linux is not possible, see: + # https://serverfault.com/questions/252723/ + raddr = "" + status = _common.CONN_NONE + yield (fd, family, type_, path, raddr, status, pid) + + def retrieve(self, kind, pid=None): + self._procfs_path = get_procfs_path() + if pid is not None: + inodes = self.get_proc_inodes(pid) + if not inodes: + # no connections for this process + return [] + else: + inodes = self.get_all_inodes() + ret = set() + for proto_name, family, type_ in self.tmap[kind]: + path = f"{self._procfs_path}/net/{proto_name}" + if family in {socket.AF_INET, socket.AF_INET6}: + ls = self.process_inet( + path, family, type_, inodes, filter_pid=pid + ) + else: + ls = self.process_unix(path, family, inodes, filter_pid=pid) + for fd, family, type_, laddr, raddr, status, bound_pid in ls: + if pid: + conn = _common.pconn( + fd, family, type_, laddr, raddr, status + ) + else: + conn = _common.sconn( + fd, family, type_, laddr, raddr, status, bound_pid + ) + ret.add(conn) + return list(ret) + + +_net_connections = NetConnections() + + +def net_connections(kind='inet'): + """Return system-wide open connections.""" + return _net_connections.retrieve(kind) + + +def net_io_counters(): + """Return network I/O statistics for every network interface + installed on the system as a dict of raw tuples. + """ + with open_text(f"{get_procfs_path()}/net/dev") as f: + lines = f.readlines() + retdict = {} + for line in lines[2:]: + colon = line.rfind(':') + assert colon > 0, repr(line) + name = line[:colon].strip() + fields = line[colon + 1 :].strip().split() + + ( + # in + bytes_recv, + packets_recv, + errin, + dropin, + _fifoin, # unused + _framein, # unused + _compressedin, # unused + _multicastin, # unused + # out + bytes_sent, + packets_sent, + errout, + dropout, + _fifoout, # unused + _collisionsout, # unused + _carrierout, # unused + _compressedout, # unused + ) = map(int, fields) + + retdict[name] = ( + bytes_sent, + bytes_recv, + packets_sent, + packets_recv, + errin, + errout, + dropin, + dropout, + ) + return retdict + + +def net_if_stats(): + """Get NIC stats (isup, duplex, speed, mtu).""" + duplex_map = { + cext.DUPLEX_FULL: NIC_DUPLEX_FULL, + cext.DUPLEX_HALF: NIC_DUPLEX_HALF, + cext.DUPLEX_UNKNOWN: NIC_DUPLEX_UNKNOWN, + } + names = net_io_counters().keys() + ret = {} + for name in names: + try: + mtu = cext_posix.net_if_mtu(name) + flags = cext_posix.net_if_flags(name) + duplex, speed = cext.net_if_duplex_speed(name) + except OSError as err: + # https://github.com/giampaolo/psutil/issues/1279 + if err.errno != errno.ENODEV: + raise + debug(err) + else: + output_flags = ','.join(flags) + isup = 'running' in flags + ret[name] = _common.snicstats( + isup, duplex_map[duplex], speed, mtu, output_flags + ) + return ret + + +# ===================================================================== +# --- disks +# ===================================================================== + + +disk_usage = _psposix.disk_usage + + +def disk_io_counters(perdisk=False): + """Return disk I/O statistics for every disk installed on the + system as a dict of raw tuples. + """ + + def read_procfs(): + # OK, this is a bit confusing. The format of /proc/diskstats can + # have 3 variations. + # On Linux 2.4 each line has always 15 fields, e.g.: + # "3 0 8 hda 8 8 8 8 8 8 8 8 8 8 8" + # On Linux 2.6+ each line *usually* has 14 fields, and the disk + # name is in another position, like this: + # "3 0 hda 8 8 8 8 8 8 8 8 8 8 8" + # ...unless (Linux 2.6) the line refers to a partition instead + # of a disk, in which case the line has less fields (7): + # "3 1 hda1 8 8 8 8" + # 4.18+ has 4 fields added: + # "3 0 hda 8 8 8 8 8 8 8 8 8 8 8 0 0 0 0" + # 5.5 has 2 more fields. + # See: + # https://www.kernel.org/doc/Documentation/iostats.txt + # https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats + with open_text(f"{get_procfs_path()}/diskstats") as f: + lines = f.readlines() + for line in lines: + fields = line.split() + flen = len(fields) + # fmt: off + if flen == 15: + # Linux 2.4 + name = fields[3] + reads = int(fields[2]) + (reads_merged, rbytes, rtime, writes, writes_merged, + wbytes, wtime, _, busy_time, _) = map(int, fields[4:14]) + elif flen == 14 or flen >= 18: + # Linux 2.6+, line referring to a disk + name = fields[2] + (reads, reads_merged, rbytes, rtime, writes, writes_merged, + wbytes, wtime, _, busy_time, _) = map(int, fields[3:14]) + elif flen == 7: + # Linux 2.6+, line referring to a partition + name = fields[2] + reads, rbytes, writes, wbytes = map(int, fields[3:]) + rtime = wtime = reads_merged = writes_merged = busy_time = 0 + else: + msg = f"not sure how to interpret line {line!r}" + raise ValueError(msg) + yield (name, reads, writes, rbytes, wbytes, rtime, wtime, + reads_merged, writes_merged, busy_time) + # fmt: on + + def read_sysfs(): + for block in os.listdir('/sys/block'): + for root, _, files in os.walk(os.path.join('/sys/block', block)): + if 'stat' not in files: + continue + with open_text(os.path.join(root, 'stat')) as f: + fields = f.read().strip().split() + name = os.path.basename(root) + # fmt: off + (reads, reads_merged, rbytes, rtime, writes, writes_merged, + wbytes, wtime, _, busy_time) = map(int, fields[:10]) + yield (name, reads, writes, rbytes, wbytes, rtime, + wtime, reads_merged, writes_merged, busy_time) + # fmt: on + + if os.path.exists(f"{get_procfs_path()}/diskstats"): + gen = read_procfs() + elif os.path.exists('/sys/block'): + gen = read_sysfs() + else: + msg = ( + f"{get_procfs_path()}/diskstats nor /sys/block are available on" + " this system" + ) + raise NotImplementedError(msg) + + retdict = {} + for entry in gen: + # fmt: off + (name, reads, writes, rbytes, wbytes, rtime, wtime, reads_merged, + writes_merged, busy_time) = entry + if not perdisk and not is_storage_device(name): + # perdisk=False means we want to calculate totals so we skip + # partitions (e.g. 'sda1', 'nvme0n1p1') and only include + # base disk devices (e.g. 'sda', 'nvme0n1'). Base disks + # include a total of all their partitions + some extra size + # of their own: + # $ cat /proc/diskstats + # 259 0 sda 10485760 ... + # 259 1 sda1 5186039 ... + # 259 1 sda2 5082039 ... + # See: + # https://github.com/giampaolo/psutil/pull/1313 + continue + + rbytes *= DISK_SECTOR_SIZE + wbytes *= DISK_SECTOR_SIZE + retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime, + reads_merged, writes_merged, busy_time) + # fmt: on + + return retdict + + +class RootFsDeviceFinder: + """disk_partitions() may return partitions with device == "/dev/root" + or "rootfs". This container class uses different strategies to try to + obtain the real device path. Resources: + https://bootlin.com/blog/find-root-device/ + https://www.systutorials.com/how-to-find-the-disk-where-root-is-on-in-bash-on-linux/. + """ + + __slots__ = ['major', 'minor'] + + def __init__(self): + dev = os.stat("/").st_dev + self.major = os.major(dev) + self.minor = os.minor(dev) + + def ask_proc_partitions(self): + with open_text(f"{get_procfs_path()}/partitions") as f: + for line in f.readlines()[2:]: + fields = line.split() + if len(fields) < 4: # just for extra safety + continue + major = int(fields[0]) if fields[0].isdigit() else None + minor = int(fields[1]) if fields[1].isdigit() else None + name = fields[3] + if major == self.major and minor == self.minor: + if name: # just for extra safety + return f"/dev/{name}" + + def ask_sys_dev_block(self): + path = f"/sys/dev/block/{self.major}:{self.minor}/uevent" + with open_text(path) as f: + for line in f: + if line.startswith("DEVNAME="): + name = line.strip().rpartition("DEVNAME=")[2] + if name: # just for extra safety + return f"/dev/{name}" + + def ask_sys_class_block(self): + needle = f"{self.major}:{self.minor}" + files = glob.iglob("/sys/class/block/*/dev") + for file in files: + try: + f = open_text(file) + except FileNotFoundError: # race condition + continue + else: + with f: + data = f.read().strip() + if data == needle: + name = os.path.basename(os.path.dirname(file)) + return f"/dev/{name}" + + def find(self): + path = None + if path is None: + try: + path = self.ask_proc_partitions() + except OSError as err: + debug(err) + if path is None: + try: + path = self.ask_sys_dev_block() + except OSError as err: + debug(err) + if path is None: + try: + path = self.ask_sys_class_block() + except OSError as err: + debug(err) + # We use exists() because the "/dev/*" part of the path is hard + # coded, so we want to be sure. + if path is not None and os.path.exists(path): + return path + + +def disk_partitions(all=False): + """Return mounted disk partitions as a list of namedtuples.""" + fstypes = set() + procfs_path = get_procfs_path() + if not all: + with open_text(f"{procfs_path}/filesystems") as f: + for line in f: + line = line.strip() + if not line.startswith("nodev"): + fstypes.add(line.strip()) + else: + # ignore all lines starting with "nodev" except "nodev zfs" + fstype = line.split("\t")[1] + if fstype == "zfs": + fstypes.add("zfs") + + # See: https://github.com/giampaolo/psutil/issues/1307 + if procfs_path == "/proc" and os.path.isfile('/etc/mtab'): + mounts_path = os.path.realpath("/etc/mtab") + else: + mounts_path = os.path.realpath(f"{procfs_path}/self/mounts") + + retlist = [] + partitions = cext.disk_partitions(mounts_path) + for partition in partitions: + device, mountpoint, fstype, opts = partition + if device == 'none': + device = '' + if device in {"/dev/root", "rootfs"}: + device = RootFsDeviceFinder().find() or device + if not all: + if not device or fstype not in fstypes: + continue + ntuple = _common.sdiskpart(device, mountpoint, fstype, opts) + retlist.append(ntuple) + + return retlist + + +# ===================================================================== +# --- sensors +# ===================================================================== + + +def sensors_temperatures(): + """Return hardware (CPU and others) temperatures as a dict + including hardware name, label, current, max and critical + temperatures. + + Implementation notes: + - /sys/class/hwmon looks like the most recent interface to + retrieve this info, and this implementation relies on it + only (old distros will probably use something else) + - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon + - /sys/class/thermal/thermal_zone* is another one but it's more + difficult to parse + """ + ret = collections.defaultdict(list) + basenames = glob.glob('/sys/class/hwmon/hwmon*/temp*_*') + # CentOS has an intermediate /device directory: + # https://github.com/giampaolo/psutil/issues/971 + # https://github.com/nicolargo/glances/issues/1060 + basenames.extend(glob.glob('/sys/class/hwmon/hwmon*/device/temp*_*')) + basenames = sorted({x.split('_')[0] for x in basenames}) + + # Only add the coretemp hwmon entries if they're not already in + # /sys/class/hwmon/ + # https://github.com/giampaolo/psutil/issues/1708 + # https://github.com/giampaolo/psutil/pull/1648 + basenames2 = glob.glob( + '/sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_*' + ) + repl = re.compile(r"/sys/devices/platform/coretemp.*/hwmon/") + for name in basenames2: + altname = repl.sub('/sys/class/hwmon/', name) + if altname not in basenames: + basenames.append(name) + + for base in basenames: + try: + path = base + '_input' + current = float(bcat(path)) / 1000.0 + path = os.path.join(os.path.dirname(base), 'name') + unit_name = cat(path).strip() + except (OSError, ValueError): + # A lot of things can go wrong here, so let's just skip the + # whole entry. Sure thing is Linux's /sys/class/hwmon really + # is a stinky broken mess. + # https://github.com/giampaolo/psutil/issues/1009 + # https://github.com/giampaolo/psutil/issues/1101 + # https://github.com/giampaolo/psutil/issues/1129 + # https://github.com/giampaolo/psutil/issues/1245 + # https://github.com/giampaolo/psutil/issues/1323 + continue + + high = bcat(base + '_max', fallback=None) + critical = bcat(base + '_crit', fallback=None) + label = cat(base + '_label', fallback='').strip() + + if high is not None: + try: + high = float(high) / 1000.0 + except ValueError: + high = None + if critical is not None: + try: + critical = float(critical) / 1000.0 + except ValueError: + critical = None + + ret[unit_name].append((label, current, high, critical)) + + # Indication that no sensors were detected in /sys/class/hwmon/ + if not basenames: + basenames = glob.glob('/sys/class/thermal/thermal_zone*') + basenames = sorted(set(basenames)) + + for base in basenames: + try: + path = os.path.join(base, 'temp') + current = float(bcat(path)) / 1000.0 + path = os.path.join(base, 'type') + unit_name = cat(path).strip() + except (OSError, ValueError) as err: + debug(err) + continue + + trip_paths = glob.glob(base + '/trip_point*') + trip_points = { + '_'.join(os.path.basename(p).split('_')[0:3]) + for p in trip_paths + } + critical = None + high = None + for trip_point in trip_points: + path = os.path.join(base, trip_point + "_type") + trip_type = cat(path, fallback='').strip() + if trip_type == 'critical': + critical = bcat( + os.path.join(base, trip_point + "_temp"), fallback=None + ) + elif trip_type == 'high': + high = bcat( + os.path.join(base, trip_point + "_temp"), fallback=None + ) + + if high is not None: + try: + high = float(high) / 1000.0 + except ValueError: + high = None + if critical is not None: + try: + critical = float(critical) / 1000.0 + except ValueError: + critical = None + + ret[unit_name].append(('', current, high, critical)) + + return dict(ret) + + +def sensors_fans(): + """Return hardware fans info (for CPU and other peripherals) as a + dict including hardware label and current speed. + + Implementation notes: + - /sys/class/hwmon looks like the most recent interface to + retrieve this info, and this implementation relies on it + only (old distros will probably use something else) + - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon + """ + ret = collections.defaultdict(list) + basenames = glob.glob('/sys/class/hwmon/hwmon*/fan*_*') + if not basenames: + # CentOS has an intermediate /device directory: + # https://github.com/giampaolo/psutil/issues/971 + basenames = glob.glob('/sys/class/hwmon/hwmon*/device/fan*_*') + + basenames = sorted({x.split("_")[0] for x in basenames}) + for base in basenames: + try: + current = int(bcat(base + '_input')) + except OSError as err: + debug(err) + continue + unit_name = cat(os.path.join(os.path.dirname(base), 'name')).strip() + label = cat(base + '_label', fallback='').strip() + ret[unit_name].append(_common.sfan(label, current)) + + return dict(ret) + + +def sensors_battery(): + """Return battery information. + Implementation note: it appears /sys/class/power_supply/BAT0/ + directory structure may vary and provide files with the same + meaning but under different names, see: + https://github.com/giampaolo/psutil/issues/966. + """ + null = object() + + def multi_bcat(*paths): + """Attempt to read the content of multiple files which may + not exist. If none of them exist return None. + """ + for path in paths: + ret = bcat(path, fallback=null) + if ret != null: + try: + return int(ret) + except ValueError: + return ret.strip() + return None + + bats = [ + x + for x in os.listdir(POWER_SUPPLY_PATH) + if x.startswith('BAT') or 'battery' in x.lower() + ] + if not bats: + return None + # Get the first available battery. Usually this is "BAT0", except + # some rare exceptions: + # https://github.com/giampaolo/psutil/issues/1238 + root = os.path.join(POWER_SUPPLY_PATH, min(bats)) + + # Base metrics. + energy_now = multi_bcat(root + "/energy_now", root + "/charge_now") + power_now = multi_bcat(root + "/power_now", root + "/current_now") + energy_full = multi_bcat(root + "/energy_full", root + "/charge_full") + time_to_empty = multi_bcat(root + "/time_to_empty_now") + + # Percent. If we have energy_full the percentage will be more + # accurate compared to reading /capacity file (float vs. int). + if energy_full is not None and energy_now is not None: + try: + percent = 100.0 * energy_now / energy_full + except ZeroDivisionError: + percent = 0.0 + else: + percent = int(cat(root + "/capacity", fallback=-1)) + if percent == -1: + return None + + # Is AC power cable plugged in? + # Note: AC0 is not always available and sometimes (e.g. CentOS7) + # it's called "AC". + power_plugged = None + online = multi_bcat( + os.path.join(POWER_SUPPLY_PATH, "AC0/online"), + os.path.join(POWER_SUPPLY_PATH, "AC/online"), + ) + if online is not None: + power_plugged = online == 1 + else: + status = cat(root + "/status", fallback="").strip().lower() + if status == "discharging": + power_plugged = False + elif status in {"charging", "full"}: + power_plugged = True + + # Seconds left. + # Note to self: we may also calculate the charging ETA as per: + # https://github.com/thialfihar/dotfiles/blob/ + # 013937745fd9050c30146290e8f963d65c0179e6/bin/battery.py#L55 + if power_plugged: + secsleft = _common.POWER_TIME_UNLIMITED + elif energy_now is not None and power_now is not None: + try: + secsleft = int(energy_now / power_now * 3600) + except ZeroDivisionError: + secsleft = _common.POWER_TIME_UNKNOWN + elif time_to_empty is not None: + secsleft = int(time_to_empty * 60) + if secsleft < 0: + secsleft = _common.POWER_TIME_UNKNOWN + else: + secsleft = _common.POWER_TIME_UNKNOWN + + return _common.sbattery(percent, secsleft, power_plugged) + + +# ===================================================================== +# --- other system functions +# ===================================================================== + + +def users(): + """Return currently connected users as a list of namedtuples.""" + retlist = [] + rawlist = cext.users() + for item in rawlist: + user, tty, hostname, tstamp, pid = item + nt = _common.suser(user, tty or None, hostname, tstamp, pid) + retlist.append(nt) + return retlist + + +def boot_time(): + """Return the system boot time expressed in seconds since the epoch.""" + global BOOT_TIME + path = f"{get_procfs_path()}/stat" + with open_binary(path) as f: + for line in f: + if line.startswith(b'btime'): + ret = float(line.strip().split()[1]) + BOOT_TIME = ret + return ret + msg = f"line 'btime' not found in {path}" + raise RuntimeError(msg) + + +# ===================================================================== +# --- processes +# ===================================================================== + + +def pids(): + """Returns a list of PIDs currently running on the system.""" + path = get_procfs_path().encode(ENCODING) + return [int(x) for x in os.listdir(path) if x.isdigit()] + + +def pid_exists(pid): + """Check for the existence of a unix PID. Linux TIDs are not + supported (always return False). + """ + if not _psposix.pid_exists(pid): + return False + else: + # Linux's apparently does not distinguish between PIDs and TIDs + # (thread IDs). + # listdir("/proc") won't show any TID (only PIDs) but + # os.stat("/proc/{tid}") will succeed if {tid} exists. + # os.kill() can also be passed a TID. This is quite confusing. + # In here we want to enforce this distinction and support PIDs + # only, see: + # https://github.com/giampaolo/psutil/issues/687 + try: + # Note: already checked that this is faster than using a + # regular expr. Also (a lot) faster than doing + # 'return pid in pids()' + path = f"{get_procfs_path()}/{pid}/status" + with open_binary(path) as f: + for line in f: + if line.startswith(b"Tgid:"): + tgid = int(line.split()[1]) + # If tgid and pid are the same then we're + # dealing with a process PID. + return tgid == pid + msg = f"'Tgid' line not found in {path}" + raise ValueError(msg) + except (OSError, ValueError): + return pid in pids() + + +def ppid_map(): + """Obtain a {pid: ppid, ...} dict for all running processes in + one shot. Used to speed up Process.children(). + """ + ret = {} + procfs_path = get_procfs_path() + for pid in pids(): + try: + with open_binary(f"{procfs_path}/{pid}/stat") as f: + data = f.read() + except (FileNotFoundError, ProcessLookupError): + # Note: we should be able to access /stat for all processes + # aka it's unlikely we'll bump into EPERM, which is good. + pass + else: + rpar = data.rfind(b')') + dset = data[rpar + 2 :].split() + ppid = int(dset[1]) + ret[pid] = ppid + return ret + + +def wrap_exceptions(fun): + """Decorator which translates bare OSError and OSError exceptions + into NoSuchProcess and AccessDenied. + """ + + @functools.wraps(fun) + def wrapper(self, *args, **kwargs): + pid, name = self.pid, self._name + try: + return fun(self, *args, **kwargs) + except PermissionError as err: + raise AccessDenied(pid, name) from err + except ProcessLookupError as err: + self._raise_if_zombie() + raise NoSuchProcess(pid, name) from err + except FileNotFoundError as err: + self._raise_if_zombie() + # /proc/PID directory may still exist, but the files within + # it may not, indicating the process is gone, see: + # https://github.com/giampaolo/psutil/issues/2418 + if not os.path.exists(f"{self._procfs_path}/{pid}/stat"): + raise NoSuchProcess(pid, name) from err + raise + + return wrapper + + +class Process: + """Linux process implementation.""" + + __slots__ = ["_cache", "_name", "_ppid", "_procfs_path", "pid"] + + def __init__(self, pid): + self.pid = pid + self._name = None + self._ppid = None + self._procfs_path = get_procfs_path() + + def _is_zombie(self): + # Note: most of the times Linux is able to return info about the + # process even if it's a zombie, and /proc/{pid} will exist. + # There are some exceptions though, like exe(), cmdline() and + # memory_maps(). In these cases /proc/{pid}/{file} exists but + # it's empty. Instead of returning a "null" value we'll raise an + # exception. + try: + data = bcat(f"{self._procfs_path}/{self.pid}/stat") + except OSError: + return False + else: + rpar = data.rfind(b')') + status = data[rpar + 2 : rpar + 3] + return status == b"Z" + + def _raise_if_zombie(self): + if self._is_zombie(): + raise ZombieProcess(self.pid, self._name, self._ppid) + + def _raise_if_not_alive(self): + """Raise NSP if the process disappeared on us.""" + # For those C function who do not raise NSP, possibly returning + # incorrect or incomplete result. + os.stat(f"{self._procfs_path}/{self.pid}") + + @wrap_exceptions + @memoize_when_activated + def _parse_stat_file(self): + """Parse /proc/{pid}/stat file and return a dict with various + process info. + Using "man proc" as a reference: where "man proc" refers to + position N always subtract 3 (e.g ppid position 4 in + 'man proc' == position 1 in here). + The return value is cached in case oneshot() ctx manager is + in use. + """ + data = bcat(f"{self._procfs_path}/{self.pid}/stat") + # Process name is between parentheses. It can contain spaces and + # other parentheses. This is taken into account by looking for + # the first occurrence of "(" and the last occurrence of ")". + rpar = data.rfind(b')') + name = data[data.find(b'(') + 1 : rpar] + fields = data[rpar + 2 :].split() + + ret = {} + ret['name'] = name + ret['status'] = fields[0] + ret['ppid'] = fields[1] + ret['ttynr'] = fields[4] + ret['utime'] = fields[11] + ret['stime'] = fields[12] + ret['children_utime'] = fields[13] + ret['children_stime'] = fields[14] + ret['create_time'] = fields[19] + ret['cpu_num'] = fields[36] + try: + ret['blkio_ticks'] = fields[39] # aka 'delayacct_blkio_ticks' + except IndexError: + # https://github.com/giampaolo/psutil/issues/2455 + debug("can't get blkio_ticks, set iowait to 0") + ret['blkio_ticks'] = 0 + + return ret + + @wrap_exceptions + @memoize_when_activated + def _read_status_file(self): + """Read /proc/{pid}/stat file and return its content. + The return value is cached in case oneshot() ctx manager is + in use. + """ + with open_binary(f"{self._procfs_path}/{self.pid}/status") as f: + return f.read() + + @wrap_exceptions + @memoize_when_activated + def _read_smaps_file(self): + with open_binary(f"{self._procfs_path}/{self.pid}/smaps") as f: + return f.read().strip() + + def oneshot_enter(self): + self._parse_stat_file.cache_activate(self) + self._read_status_file.cache_activate(self) + self._read_smaps_file.cache_activate(self) + + def oneshot_exit(self): + self._parse_stat_file.cache_deactivate(self) + self._read_status_file.cache_deactivate(self) + self._read_smaps_file.cache_deactivate(self) + + @wrap_exceptions + def name(self): + # XXX - gets changed later and probably needs refactoring + return decode(self._parse_stat_file()['name']) + + @wrap_exceptions + def exe(self): + try: + return readlink(f"{self._procfs_path}/{self.pid}/exe") + except (FileNotFoundError, ProcessLookupError): + self._raise_if_zombie() + # no such file error; might be raised also if the + # path actually exists for system processes with + # low pids (about 0-20) + if os.path.lexists(f"{self._procfs_path}/{self.pid}"): + return "" + raise + + @wrap_exceptions + def cmdline(self): + with open_text(f"{self._procfs_path}/{self.pid}/cmdline") as f: + data = f.read() + if not data: + # may happen in case of zombie process + self._raise_if_zombie() + return [] + # 'man proc' states that args are separated by null bytes '\0' + # and last char is supposed to be a null byte. Nevertheless + # some processes may change their cmdline after being started + # (via setproctitle() or similar), they are usually not + # compliant with this rule and use spaces instead. Google + # Chrome process is an example. See: + # https://github.com/giampaolo/psutil/issues/1179 + sep = '\x00' if data.endswith('\x00') else ' ' + if data.endswith(sep): + data = data[:-1] + cmdline = data.split(sep) + # Sometimes last char is a null byte '\0' but the args are + # separated by spaces, see: https://github.com/giampaolo/psutil/ + # issues/1179#issuecomment-552984549 + if sep == '\x00' and len(cmdline) == 1 and ' ' in data: + cmdline = data.split(' ') + return cmdline + + @wrap_exceptions + def environ(self): + with open_text(f"{self._procfs_path}/{self.pid}/environ") as f: + data = f.read() + return parse_environ_block(data) + + @wrap_exceptions + def terminal(self): + tty_nr = int(self._parse_stat_file()['ttynr']) + tmap = _psposix.get_terminal_map() + try: + return tmap[tty_nr] + except KeyError: + return None + + # May not be available on old kernels. + if os.path.exists(f"/proc/{os.getpid()}/io"): + + @wrap_exceptions + def io_counters(self): + fname = f"{self._procfs_path}/{self.pid}/io" + fields = {} + with open_binary(fname) as f: + for line in f: + # https://github.com/giampaolo/psutil/issues/1004 + line = line.strip() + if line: + try: + name, value = line.split(b': ') + except ValueError: + # https://github.com/giampaolo/psutil/issues/1004 + continue + else: + fields[name] = int(value) + if not fields: + msg = f"{fname} file was empty" + raise RuntimeError(msg) + try: + return pio( + fields[b'syscr'], # read syscalls + fields[b'syscw'], # write syscalls + fields[b'read_bytes'], # read bytes + fields[b'write_bytes'], # write bytes + fields[b'rchar'], # read chars + fields[b'wchar'], # write chars + ) + except KeyError as err: + msg = ( + f"{err.args[0]!r} field was not found in {fname}; found" + f" fields are {fields!r}" + ) + raise ValueError(msg) from None + + @wrap_exceptions + def cpu_times(self): + values = self._parse_stat_file() + utime = float(values['utime']) / CLOCK_TICKS + stime = float(values['stime']) / CLOCK_TICKS + children_utime = float(values['children_utime']) / CLOCK_TICKS + children_stime = float(values['children_stime']) / CLOCK_TICKS + iowait = float(values['blkio_ticks']) / CLOCK_TICKS + return pcputimes(utime, stime, children_utime, children_stime, iowait) + + @wrap_exceptions + def cpu_num(self): + """What CPU the process is on.""" + return int(self._parse_stat_file()['cpu_num']) + + @wrap_exceptions + def wait(self, timeout=None): + return _psposix.wait_pid(self.pid, timeout, self._name) + + @wrap_exceptions + def create_time(self): + ctime = float(self._parse_stat_file()['create_time']) + # According to documentation, starttime is in field 21 and the + # unit is jiffies (clock ticks). + # We first divide it for clock ticks and then add uptime returning + # seconds since the epoch. + # Also use cached value if available. + bt = BOOT_TIME or boot_time() + return (ctime / CLOCK_TICKS) + bt + + @wrap_exceptions + def memory_info(self): + # ============================================================ + # | FIELD | DESCRIPTION | AKA | TOP | + # ============================================================ + # | rss | resident set size | | RES | + # | vms | total program size | size | VIRT | + # | shared | shared pages (from shared mappings) | | SHR | + # | text | text ('code') | trs | CODE | + # | lib | library (unused in Linux 2.6) | lrs | | + # | data | data + stack | drs | DATA | + # | dirty | dirty pages (unused in Linux 2.6) | dt | | + # ============================================================ + with open_binary(f"{self._procfs_path}/{self.pid}/statm") as f: + vms, rss, shared, text, lib, data, dirty = ( + int(x) * PAGESIZE for x in f.readline().split()[:7] + ) + return pmem(rss, vms, shared, text, lib, data, dirty) + + if HAS_PROC_SMAPS_ROLLUP or HAS_PROC_SMAPS: + + def _parse_smaps_rollup(self): + # /proc/pid/smaps_rollup was added to Linux in 2017. Faster + # than /proc/pid/smaps. It reports higher PSS than */smaps + # (from 1k up to 200k higher; tested against all processes). + # IMPORTANT: /proc/pid/smaps_rollup is weird, because it + # raises ESRCH / ENOENT for many PIDs, even if they're alive + # (also as root). In that case we'll use /proc/pid/smaps as + # fallback, which is slower but has a +50% success rate + # compared to /proc/pid/smaps_rollup. + uss = pss = swap = 0 + with open_binary( + f"{self._procfs_path}/{self.pid}/smaps_rollup" + ) as f: + for line in f: + if line.startswith(b"Private_"): + # Private_Clean, Private_Dirty, Private_Hugetlb + uss += int(line.split()[1]) * 1024 + elif line.startswith(b"Pss:"): + pss = int(line.split()[1]) * 1024 + elif line.startswith(b"Swap:"): + swap = int(line.split()[1]) * 1024 + return (uss, pss, swap) + + @wrap_exceptions + def _parse_smaps( + self, + # Gets Private_Clean, Private_Dirty, Private_Hugetlb. + _private_re=re.compile(br"\nPrivate.*:\s+(\d+)"), + _pss_re=re.compile(br"\nPss\:\s+(\d+)"), + _swap_re=re.compile(br"\nSwap\:\s+(\d+)"), + ): + # /proc/pid/smaps does not exist on kernels < 2.6.14 or if + # CONFIG_MMU kernel configuration option is not enabled. + + # Note: using 3 regexes is faster than reading the file + # line by line. + # + # You might be tempted to calculate USS by subtracting + # the "shared" value from the "resident" value in + # /proc//statm. But at least on Linux, statm's "shared" + # value actually counts pages backed by files, which has + # little to do with whether the pages are actually shared. + # /proc/self/smaps on the other hand appears to give us the + # correct information. + smaps_data = self._read_smaps_file() + # Note: smaps file can be empty for certain processes. + # The code below will not crash though and will result to 0. + uss = sum(map(int, _private_re.findall(smaps_data))) * 1024 + pss = sum(map(int, _pss_re.findall(smaps_data))) * 1024 + swap = sum(map(int, _swap_re.findall(smaps_data))) * 1024 + return (uss, pss, swap) + + @wrap_exceptions + def memory_full_info(self): + if HAS_PROC_SMAPS_ROLLUP: # faster + try: + uss, pss, swap = self._parse_smaps_rollup() + except (ProcessLookupError, FileNotFoundError): + uss, pss, swap = self._parse_smaps() + else: + uss, pss, swap = self._parse_smaps() + basic_mem = self.memory_info() + return pfullmem(*basic_mem + (uss, pss, swap)) + + else: + memory_full_info = memory_info + + if HAS_PROC_SMAPS: + + @wrap_exceptions + def memory_maps(self): + """Return process's mapped memory regions as a list of named + tuples. Fields are explained in 'man proc'; here is an updated + (Apr 2012) version: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/filesystems/proc.txt?id=b76437579d1344b612cf1851ae610c636cec7db0. + + /proc/{PID}/smaps does not exist on kernels < 2.6.14 or if + CONFIG_MMU kernel configuration option is not enabled. + """ + + def get_blocks(lines, current_block): + data = {} + for line in lines: + fields = line.split(None, 5) + if not fields[0].endswith(b':'): + # new block section + yield (current_block.pop(), data) + current_block.append(line) + else: + try: + data[fields[0]] = int(fields[1]) * 1024 + except ValueError: + if fields[0].startswith(b'VmFlags:'): + # see issue #369 + continue + msg = f"don't know how to interpret line {line!r}" + raise ValueError(msg) from None + yield (current_block.pop(), data) + + data = self._read_smaps_file() + # Note: smaps file can be empty for certain processes or for + # zombies. + if not data: + self._raise_if_zombie() + return [] + lines = data.split(b'\n') + ls = [] + first_line = lines.pop(0) + current_block = [first_line] + for header, data in get_blocks(lines, current_block): + hfields = header.split(None, 5) + try: + addr, perms, _offset, _dev, _inode, path = hfields + except ValueError: + addr, perms, _offset, _dev, _inode, path = hfields + [''] + if not path: + path = '[anon]' + else: + path = decode(path) + path = path.strip() + if path.endswith(' (deleted)') and not path_exists_strict( + path + ): + path = path[:-10] + item = ( + decode(addr), + decode(perms), + path, + data.get(b'Rss:', 0), + data.get(b'Size:', 0), + data.get(b'Pss:', 0), + data.get(b'Shared_Clean:', 0), + data.get(b'Shared_Dirty:', 0), + data.get(b'Private_Clean:', 0), + data.get(b'Private_Dirty:', 0), + data.get(b'Referenced:', 0), + data.get(b'Anonymous:', 0), + data.get(b'Swap:', 0), + ) + ls.append(item) + return ls + + @wrap_exceptions + def cwd(self): + return readlink(f"{self._procfs_path}/{self.pid}/cwd") + + @wrap_exceptions + def num_ctx_switches( + self, _ctxsw_re=re.compile(br'ctxt_switches:\t(\d+)') + ): + data = self._read_status_file() + ctxsw = _ctxsw_re.findall(data) + if not ctxsw: + msg = ( + "'voluntary_ctxt_switches' and" + " 'nonvoluntary_ctxt_switches'lines were not found in" + f" {self._procfs_path}/{self.pid}/status; the kernel is" + " probably older than 2.6.23" + ) + raise NotImplementedError(msg) + return _common.pctxsw(int(ctxsw[0]), int(ctxsw[1])) + + @wrap_exceptions + def num_threads(self, _num_threads_re=re.compile(br'Threads:\t(\d+)')): + # Using a re is faster than iterating over file line by line. + data = self._read_status_file() + return int(_num_threads_re.findall(data)[0]) + + @wrap_exceptions + def threads(self): + thread_ids = os.listdir(f"{self._procfs_path}/{self.pid}/task") + thread_ids.sort() + retlist = [] + hit_enoent = False + for thread_id in thread_ids: + fname = f"{self._procfs_path}/{self.pid}/task/{thread_id}/stat" + try: + with open_binary(fname) as f: + st = f.read().strip() + except (FileNotFoundError, ProcessLookupError): + # no such file or directory or no such process; + # it means thread disappeared on us + hit_enoent = True + continue + # ignore the first two values ("pid (exe)") + st = st[st.find(b')') + 2 :] + values = st.split(b' ') + utime = float(values[11]) / CLOCK_TICKS + stime = float(values[12]) / CLOCK_TICKS + ntuple = _common.pthread(int(thread_id), utime, stime) + retlist.append(ntuple) + if hit_enoent: + self._raise_if_not_alive() + return retlist + + @wrap_exceptions + def nice_get(self): + # with open_text(f"{self._procfs_path}/{self.pid}/stat") as f: + # data = f.read() + # return int(data.split()[18]) + + # Use C implementation + return cext_posix.getpriority(self.pid) + + @wrap_exceptions + def nice_set(self, value): + return cext_posix.setpriority(self.pid, value) + + # starting from CentOS 6. + if HAS_CPU_AFFINITY: + + @wrap_exceptions + def cpu_affinity_get(self): + return cext.proc_cpu_affinity_get(self.pid) + + def _get_eligible_cpus( + self, _re=re.compile(br"Cpus_allowed_list:\t(\d+)-(\d+)") + ): + # See: https://github.com/giampaolo/psutil/issues/956 + data = self._read_status_file() + match = _re.findall(data) + if match: + return list(range(int(match[0][0]), int(match[0][1]) + 1)) + else: + return list(range(len(per_cpu_times()))) + + @wrap_exceptions + def cpu_affinity_set(self, cpus): + try: + cext.proc_cpu_affinity_set(self.pid, cpus) + except (OSError, ValueError) as err: + if isinstance(err, ValueError) or err.errno == errno.EINVAL: + eligible_cpus = self._get_eligible_cpus() + all_cpus = tuple(range(len(per_cpu_times()))) + for cpu in cpus: + if cpu not in all_cpus: + msg = ( + f"invalid CPU {cpu!r}; choose between" + f" {eligible_cpus!r}" + ) + raise ValueError(msg) from None + if cpu not in eligible_cpus: + msg = ( + f"CPU number {cpu} is not eligible; choose" + f" between {eligible_cpus}" + ) + raise ValueError(msg) from err + raise + + # only starting from kernel 2.6.13 + if HAS_PROC_IO_PRIORITY: + + @wrap_exceptions + def ionice_get(self): + ioclass, value = cext.proc_ioprio_get(self.pid) + ioclass = IOPriority(ioclass) + return _common.pionice(ioclass, value) + + @wrap_exceptions + def ionice_set(self, ioclass, value): + if value is None: + value = 0 + if value and ioclass in { + IOPriority.IOPRIO_CLASS_IDLE, + IOPriority.IOPRIO_CLASS_NONE, + }: + msg = f"{ioclass!r} ioclass accepts no value" + raise ValueError(msg) + if value < 0 or value > 7: + msg = "value not in 0-7 range" + raise ValueError(msg) + return cext.proc_ioprio_set(self.pid, ioclass, value) + + if hasattr(resource, "prlimit"): + + @wrap_exceptions + def rlimit(self, resource_, limits=None): + # If pid is 0 prlimit() applies to the calling process and + # we don't want that. We should never get here though as + # PID 0 is not supported on Linux. + if self.pid == 0: + msg = "can't use prlimit() against PID 0 process" + raise ValueError(msg) + try: + if limits is None: + # get + return resource.prlimit(self.pid, resource_) + else: + # set + if len(limits) != 2: + msg = ( + "second argument must be a (soft, hard) " + f"tuple, got {limits!r}" + ) + raise ValueError(msg) + resource.prlimit(self.pid, resource_, limits) + except OSError as err: + if err.errno == errno.ENOSYS: + # I saw this happening on Travis: + # https://travis-ci.org/giampaolo/psutil/jobs/51368273 + self._raise_if_zombie() + raise + + @wrap_exceptions + def status(self): + letter = self._parse_stat_file()['status'] + letter = letter.decode() + # XXX is '?' legit? (we're not supposed to return it anyway) + return PROC_STATUSES.get(letter, '?') + + @wrap_exceptions + def open_files(self): + retlist = [] + files = os.listdir(f"{self._procfs_path}/{self.pid}/fd") + hit_enoent = False + for fd in files: + file = f"{self._procfs_path}/{self.pid}/fd/{fd}" + try: + path = readlink(file) + except (FileNotFoundError, ProcessLookupError): + # ENOENT == file which is gone in the meantime + hit_enoent = True + continue + except OSError as err: + if err.errno == errno.EINVAL: + # not a link + continue + if err.errno == errno.ENAMETOOLONG: + # file name too long + debug(err) + continue + raise + else: + # If path is not an absolute there's no way to tell + # whether it's a regular file or not, so we skip it. + # A regular file is always supposed to be have an + # absolute path though. + if path.startswith('/') and isfile_strict(path): + # Get file position and flags. + file = f"{self._procfs_path}/{self.pid}/fdinfo/{fd}" + try: + with open_binary(file) as f: + pos = int(f.readline().split()[1]) + flags = int(f.readline().split()[1], 8) + except (FileNotFoundError, ProcessLookupError): + # fd gone in the meantime; process may + # still be alive + hit_enoent = True + else: + mode = file_flags_to_mode(flags) + ntuple = popenfile( + path, int(fd), int(pos), mode, flags + ) + retlist.append(ntuple) + if hit_enoent: + self._raise_if_not_alive() + return retlist + + @wrap_exceptions + def net_connections(self, kind='inet'): + ret = _net_connections.retrieve(kind, self.pid) + self._raise_if_not_alive() + return ret + + @wrap_exceptions + def num_fds(self): + return len(os.listdir(f"{self._procfs_path}/{self.pid}/fd")) + + @wrap_exceptions + def ppid(self): + return int(self._parse_stat_file()['ppid']) + + @wrap_exceptions + def uids(self, _uids_re=re.compile(br'Uid:\t(\d+)\t(\d+)\t(\d+)')): + data = self._read_status_file() + real, effective, saved = _uids_re.findall(data)[0] + return _common.puids(int(real), int(effective), int(saved)) + + @wrap_exceptions + def gids(self, _gids_re=re.compile(br'Gid:\t(\d+)\t(\d+)\t(\d+)')): + data = self._read_status_file() + real, effective, saved = _gids_re.findall(data)[0] + return _common.pgids(int(real), int(effective), int(saved)) diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psosx.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psosx.py new file mode 100644 index 0000000000000000000000000000000000000000..620497b30a07bd104c34cc1a3fcb46243b8c9b67 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psosx.py @@ -0,0 +1,544 @@ +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""macOS platform implementation.""" + +import errno +import functools +import os +from collections import namedtuple + +from . import _common +from . import _psposix +from . import _psutil_osx as cext +from . import _psutil_posix as cext_posix +from ._common import AccessDenied +from ._common import NoSuchProcess +from ._common import ZombieProcess +from ._common import conn_tmap +from ._common import conn_to_ntuple +from ._common import isfile_strict +from ._common import memoize_when_activated +from ._common import parse_environ_block +from ._common import usage_percent + + +__extra__all__ = [] + + +# ===================================================================== +# --- globals +# ===================================================================== + + +PAGESIZE = cext_posix.getpagesize() +AF_LINK = cext_posix.AF_LINK + +TCP_STATUSES = { + cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED, + cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT, + cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV, + cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1, + cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2, + cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT, + cext.TCPS_CLOSED: _common.CONN_CLOSE, + cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, + cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK, + cext.TCPS_LISTEN: _common.CONN_LISTEN, + cext.TCPS_CLOSING: _common.CONN_CLOSING, + cext.PSUTIL_CONN_NONE: _common.CONN_NONE, +} + +PROC_STATUSES = { + cext.SIDL: _common.STATUS_IDLE, + cext.SRUN: _common.STATUS_RUNNING, + cext.SSLEEP: _common.STATUS_SLEEPING, + cext.SSTOP: _common.STATUS_STOPPED, + cext.SZOMB: _common.STATUS_ZOMBIE, +} + +kinfo_proc_map = dict( + ppid=0, + ruid=1, + euid=2, + suid=3, + rgid=4, + egid=5, + sgid=6, + ttynr=7, + ctime=8, + status=9, + name=10, +) + +pidtaskinfo_map = dict( + cpuutime=0, + cpustime=1, + rss=2, + vms=3, + pfaults=4, + pageins=5, + numthreads=6, + volctxsw=7, +) + + +# ===================================================================== +# --- named tuples +# ===================================================================== + + +# fmt: off +# psutil.cpu_times() +scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle']) +# psutil.virtual_memory() +svmem = namedtuple( + 'svmem', ['total', 'available', 'percent', 'used', 'free', + 'active', 'inactive', 'wired']) +# psutil.Process.memory_info() +pmem = namedtuple('pmem', ['rss', 'vms', 'pfaults', 'pageins']) +# psutil.Process.memory_full_info() +pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', )) +# fmt: on + + +# ===================================================================== +# --- memory +# ===================================================================== + + +def virtual_memory(): + """System virtual memory as a namedtuple.""" + total, active, inactive, wired, free, speculative = cext.virtual_mem() + # This is how Zabbix calculate avail and used mem: + # https://github.com/zabbix/zabbix/blob/master/src/libs/zbxsysinfo/osx/memory.c + # Also see: https://github.com/giampaolo/psutil/issues/1277 + avail = inactive + free + used = active + wired + # This is NOT how Zabbix calculates free mem but it matches "free" + # cmdline utility. + free -= speculative + percent = usage_percent((total - avail), total, round_=1) + return svmem(total, avail, percent, used, free, active, inactive, wired) + + +def swap_memory(): + """Swap system memory as a (total, used, free, sin, sout) tuple.""" + total, used, free, sin, sout = cext.swap_mem() + percent = usage_percent(used, total, round_=1) + return _common.sswap(total, used, free, percent, sin, sout) + + +# ===================================================================== +# --- CPU +# ===================================================================== + + +def cpu_times(): + """Return system CPU times as a namedtuple.""" + user, nice, system, idle = cext.cpu_times() + return scputimes(user, nice, system, idle) + + +def per_cpu_times(): + """Return system CPU times as a named tuple.""" + ret = [] + for cpu_t in cext.per_cpu_times(): + user, nice, system, idle = cpu_t + item = scputimes(user, nice, system, idle) + ret.append(item) + return ret + + +def cpu_count_logical(): + """Return the number of logical CPUs in the system.""" + return cext.cpu_count_logical() + + +def cpu_count_cores(): + """Return the number of CPU cores in the system.""" + return cext.cpu_count_cores() + + +def cpu_stats(): + ctx_switches, interrupts, soft_interrupts, syscalls, _traps = ( + cext.cpu_stats() + ) + return _common.scpustats( + ctx_switches, interrupts, soft_interrupts, syscalls + ) + + +def cpu_freq(): + """Return CPU frequency. + On macOS per-cpu frequency is not supported. + Also, the returned frequency never changes, see: + https://arstechnica.com/civis/viewtopic.php?f=19&t=465002. + """ + curr, min_, max_ = cext.cpu_freq() + return [_common.scpufreq(curr, min_, max_)] + + +# ===================================================================== +# --- disks +# ===================================================================== + + +disk_usage = _psposix.disk_usage +disk_io_counters = cext.disk_io_counters + + +def disk_partitions(all=False): + """Return mounted disk partitions as a list of namedtuples.""" + retlist = [] + partitions = cext.disk_partitions() + for partition in partitions: + device, mountpoint, fstype, opts = partition + if device == 'none': + device = '' + if not all: + if not os.path.isabs(device) or not os.path.exists(device): + continue + ntuple = _common.sdiskpart(device, mountpoint, fstype, opts) + retlist.append(ntuple) + return retlist + + +# ===================================================================== +# --- sensors +# ===================================================================== + + +def sensors_battery(): + """Return battery information.""" + try: + percent, minsleft, power_plugged = cext.sensors_battery() + except NotImplementedError: + # no power source - return None according to interface + return None + power_plugged = power_plugged == 1 + if power_plugged: + secsleft = _common.POWER_TIME_UNLIMITED + elif minsleft == -1: + secsleft = _common.POWER_TIME_UNKNOWN + else: + secsleft = minsleft * 60 + return _common.sbattery(percent, secsleft, power_plugged) + + +# ===================================================================== +# --- network +# ===================================================================== + + +net_io_counters = cext.net_io_counters +net_if_addrs = cext_posix.net_if_addrs + + +def net_connections(kind='inet'): + """System-wide network connections.""" + # Note: on macOS this will fail with AccessDenied unless + # the process is owned by root. + ret = [] + for pid in pids(): + try: + cons = Process(pid).net_connections(kind) + except NoSuchProcess: + continue + else: + if cons: + for c in cons: + c = list(c) + [pid] + ret.append(_common.sconn(*c)) + return ret + + +def net_if_stats(): + """Get NIC stats (isup, duplex, speed, mtu).""" + names = net_io_counters().keys() + ret = {} + for name in names: + try: + mtu = cext_posix.net_if_mtu(name) + flags = cext_posix.net_if_flags(name) + duplex, speed = cext_posix.net_if_duplex_speed(name) + except OSError as err: + # https://github.com/giampaolo/psutil/issues/1279 + if err.errno != errno.ENODEV: + raise + else: + if hasattr(_common, 'NicDuplex'): + duplex = _common.NicDuplex(duplex) + output_flags = ','.join(flags) + isup = 'running' in flags + ret[name] = _common.snicstats( + isup, duplex, speed, mtu, output_flags + ) + return ret + + +# ===================================================================== +# --- other system functions +# ===================================================================== + + +def boot_time(): + """The system boot time expressed in seconds since the epoch.""" + return cext.boot_time() + + +def users(): + """Return currently connected users as a list of namedtuples.""" + retlist = [] + rawlist = cext.users() + for item in rawlist: + user, tty, hostname, tstamp, pid = item + if tty == '~': + continue # reboot or shutdown + if not tstamp: + continue + nt = _common.suser(user, tty or None, hostname or None, tstamp, pid) + retlist.append(nt) + return retlist + + +# ===================================================================== +# --- processes +# ===================================================================== + + +def pids(): + ls = cext.pids() + if 0 not in ls: + # On certain macOS versions pids() C doesn't return PID 0 but + # "ps" does and the process is querable via sysctl(): + # https://travis-ci.org/giampaolo/psutil/jobs/309619941 + try: + Process(0).create_time() + ls.insert(0, 0) + except NoSuchProcess: + pass + except AccessDenied: + ls.insert(0, 0) + return ls + + +pid_exists = _psposix.pid_exists + + +def is_zombie(pid): + try: + st = cext.proc_kinfo_oneshot(pid)[kinfo_proc_map['status']] + return st == cext.SZOMB + except OSError: + return False + + +def wrap_exceptions(fun): + """Decorator which translates bare OSError exceptions into + NoSuchProcess and AccessDenied. + """ + + @functools.wraps(fun) + def wrapper(self, *args, **kwargs): + pid, ppid, name = self.pid, self._ppid, self._name + try: + return fun(self, *args, **kwargs) + except ProcessLookupError as err: + if is_zombie(pid): + raise ZombieProcess(pid, name, ppid) from err + raise NoSuchProcess(pid, name) from err + except PermissionError as err: + raise AccessDenied(pid, name) from err + + return wrapper + + +class Process: + """Wrapper class around underlying C implementation.""" + + __slots__ = ["_cache", "_name", "_ppid", "pid"] + + def __init__(self, pid): + self.pid = pid + self._name = None + self._ppid = None + + @wrap_exceptions + @memoize_when_activated + def _get_kinfo_proc(self): + # Note: should work with all PIDs without permission issues. + ret = cext.proc_kinfo_oneshot(self.pid) + assert len(ret) == len(kinfo_proc_map) + return ret + + @wrap_exceptions + @memoize_when_activated + def _get_pidtaskinfo(self): + # Note: should work for PIDs owned by user only. + ret = cext.proc_pidtaskinfo_oneshot(self.pid) + assert len(ret) == len(pidtaskinfo_map) + return ret + + def oneshot_enter(self): + self._get_kinfo_proc.cache_activate(self) + self._get_pidtaskinfo.cache_activate(self) + + def oneshot_exit(self): + self._get_kinfo_proc.cache_deactivate(self) + self._get_pidtaskinfo.cache_deactivate(self) + + @wrap_exceptions + def name(self): + name = self._get_kinfo_proc()[kinfo_proc_map['name']] + return name if name is not None else cext.proc_name(self.pid) + + @wrap_exceptions + def exe(self): + return cext.proc_exe(self.pid) + + @wrap_exceptions + def cmdline(self): + return cext.proc_cmdline(self.pid) + + @wrap_exceptions + def environ(self): + return parse_environ_block(cext.proc_environ(self.pid)) + + @wrap_exceptions + def ppid(self): + self._ppid = self._get_kinfo_proc()[kinfo_proc_map['ppid']] + return self._ppid + + @wrap_exceptions + def cwd(self): + return cext.proc_cwd(self.pid) + + @wrap_exceptions + def uids(self): + rawtuple = self._get_kinfo_proc() + return _common.puids( + rawtuple[kinfo_proc_map['ruid']], + rawtuple[kinfo_proc_map['euid']], + rawtuple[kinfo_proc_map['suid']], + ) + + @wrap_exceptions + def gids(self): + rawtuple = self._get_kinfo_proc() + return _common.puids( + rawtuple[kinfo_proc_map['rgid']], + rawtuple[kinfo_proc_map['egid']], + rawtuple[kinfo_proc_map['sgid']], + ) + + @wrap_exceptions + def terminal(self): + tty_nr = self._get_kinfo_proc()[kinfo_proc_map['ttynr']] + tmap = _psposix.get_terminal_map() + try: + return tmap[tty_nr] + except KeyError: + return None + + @wrap_exceptions + def memory_info(self): + rawtuple = self._get_pidtaskinfo() + return pmem( + rawtuple[pidtaskinfo_map['rss']], + rawtuple[pidtaskinfo_map['vms']], + rawtuple[pidtaskinfo_map['pfaults']], + rawtuple[pidtaskinfo_map['pageins']], + ) + + @wrap_exceptions + def memory_full_info(self): + basic_mem = self.memory_info() + uss = cext.proc_memory_uss(self.pid) + return pfullmem(*basic_mem + (uss,)) + + @wrap_exceptions + def cpu_times(self): + rawtuple = self._get_pidtaskinfo() + return _common.pcputimes( + rawtuple[pidtaskinfo_map['cpuutime']], + rawtuple[pidtaskinfo_map['cpustime']], + # children user / system times are not retrievable (set to 0) + 0.0, + 0.0, + ) + + @wrap_exceptions + def create_time(self): + return self._get_kinfo_proc()[kinfo_proc_map['ctime']] + + @wrap_exceptions + def num_ctx_switches(self): + # Unvoluntary value seems not to be available; + # getrusage() numbers seems to confirm this theory. + # We set it to 0. + vol = self._get_pidtaskinfo()[pidtaskinfo_map['volctxsw']] + return _common.pctxsw(vol, 0) + + @wrap_exceptions + def num_threads(self): + return self._get_pidtaskinfo()[pidtaskinfo_map['numthreads']] + + @wrap_exceptions + def open_files(self): + if self.pid == 0: + return [] + files = [] + rawlist = cext.proc_open_files(self.pid) + for path, fd in rawlist: + if isfile_strict(path): + ntuple = _common.popenfile(path, fd) + files.append(ntuple) + return files + + @wrap_exceptions + def net_connections(self, kind='inet'): + families, types = conn_tmap[kind] + rawlist = cext.proc_net_connections(self.pid, families, types) + ret = [] + for item in rawlist: + fd, fam, type, laddr, raddr, status = item + nt = conn_to_ntuple( + fd, fam, type, laddr, raddr, status, TCP_STATUSES + ) + ret.append(nt) + return ret + + @wrap_exceptions + def num_fds(self): + if self.pid == 0: + return 0 + return cext.proc_num_fds(self.pid) + + @wrap_exceptions + def wait(self, timeout=None): + return _psposix.wait_pid(self.pid, timeout, self._name) + + @wrap_exceptions + def nice_get(self): + return cext_posix.getpriority(self.pid) + + @wrap_exceptions + def nice_set(self, value): + return cext_posix.setpriority(self.pid, value) + + @wrap_exceptions + def status(self): + code = self._get_kinfo_proc()[kinfo_proc_map['status']] + # XXX is '?' legit? (we're not supposed to return it anyway) + return PROC_STATUSES.get(code, '?') + + @wrap_exceptions + def threads(self): + rawlist = cext.proc_threads(self.pid) + retlist = [] + for thread_id, utime, stime in rawlist: + ntuple = _common.pthread(thread_id, utime, stime) + retlist.append(ntuple) + return retlist diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psposix.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psposix.py new file mode 100644 index 0000000000000000000000000000000000000000..88703fdbd26a2b7a117b0d86367ed5dc2d7951aa --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psposix.py @@ -0,0 +1,207 @@ +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Routines common to all posix systems.""" + +import enum +import glob +import os +import signal +import time + +from ._common import MACOS +from ._common import TimeoutExpired +from ._common import memoize +from ._common import sdiskusage +from ._common import usage_percent + + +if MACOS: + from . import _psutil_osx + + +__all__ = ['pid_exists', 'wait_pid', 'disk_usage', 'get_terminal_map'] + + +def pid_exists(pid): + """Check whether pid exists in the current process table.""" + if pid == 0: + # According to "man 2 kill" PID 0 has a special meaning: + # it refers to <> so we don't want to go any further. + # If we get here it means this UNIX platform *does* have + # a process with id 0. + return True + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + # EPERM clearly means there's a process to deny access to + return True + # According to "man 2 kill" possible error values are + # (EINVAL, EPERM, ESRCH) + else: + return True + + +Negsignal = enum.IntEnum( + 'Negsignal', {x.name: -x.value for x in signal.Signals} +) + + +def negsig_to_enum(num): + """Convert a negative signal value to an enum.""" + try: + return Negsignal(num) + except ValueError: + return num + + +def wait_pid( + pid, + timeout=None, + proc_name=None, + _waitpid=os.waitpid, + _timer=getattr(time, 'monotonic', time.time), # noqa: B008 + _min=min, + _sleep=time.sleep, + _pid_exists=pid_exists, +): + """Wait for a process PID to terminate. + + If the process terminated normally by calling exit(3) or _exit(2), + or by returning from main(), the return value is the positive integer + passed to *exit(). + + If it was terminated by a signal it returns the negated value of the + signal which caused the termination (e.g. -SIGTERM). + + If PID is not a children of os.getpid() (current process) just + wait until the process disappears and return None. + + If PID does not exist at all return None immediately. + + If *timeout* != None and process is still alive raise TimeoutExpired. + timeout=0 is also possible (either return immediately or raise). + """ + if pid <= 0: + # see "man waitpid" + msg = "can't wait for PID 0" + raise ValueError(msg) + interval = 0.0001 + flags = 0 + if timeout is not None: + flags |= os.WNOHANG + stop_at = _timer() + timeout + + def sleep(interval): + # Sleep for some time and return a new increased interval. + if timeout is not None: + if _timer() >= stop_at: + raise TimeoutExpired(timeout, pid=pid, name=proc_name) + _sleep(interval) + return _min(interval * 2, 0.04) + + # See: https://linux.die.net/man/2/waitpid + while True: + try: + retpid, status = os.waitpid(pid, flags) + except InterruptedError: + interval = sleep(interval) + except ChildProcessError: + # This has two meanings: + # - PID is not a child of os.getpid() in which case + # we keep polling until it's gone + # - PID never existed in the first place + # In both cases we'll eventually return None as we + # can't determine its exit status code. + while _pid_exists(pid): + interval = sleep(interval) + return None + else: + if retpid == 0: + # WNOHANG flag was used and PID is still running. + interval = sleep(interval) + continue + + if os.WIFEXITED(status): + # Process terminated normally by calling exit(3) or _exit(2), + # or by returning from main(). The return value is the + # positive integer passed to *exit(). + return os.WEXITSTATUS(status) + elif os.WIFSIGNALED(status): + # Process exited due to a signal. Return the negative value + # of that signal. + return negsig_to_enum(-os.WTERMSIG(status)) + # elif os.WIFSTOPPED(status): + # # Process was stopped via SIGSTOP or is being traced, and + # # waitpid() was called with WUNTRACED flag. PID is still + # # alive. From now on waitpid() will keep returning (0, 0) + # # until the process state doesn't change. + # # It may make sense to catch/enable this since stopped PIDs + # # ignore SIGTERM. + # interval = sleep(interval) + # continue + # elif os.WIFCONTINUED(status): + # # Process was resumed via SIGCONT and waitpid() was called + # # with WCONTINUED flag. + # interval = sleep(interval) + # continue + else: + # Should never happen. + msg = f"unknown process exit status {status!r}" + raise ValueError(msg) + + +def disk_usage(path): + """Return disk usage associated with path. + Note: UNIX usually reserves 5% disk space which is not accessible + by user. In this function "total" and "used" values reflect the + total and used disk space whereas "free" and "percent" represent + the "free" and "used percent" user disk space. + """ + st = os.statvfs(path) + # Total space which is only available to root (unless changed + # at system level). + total = st.f_blocks * st.f_frsize + # Remaining free space usable by root. + avail_to_root = st.f_bfree * st.f_frsize + # Remaining free space usable by user. + avail_to_user = st.f_bavail * st.f_frsize + # Total space being used in general. + used = total - avail_to_root + if MACOS: + # see: https://github.com/giampaolo/psutil/pull/2152 + used = _psutil_osx.disk_usage_used(path, used) + # Total space which is available to user (same as 'total' but + # for the user). + total_user = used + avail_to_user + # User usage percent compared to the total amount of space + # the user can use. This number would be higher if compared + # to root's because the user has less space (usually -5%). + usage_percent_user = usage_percent(used, total_user, round_=1) + + # NB: the percentage is -5% than what shown by df due to + # reserved blocks that we are currently not considering: + # https://github.com/giampaolo/psutil/issues/829#issuecomment-223750462 + return sdiskusage( + total=total, used=used, free=avail_to_user, percent=usage_percent_user + ) + + +@memoize +def get_terminal_map(): + """Get a map of device-id -> path as a dict. + Used by Process.terminal(). + """ + ret = {} + ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*') + for name in ls: + assert name not in ret, name + try: + ret[os.stat(name).st_rdev] = name + except FileNotFoundError: + pass + return ret diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_pssunos.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_pssunos.py new file mode 100644 index 0000000000000000000000000000000000000000..78d941cc5ffdc5c08d858f9bd6cfaa4176b8e246 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_pssunos.py @@ -0,0 +1,734 @@ +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Sun OS Solaris platform implementation.""" + +import errno +import functools +import os +import socket +import subprocess +import sys +from collections import namedtuple +from socket import AF_INET + +from . import _common +from . import _psposix +from . import _psutil_posix as cext_posix +from . import _psutil_sunos as cext +from ._common import AF_INET6 +from ._common import ENCODING +from ._common import AccessDenied +from ._common import NoSuchProcess +from ._common import ZombieProcess +from ._common import debug +from ._common import get_procfs_path +from ._common import isfile_strict +from ._common import memoize_when_activated +from ._common import sockfam_to_enum +from ._common import socktype_to_enum +from ._common import usage_percent + + +__extra__all__ = ["CONN_IDLE", "CONN_BOUND", "PROCFS_PATH"] + + +# ===================================================================== +# --- globals +# ===================================================================== + + +PAGE_SIZE = cext_posix.getpagesize() +AF_LINK = cext_posix.AF_LINK +IS_64_BIT = sys.maxsize > 2**32 + +CONN_IDLE = "IDLE" +CONN_BOUND = "BOUND" + +PROC_STATUSES = { + cext.SSLEEP: _common.STATUS_SLEEPING, + cext.SRUN: _common.STATUS_RUNNING, + cext.SZOMB: _common.STATUS_ZOMBIE, + cext.SSTOP: _common.STATUS_STOPPED, + cext.SIDL: _common.STATUS_IDLE, + cext.SONPROC: _common.STATUS_RUNNING, # same as run + cext.SWAIT: _common.STATUS_WAITING, +} + +TCP_STATUSES = { + cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED, + cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT, + cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV, + cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1, + cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2, + cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT, + cext.TCPS_CLOSED: _common.CONN_CLOSE, + cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, + cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK, + cext.TCPS_LISTEN: _common.CONN_LISTEN, + cext.TCPS_CLOSING: _common.CONN_CLOSING, + cext.PSUTIL_CONN_NONE: _common.CONN_NONE, + cext.TCPS_IDLE: CONN_IDLE, # sunos specific + cext.TCPS_BOUND: CONN_BOUND, # sunos specific +} + +proc_info_map = dict( + ppid=0, + rss=1, + vms=2, + create_time=3, + nice=4, + num_threads=5, + status=6, + ttynr=7, + uid=8, + euid=9, + gid=10, + egid=11, +) + + +# ===================================================================== +# --- named tuples +# ===================================================================== + + +# psutil.cpu_times() +scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait']) +# psutil.cpu_times(percpu=True) +pcputimes = namedtuple( + 'pcputimes', ['user', 'system', 'children_user', 'children_system'] +) +# psutil.virtual_memory() +svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free']) +# psutil.Process.memory_info() +pmem = namedtuple('pmem', ['rss', 'vms']) +pfullmem = pmem +# psutil.Process.memory_maps(grouped=True) +pmmap_grouped = namedtuple( + 'pmmap_grouped', ['path', 'rss', 'anonymous', 'locked'] +) +# psutil.Process.memory_maps(grouped=False) +pmmap_ext = namedtuple( + 'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields) +) + + +# ===================================================================== +# --- memory +# ===================================================================== + + +def virtual_memory(): + """Report virtual memory metrics.""" + # we could have done this with kstat, but IMHO this is good enough + total = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE + # note: there's no difference on Solaris + free = avail = os.sysconf('SC_AVPHYS_PAGES') * PAGE_SIZE + used = total - free + percent = usage_percent(used, total, round_=1) + return svmem(total, avail, percent, used, free) + + +def swap_memory(): + """Report swap memory metrics.""" + sin, sout = cext.swap_mem() + # XXX + # we are supposed to get total/free by doing so: + # http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/ + # usr/src/cmd/swap/swap.c + # ...nevertheless I can't manage to obtain the same numbers as 'swap' + # cmdline utility, so let's parse its output (sigh!) + p = subprocess.Popen( + [ + '/usr/bin/env', + f"PATH=/usr/sbin:/sbin:{os.environ['PATH']}", + 'swap', + '-l', + ], + stdout=subprocess.PIPE, + ) + stdout, _ = p.communicate() + stdout = stdout.decode(sys.stdout.encoding) + if p.returncode != 0: + msg = f"'swap -l' failed (retcode={p.returncode})" + raise RuntimeError(msg) + + lines = stdout.strip().split('\n')[1:] + if not lines: + msg = 'no swap device(s) configured' + raise RuntimeError(msg) + total = free = 0 + for line in lines: + line = line.split() + t, f = line[3:5] + total += int(int(t) * 512) + free += int(int(f) * 512) + used = total - free + percent = usage_percent(used, total, round_=1) + return _common.sswap( + total, used, free, percent, sin * PAGE_SIZE, sout * PAGE_SIZE + ) + + +# ===================================================================== +# --- CPU +# ===================================================================== + + +def cpu_times(): + """Return system-wide CPU times as a named tuple.""" + ret = cext.per_cpu_times() + return scputimes(*[sum(x) for x in zip(*ret)]) + + +def per_cpu_times(): + """Return system per-CPU times as a list of named tuples.""" + ret = cext.per_cpu_times() + return [scputimes(*x) for x in ret] + + +def cpu_count_logical(): + """Return the number of logical CPUs in the system.""" + try: + return os.sysconf("SC_NPROCESSORS_ONLN") + except ValueError: + # mimic os.cpu_count() behavior + return None + + +def cpu_count_cores(): + """Return the number of CPU cores in the system.""" + return cext.cpu_count_cores() + + +def cpu_stats(): + """Return various CPU stats as a named tuple.""" + ctx_switches, interrupts, syscalls, _traps = cext.cpu_stats() + soft_interrupts = 0 + return _common.scpustats( + ctx_switches, interrupts, soft_interrupts, syscalls + ) + + +# ===================================================================== +# --- disks +# ===================================================================== + + +disk_io_counters = cext.disk_io_counters +disk_usage = _psposix.disk_usage + + +def disk_partitions(all=False): + """Return system disk partitions.""" + # TODO - the filtering logic should be better checked so that + # it tries to reflect 'df' as much as possible + retlist = [] + partitions = cext.disk_partitions() + for partition in partitions: + device, mountpoint, fstype, opts = partition + if device == 'none': + device = '' + if not all: + # Differently from, say, Linux, we don't have a list of + # common fs types so the best we can do, AFAIK, is to + # filter by filesystem having a total size > 0. + try: + if not disk_usage(mountpoint).total: + continue + except OSError as err: + # https://github.com/giampaolo/psutil/issues/1674 + debug(f"skipping {mountpoint!r}: {err}") + continue + ntuple = _common.sdiskpart(device, mountpoint, fstype, opts) + retlist.append(ntuple) + return retlist + + +# ===================================================================== +# --- network +# ===================================================================== + + +net_io_counters = cext.net_io_counters +net_if_addrs = cext_posix.net_if_addrs + + +def net_connections(kind, _pid=-1): + """Return socket connections. If pid == -1 return system-wide + connections (as opposed to connections opened by one process only). + Only INET sockets are returned (UNIX are not). + """ + families, types = _common.conn_tmap[kind] + rawlist = cext.net_connections(_pid) + ret = set() + for item in rawlist: + fd, fam, type_, laddr, raddr, status, pid = item + if fam not in families: + continue + if type_ not in types: + continue + # TODO: refactor and use _common.conn_to_ntuple. + if fam in {AF_INET, AF_INET6}: + if laddr: + laddr = _common.addr(*laddr) + if raddr: + raddr = _common.addr(*raddr) + status = TCP_STATUSES[status] + fam = sockfam_to_enum(fam) + type_ = socktype_to_enum(type_) + if _pid == -1: + nt = _common.sconn(fd, fam, type_, laddr, raddr, status, pid) + else: + nt = _common.pconn(fd, fam, type_, laddr, raddr, status) + ret.add(nt) + return list(ret) + + +def net_if_stats(): + """Get NIC stats (isup, duplex, speed, mtu).""" + ret = cext.net_if_stats() + for name, items in ret.items(): + isup, duplex, speed, mtu = items + if hasattr(_common, 'NicDuplex'): + duplex = _common.NicDuplex(duplex) + ret[name] = _common.snicstats(isup, duplex, speed, mtu, '') + return ret + + +# ===================================================================== +# --- other system functions +# ===================================================================== + + +def boot_time(): + """The system boot time expressed in seconds since the epoch.""" + return cext.boot_time() + + +def users(): + """Return currently connected users as a list of namedtuples.""" + retlist = [] + rawlist = cext.users() + localhost = (':0.0', ':0') + for item in rawlist: + user, tty, hostname, tstamp, user_process, pid = item + # note: the underlying C function includes entries about + # system boot, run level and others. We might want + # to use them in the future. + if not user_process: + continue + if hostname in localhost: + hostname = 'localhost' + nt = _common.suser(user, tty, hostname, tstamp, pid) + retlist.append(nt) + return retlist + + +# ===================================================================== +# --- processes +# ===================================================================== + + +def pids(): + """Returns a list of PIDs currently running on the system.""" + path = get_procfs_path().encode(ENCODING) + return [int(x) for x in os.listdir(path) if x.isdigit()] + + +def pid_exists(pid): + """Check for the existence of a unix pid.""" + return _psposix.pid_exists(pid) + + +def wrap_exceptions(fun): + """Call callable into a try/except clause and translate ENOENT, + EACCES and EPERM in NoSuchProcess or AccessDenied exceptions. + """ + + @functools.wraps(fun) + def wrapper(self, *args, **kwargs): + pid, ppid, name = self.pid, self._ppid, self._name + try: + return fun(self, *args, **kwargs) + except (FileNotFoundError, ProcessLookupError) as err: + # ENOENT (no such file or directory) gets raised on open(). + # ESRCH (no such process) can get raised on read() if + # process is gone in meantime. + if not pid_exists(pid): + raise NoSuchProcess(pid, name) from err + raise ZombieProcess(pid, name, ppid) from err + except PermissionError as err: + raise AccessDenied(pid, name) from err + except OSError as err: + if pid == 0: + if 0 in pids(): + raise AccessDenied(pid, name) from err + raise + raise + + return wrapper + + +class Process: + """Wrapper class around underlying C implementation.""" + + __slots__ = ["_cache", "_name", "_ppid", "_procfs_path", "pid"] + + def __init__(self, pid): + self.pid = pid + self._name = None + self._ppid = None + self._procfs_path = get_procfs_path() + + def _assert_alive(self): + """Raise NSP if the process disappeared on us.""" + # For those C function who do not raise NSP, possibly returning + # incorrect or incomplete result. + os.stat(f"{self._procfs_path}/{self.pid}") + + def oneshot_enter(self): + self._proc_name_and_args.cache_activate(self) + self._proc_basic_info.cache_activate(self) + self._proc_cred.cache_activate(self) + + def oneshot_exit(self): + self._proc_name_and_args.cache_deactivate(self) + self._proc_basic_info.cache_deactivate(self) + self._proc_cred.cache_deactivate(self) + + @wrap_exceptions + @memoize_when_activated + def _proc_name_and_args(self): + return cext.proc_name_and_args(self.pid, self._procfs_path) + + @wrap_exceptions + @memoize_when_activated + def _proc_basic_info(self): + if self.pid == 0 and not os.path.exists( + f"{self._procfs_path}/{self.pid}/psinfo" + ): + raise AccessDenied(self.pid) + ret = cext.proc_basic_info(self.pid, self._procfs_path) + assert len(ret) == len(proc_info_map) + return ret + + @wrap_exceptions + @memoize_when_activated + def _proc_cred(self): + return cext.proc_cred(self.pid, self._procfs_path) + + @wrap_exceptions + def name(self): + # note: max len == 15 + return self._proc_name_and_args()[0] + + @wrap_exceptions + def exe(self): + try: + return os.readlink(f"{self._procfs_path}/{self.pid}/path/a.out") + except OSError: + pass # continue and guess the exe name from the cmdline + # Will be guessed later from cmdline but we want to explicitly + # invoke cmdline here in order to get an AccessDenied + # exception if the user has not enough privileges. + self.cmdline() + return "" + + @wrap_exceptions + def cmdline(self): + return self._proc_name_and_args()[1].split(' ') + + @wrap_exceptions + def environ(self): + return cext.proc_environ(self.pid, self._procfs_path) + + @wrap_exceptions + def create_time(self): + return self._proc_basic_info()[proc_info_map['create_time']] + + @wrap_exceptions + def num_threads(self): + return self._proc_basic_info()[proc_info_map['num_threads']] + + @wrap_exceptions + def nice_get(self): + # Note #1: getpriority(3) doesn't work for realtime processes. + # Psinfo is what ps uses, see: + # https://github.com/giampaolo/psutil/issues/1194 + return self._proc_basic_info()[proc_info_map['nice']] + + @wrap_exceptions + def nice_set(self, value): + if self.pid in {2, 3}: + # Special case PIDs: internally setpriority(3) return ESRCH + # (no such process), no matter what. + # The process actually exists though, as it has a name, + # creation time, etc. + raise AccessDenied(self.pid, self._name) + return cext_posix.setpriority(self.pid, value) + + @wrap_exceptions + def ppid(self): + self._ppid = self._proc_basic_info()[proc_info_map['ppid']] + return self._ppid + + @wrap_exceptions + def uids(self): + try: + real, effective, saved, _, _, _ = self._proc_cred() + except AccessDenied: + real = self._proc_basic_info()[proc_info_map['uid']] + effective = self._proc_basic_info()[proc_info_map['euid']] + saved = None + return _common.puids(real, effective, saved) + + @wrap_exceptions + def gids(self): + try: + _, _, _, real, effective, saved = self._proc_cred() + except AccessDenied: + real = self._proc_basic_info()[proc_info_map['gid']] + effective = self._proc_basic_info()[proc_info_map['egid']] + saved = None + return _common.puids(real, effective, saved) + + @wrap_exceptions + def cpu_times(self): + try: + times = cext.proc_cpu_times(self.pid, self._procfs_path) + except OSError as err: + if err.errno == errno.EOVERFLOW and not IS_64_BIT: + # We may get here if we attempt to query a 64bit process + # with a 32bit python. + # Error originates from read() and also tools like "cat" + # fail in the same way (!). + # Since there simply is no way to determine CPU times we + # return 0.0 as a fallback. See: + # https://github.com/giampaolo/psutil/issues/857 + times = (0.0, 0.0, 0.0, 0.0) + else: + raise + return _common.pcputimes(*times) + + @wrap_exceptions + def cpu_num(self): + return cext.proc_cpu_num(self.pid, self._procfs_path) + + @wrap_exceptions + def terminal(self): + procfs_path = self._procfs_path + hit_enoent = False + tty = wrap_exceptions(self._proc_basic_info()[proc_info_map['ttynr']]) + if tty != cext.PRNODEV: + for x in (0, 1, 2, 255): + try: + return os.readlink(f"{procfs_path}/{self.pid}/path/{x}") + except FileNotFoundError: + hit_enoent = True + continue + if hit_enoent: + self._assert_alive() + + @wrap_exceptions + def cwd(self): + # /proc/PID/path/cwd may not be resolved by readlink() even if + # it exists (ls shows it). If that's the case and the process + # is still alive return None (we can return None also on BSD). + # Reference: https://groups.google.com/g/comp.unix.solaris/c/tcqvhTNFCAs + procfs_path = self._procfs_path + try: + return os.readlink(f"{procfs_path}/{self.pid}/path/cwd") + except FileNotFoundError: + os.stat(f"{procfs_path}/{self.pid}") # raise NSP or AD + return "" + + @wrap_exceptions + def memory_info(self): + ret = self._proc_basic_info() + rss = ret[proc_info_map['rss']] * 1024 + vms = ret[proc_info_map['vms']] * 1024 + return pmem(rss, vms) + + memory_full_info = memory_info + + @wrap_exceptions + def status(self): + code = self._proc_basic_info()[proc_info_map['status']] + # XXX is '?' legit? (we're not supposed to return it anyway) + return PROC_STATUSES.get(code, '?') + + @wrap_exceptions + def threads(self): + procfs_path = self._procfs_path + ret = [] + tids = os.listdir(f"{procfs_path}/{self.pid}/lwp") + hit_enoent = False + for tid in tids: + tid = int(tid) + try: + utime, stime = cext.query_process_thread( + self.pid, tid, procfs_path + ) + except OSError as err: + if err.errno == errno.EOVERFLOW and not IS_64_BIT: + # We may get here if we attempt to query a 64bit process + # with a 32bit python. + # Error originates from read() and also tools like "cat" + # fail in the same way (!). + # Since there simply is no way to determine CPU times we + # return 0.0 as a fallback. See: + # https://github.com/giampaolo/psutil/issues/857 + continue + # ENOENT == thread gone in meantime + if err.errno == errno.ENOENT: + hit_enoent = True + continue + raise + else: + nt = _common.pthread(tid, utime, stime) + ret.append(nt) + if hit_enoent: + self._assert_alive() + return ret + + @wrap_exceptions + def open_files(self): + retlist = [] + hit_enoent = False + procfs_path = self._procfs_path + pathdir = f"{procfs_path}/{self.pid}/path" + for fd in os.listdir(f"{procfs_path}/{self.pid}/fd"): + path = os.path.join(pathdir, fd) + if os.path.islink(path): + try: + file = os.readlink(path) + except FileNotFoundError: + hit_enoent = True + continue + else: + if isfile_strict(file): + retlist.append(_common.popenfile(file, int(fd))) + if hit_enoent: + self._assert_alive() + return retlist + + def _get_unix_sockets(self, pid): + """Get UNIX sockets used by process by parsing 'pfiles' output.""" + # TODO: rewrite this in C (...but the damn netstat source code + # does not include this part! Argh!!) + cmd = ["pfiles", str(pid)] + p = subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) + stdout, stderr = p.communicate() + stdout, stderr = ( + x.decode(sys.stdout.encoding) for x in (stdout, stderr) + ) + if p.returncode != 0: + if 'permission denied' in stderr.lower(): + raise AccessDenied(self.pid, self._name) + if 'no such process' in stderr.lower(): + raise NoSuchProcess(self.pid, self._name) + msg = f"{cmd!r} command error\n{stderr}" + raise RuntimeError(msg) + + lines = stdout.split('\n')[2:] + for i, line in enumerate(lines): + line = line.lstrip() + if line.startswith('sockname: AF_UNIX'): + path = line.split(' ', 2)[2] + type = lines[i - 2].strip() + if type == 'SOCK_STREAM': + type = socket.SOCK_STREAM + elif type == 'SOCK_DGRAM': + type = socket.SOCK_DGRAM + else: + type = -1 + yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE) + + @wrap_exceptions + def net_connections(self, kind='inet'): + ret = net_connections(kind, _pid=self.pid) + # The underlying C implementation retrieves all OS connections + # and filters them by PID. At this point we can't tell whether + # an empty list means there were no connections for process or + # process is no longer active so we force NSP in case the PID + # is no longer there. + if not ret: + # will raise NSP if process is gone + os.stat(f"{self._procfs_path}/{self.pid}") + + # UNIX sockets + if kind in {'all', 'unix'}: + ret.extend([ + _common.pconn(*conn) + for conn in self._get_unix_sockets(self.pid) + ]) + return ret + + nt_mmap_grouped = namedtuple('mmap', 'path rss anon locked') + nt_mmap_ext = namedtuple('mmap', 'addr perms path rss anon locked') + + @wrap_exceptions + def memory_maps(self): + def toaddr(start, end): + return "{}-{}".format( + hex(start)[2:].strip('L'), hex(end)[2:].strip('L') + ) + + procfs_path = self._procfs_path + retlist = [] + try: + rawlist = cext.proc_memory_maps(self.pid, procfs_path) + except OSError as err: + if err.errno == errno.EOVERFLOW and not IS_64_BIT: + # We may get here if we attempt to query a 64bit process + # with a 32bit python. + # Error originates from read() and also tools like "cat" + # fail in the same way (!). + # Since there simply is no way to determine CPU times we + # return 0.0 as a fallback. See: + # https://github.com/giampaolo/psutil/issues/857 + return [] + else: + raise + hit_enoent = False + for item in rawlist: + addr, addrsize, perm, name, rss, anon, locked = item + addr = toaddr(addr, addrsize) + if not name.startswith('['): + try: + name = os.readlink(f"{procfs_path}/{self.pid}/path/{name}") + except OSError as err: + if err.errno == errno.ENOENT: + # sometimes the link may not be resolved by + # readlink() even if it exists (ls shows it). + # If that's the case we just return the + # unresolved link path. + # This seems an inconsistency with /proc similar + # to: http://goo.gl/55XgO + name = f"{procfs_path}/{self.pid}/path/{name}" + hit_enoent = True + else: + raise + retlist.append((addr, perm, name, rss, anon, locked)) + if hit_enoent: + self._assert_alive() + return retlist + + @wrap_exceptions + def num_fds(self): + return len(os.listdir(f"{self._procfs_path}/{self.pid}/fd")) + + @wrap_exceptions + def num_ctx_switches(self): + return _common.pctxsw( + *cext.proc_num_ctx_switches(self.pid, self._procfs_path) + ) + + @wrap_exceptions + def wait(self, timeout=None): + return _psposix.wait_pid(self.pid, timeout, self._name) diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psutil_posix.abi3.so b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psutil_posix.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..70bd2966a422d59e8750d4c1d12e833add3d065b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psutil_posix.abi3.so differ diff --git a/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_pswindows.py b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_pswindows.py new file mode 100644 index 0000000000000000000000000000000000000000..e5af3c90f4311077d0134575f6e7ff25d89baee5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_pswindows.py @@ -0,0 +1,1103 @@ +# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Windows platform implementation.""" + +import contextlib +import enum +import functools +import os +import signal +import sys +import time +from collections import namedtuple + +from . import _common +from ._common import ENCODING +from ._common import AccessDenied +from ._common import NoSuchProcess +from ._common import TimeoutExpired +from ._common import conn_tmap +from ._common import conn_to_ntuple +from ._common import debug +from ._common import isfile_strict +from ._common import memoize +from ._common import memoize_when_activated +from ._common import parse_environ_block +from ._common import usage_percent +from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS +from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS +from ._psutil_windows import HIGH_PRIORITY_CLASS +from ._psutil_windows import IDLE_PRIORITY_CLASS +from ._psutil_windows import NORMAL_PRIORITY_CLASS +from ._psutil_windows import REALTIME_PRIORITY_CLASS + + +try: + from . import _psutil_windows as cext +except ImportError as err: + if ( + str(err).lower().startswith("dll load failed") + and sys.getwindowsversion()[0] < 6 + ): + # We may get here if: + # 1) we are on an old Windows version + # 2) psutil was installed via pip + wheel + # See: https://github.com/giampaolo/psutil/issues/811 + msg = "this Windows version is too old (< Windows Vista); " + msg += "psutil 3.4.2 is the latest version which supports Windows " + msg += "2000, XP and 2003 server" + raise RuntimeError(msg) from err + else: + raise + + +# process priority constants, import from __init__.py: +# http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx +# fmt: off +__extra__all__ = [ + "win_service_iter", "win_service_get", + # Process priority + "ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS", + "HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS", "NORMAL_PRIORITY_CLASS", + "REALTIME_PRIORITY_CLASS", + # IO priority + "IOPRIO_VERYLOW", "IOPRIO_LOW", "IOPRIO_NORMAL", "IOPRIO_HIGH", + # others + "CONN_DELETE_TCB", "AF_LINK", +] +# fmt: on + + +# ===================================================================== +# --- globals +# ===================================================================== + +CONN_DELETE_TCB = "DELETE_TCB" +ERROR_PARTIAL_COPY = 299 +PYPY = '__pypy__' in sys.builtin_module_names + +AddressFamily = enum.IntEnum('AddressFamily', {'AF_LINK': -1}) +AF_LINK = AddressFamily.AF_LINK + +TCP_STATUSES = { + cext.MIB_TCP_STATE_ESTAB: _common.CONN_ESTABLISHED, + cext.MIB_TCP_STATE_SYN_SENT: _common.CONN_SYN_SENT, + cext.MIB_TCP_STATE_SYN_RCVD: _common.CONN_SYN_RECV, + cext.MIB_TCP_STATE_FIN_WAIT1: _common.CONN_FIN_WAIT1, + cext.MIB_TCP_STATE_FIN_WAIT2: _common.CONN_FIN_WAIT2, + cext.MIB_TCP_STATE_TIME_WAIT: _common.CONN_TIME_WAIT, + cext.MIB_TCP_STATE_CLOSED: _common.CONN_CLOSE, + cext.MIB_TCP_STATE_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, + cext.MIB_TCP_STATE_LAST_ACK: _common.CONN_LAST_ACK, + cext.MIB_TCP_STATE_LISTEN: _common.CONN_LISTEN, + cext.MIB_TCP_STATE_CLOSING: _common.CONN_CLOSING, + cext.MIB_TCP_STATE_DELETE_TCB: CONN_DELETE_TCB, + cext.PSUTIL_CONN_NONE: _common.CONN_NONE, +} + + +class Priority(enum.IntEnum): + ABOVE_NORMAL_PRIORITY_CLASS = ABOVE_NORMAL_PRIORITY_CLASS + BELOW_NORMAL_PRIORITY_CLASS = BELOW_NORMAL_PRIORITY_CLASS + HIGH_PRIORITY_CLASS = HIGH_PRIORITY_CLASS + IDLE_PRIORITY_CLASS = IDLE_PRIORITY_CLASS + NORMAL_PRIORITY_CLASS = NORMAL_PRIORITY_CLASS + REALTIME_PRIORITY_CLASS = REALTIME_PRIORITY_CLASS + + +globals().update(Priority.__members__) + + +class IOPriority(enum.IntEnum): + IOPRIO_VERYLOW = 0 + IOPRIO_LOW = 1 + IOPRIO_NORMAL = 2 + IOPRIO_HIGH = 3 + + +globals().update(IOPriority.__members__) + +pinfo_map = dict( + num_handles=0, + ctx_switches=1, + user_time=2, + kernel_time=3, + create_time=4, + num_threads=5, + io_rcount=6, + io_wcount=7, + io_rbytes=8, + io_wbytes=9, + io_count_others=10, + io_bytes_others=11, + num_page_faults=12, + peak_wset=13, + wset=14, + peak_paged_pool=15, + paged_pool=16, + peak_non_paged_pool=17, + non_paged_pool=18, + pagefile=19, + peak_pagefile=20, + mem_private=21, +) + + +# ===================================================================== +# --- named tuples +# ===================================================================== + + +# fmt: off +# psutil.cpu_times() +scputimes = namedtuple('scputimes', + ['user', 'system', 'idle', 'interrupt', 'dpc']) +# psutil.virtual_memory() +svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free']) +# psutil.Process.memory_info() +pmem = namedtuple( + 'pmem', ['rss', 'vms', + 'num_page_faults', 'peak_wset', 'wset', 'peak_paged_pool', + 'paged_pool', 'peak_nonpaged_pool', 'nonpaged_pool', + 'pagefile', 'peak_pagefile', 'private']) +# psutil.Process.memory_full_info() +pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', )) +# psutil.Process.memory_maps(grouped=True) +pmmap_grouped = namedtuple('pmmap_grouped', ['path', 'rss']) +# psutil.Process.memory_maps(grouped=False) +pmmap_ext = namedtuple( + 'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields)) +# psutil.Process.io_counters() +pio = namedtuple('pio', ['read_count', 'write_count', + 'read_bytes', 'write_bytes', + 'other_count', 'other_bytes']) +# fmt: on + + +# ===================================================================== +# --- utils +# ===================================================================== + + +@functools.lru_cache(maxsize=512) +def convert_dos_path(s): + r"""Convert paths using native DOS format like: + "\Device\HarddiskVolume1\Windows\systemew\file.txt" + into: + "C:\Windows\systemew\file.txt". + """ + rawdrive = '\\'.join(s.split('\\')[:3]) + driveletter = cext.QueryDosDevice(rawdrive) + remainder = s[len(rawdrive) :] + return os.path.join(driveletter, remainder) + + +@memoize +def getpagesize(): + return cext.getpagesize() + + +# ===================================================================== +# --- memory +# ===================================================================== + + +def virtual_memory(): + """System virtual memory as a namedtuple.""" + mem = cext.virtual_mem() + totphys, availphys, _totsys, _availsys = mem + total = totphys + avail = availphys + free = availphys + used = total - avail + percent = usage_percent((total - avail), total, round_=1) + return svmem(total, avail, percent, used, free) + + +def swap_memory(): + """Swap system memory as a (total, used, free, sin, sout) tuple.""" + mem = cext.virtual_mem() + + total_phys = mem[0] + total_system = mem[2] + + # system memory (commit total/limit) is the sum of physical and swap + # thus physical memory values need to be subtracted to get swap values + total = total_system - total_phys + # commit total is incremented immediately (decrementing free_system) + # while the corresponding free physical value is not decremented until + # pages are accessed, so we can't use free system memory for swap. + # instead, we calculate page file usage based on performance counter + if total > 0: + percentswap = cext.swap_percent() + used = int(0.01 * percentswap * total) + else: + percentswap = 0.0 + used = 0 + + free = total - used + percent = round(percentswap, 1) + return _common.sswap(total, used, free, percent, 0, 0) + + +# ===================================================================== +# --- disk +# ===================================================================== + + +disk_io_counters = cext.disk_io_counters + + +def disk_usage(path): + """Return disk usage associated with path.""" + if isinstance(path, bytes): + # XXX: do we want to use "strict"? Probably yes, in order + # to fail immediately. After all we are accepting input here... + path = path.decode(ENCODING, errors="strict") + total, free = cext.disk_usage(path) + used = total - free + percent = usage_percent(used, total, round_=1) + return _common.sdiskusage(total, used, free, percent) + + +def disk_partitions(all): + """Return disk partitions.""" + rawlist = cext.disk_partitions(all) + return [_common.sdiskpart(*x) for x in rawlist] + + +# ===================================================================== +# --- CPU +# ===================================================================== + + +def cpu_times(): + """Return system CPU times as a named tuple.""" + user, system, idle = cext.cpu_times() + # Internally, GetSystemTimes() is used, and it doesn't return + # interrupt and dpc times. cext.per_cpu_times() does, so we + # rely on it to get those only. + percpu_summed = scputimes(*[sum(n) for n in zip(*cext.per_cpu_times())]) + return scputimes( + user, system, idle, percpu_summed.interrupt, percpu_summed.dpc + ) + + +def per_cpu_times(): + """Return system per-CPU times as a list of named tuples.""" + ret = [] + for user, system, idle, interrupt, dpc in cext.per_cpu_times(): + item = scputimes(user, system, idle, interrupt, dpc) + ret.append(item) + return ret + + +def cpu_count_logical(): + """Return the number of logical CPUs in the system.""" + return cext.cpu_count_logical() + + +def cpu_count_cores(): + """Return the number of CPU cores in the system.""" + return cext.cpu_count_cores() + + +def cpu_stats(): + """Return CPU statistics.""" + ctx_switches, interrupts, _dpcs, syscalls = cext.cpu_stats() + soft_interrupts = 0 + return _common.scpustats( + ctx_switches, interrupts, soft_interrupts, syscalls + ) + + +def cpu_freq(): + """Return CPU frequency. + On Windows per-cpu frequency is not supported. + """ + curr, max_ = cext.cpu_freq() + min_ = 0.0 + return [_common.scpufreq(float(curr), min_, float(max_))] + + +_loadavg_inititialized = False + + +def getloadavg(): + """Return the number of processes in the system run queue averaged + over the last 1, 5, and 15 minutes respectively as a tuple. + """ + global _loadavg_inititialized + + if not _loadavg_inititialized: + cext.init_loadavg_counter() + _loadavg_inititialized = True + + # Drop to 2 decimal points which is what Linux does + raw_loads = cext.getloadavg() + return tuple(round(load, 2) for load in raw_loads) + + +# ===================================================================== +# --- network +# ===================================================================== + + +def net_connections(kind, _pid=-1): + """Return socket connections. If pid == -1 return system-wide + connections (as opposed to connections opened by one process only). + """ + families, types = conn_tmap[kind] + rawlist = cext.net_connections(_pid, families, types) + ret = set() + for item in rawlist: + fd, fam, type, laddr, raddr, status, pid = item + nt = conn_to_ntuple( + fd, + fam, + type, + laddr, + raddr, + status, + TCP_STATUSES, + pid=pid if _pid == -1 else None, + ) + ret.add(nt) + return list(ret) + + +def net_if_stats(): + """Get NIC stats (isup, duplex, speed, mtu).""" + ret = {} + rawdict = cext.net_if_stats() + for name, items in rawdict.items(): + isup, duplex, speed, mtu = items + if hasattr(_common, 'NicDuplex'): + duplex = _common.NicDuplex(duplex) + ret[name] = _common.snicstats(isup, duplex, speed, mtu, '') + return ret + + +def net_io_counters(): + """Return network I/O statistics for every network interface + installed on the system as a dict of raw tuples. + """ + return cext.net_io_counters() + + +def net_if_addrs(): + """Return the addresses associated to each NIC.""" + return cext.net_if_addrs() + + +# ===================================================================== +# --- sensors +# ===================================================================== + + +def sensors_battery(): + """Return battery information.""" + # For constants meaning see: + # https://msdn.microsoft.com/en-us/library/windows/desktop/ + # aa373232(v=vs.85).aspx + acline_status, flags, percent, secsleft = cext.sensors_battery() + power_plugged = acline_status == 1 + no_battery = bool(flags & 128) + charging = bool(flags & 8) + + if no_battery: + return None + if power_plugged or charging: + secsleft = _common.POWER_TIME_UNLIMITED + elif secsleft == -1: + secsleft = _common.POWER_TIME_UNKNOWN + + return _common.sbattery(percent, secsleft, power_plugged) + + +# ===================================================================== +# --- other system functions +# ===================================================================== + + +_last_btime = 0 + + +def boot_time(): + """The system boot time expressed in seconds since the epoch.""" + # This dirty hack is to adjust the precision of the returned + # value which may have a 1 second fluctuation, see: + # https://github.com/giampaolo/psutil/issues/1007 + global _last_btime + ret = float(cext.boot_time()) + if abs(ret - _last_btime) <= 1: + return _last_btime + else: + _last_btime = ret + return ret + + +def users(): + """Return currently connected users as a list of namedtuples.""" + retlist = [] + rawlist = cext.users() + for item in rawlist: + user, hostname, tstamp = item + nt = _common.suser(user, None, hostname, tstamp, None) + retlist.append(nt) + return retlist + + +# ===================================================================== +# --- Windows services +# ===================================================================== + + +def win_service_iter(): + """Yields a list of WindowsService instances.""" + for name, display_name in cext.winservice_enumerate(): + yield WindowsService(name, display_name) + + +def win_service_get(name): + """Open a Windows service and return it as a WindowsService instance.""" + service = WindowsService(name, None) + service._display_name = service._query_config()['display_name'] + return service + + +class WindowsService: # noqa: PLW1641 + """Represents an installed Windows service.""" + + def __init__(self, name, display_name): + self._name = name + self._display_name = display_name + + def __str__(self): + details = f"(name={self._name!r}, display_name={self._display_name!r})" + return f"{self.__class__.__name__}{details}" + + def __repr__(self): + return f"<{self.__str__()} at {id(self)}>" + + def __eq__(self, other): + # Test for equality with another WindosService object based + # on name. + if not isinstance(other, WindowsService): + return NotImplemented + return self._name == other._name + + def __ne__(self, other): + return not self == other + + def _query_config(self): + with self._wrap_exceptions(): + display_name, binpath, username, start_type = ( + cext.winservice_query_config(self._name) + ) + # XXX - update _self.display_name? + return dict( + display_name=display_name, + binpath=binpath, + username=username, + start_type=start_type, + ) + + def _query_status(self): + with self._wrap_exceptions(): + status, pid = cext.winservice_query_status(self._name) + if pid == 0: + pid = None + return dict(status=status, pid=pid) + + @contextlib.contextmanager + def _wrap_exceptions(self): + """Ctx manager which translates bare OSError and WindowsError + exceptions into NoSuchProcess and AccessDenied. + """ + try: + yield + except OSError as err: + name = self._name + if is_permission_err(err): + msg = ( + f"service {name!r} is not querable (not enough privileges)" + ) + raise AccessDenied(pid=None, name=name, msg=msg) from err + elif err.winerror in { + cext.ERROR_INVALID_NAME, + cext.ERROR_SERVICE_DOES_NOT_EXIST, + }: + msg = f"service {name!r} does not exist" + raise NoSuchProcess(pid=None, name=name, msg=msg) from err + else: + raise + + # config query + + def name(self): + """The service name. This string is how a service is referenced + and can be passed to win_service_get() to get a new + WindowsService instance. + """ + return self._name + + def display_name(self): + """The service display name. The value is cached when this class + is instantiated. + """ + return self._display_name + + def binpath(self): + """The fully qualified path to the service binary/exe file as + a string, including command line arguments. + """ + return self._query_config()['binpath'] + + def username(self): + """The name of the user that owns this service.""" + return self._query_config()['username'] + + def start_type(self): + """A string which can either be "automatic", "manual" or + "disabled". + """ + return self._query_config()['start_type'] + + # status query + + def pid(self): + """The process PID, if any, else None. This can be passed + to Process class to control the service's process. + """ + return self._query_status()['pid'] + + def status(self): + """Service status as a string.""" + return self._query_status()['status'] + + def description(self): + """Service long description.""" + return cext.winservice_query_descr(self.name()) + + # utils + + def as_dict(self): + """Utility method retrieving all the information above as a + dictionary. + """ + d = self._query_config() + d.update(self._query_status()) + d['name'] = self.name() + d['display_name'] = self.display_name() + d['description'] = self.description() + return d + + # actions + # XXX: the necessary C bindings for start() and stop() are + # implemented but for now I prefer not to expose them. + # I may change my mind in the future. Reasons: + # - they require Administrator privileges + # - can't implement a timeout for stop() (unless by using a thread, + # which sucks) + # - would require adding ServiceAlreadyStarted and + # ServiceAlreadyStopped exceptions, adding two new APIs. + # - we might also want to have modify(), which would basically mean + # rewriting win32serviceutil.ChangeServiceConfig, which involves a + # lot of stuff (and API constants which would pollute the API), see: + # http://pyxr.sourceforge.net/PyXR/c/python24/lib/site-packages/ + # win32/lib/win32serviceutil.py.html#0175 + # - psutil is typically about "read only" monitoring stuff; + # win_service_* APIs should only be used to retrieve a service and + # check whether it's running + + # def start(self, timeout=None): + # with self._wrap_exceptions(): + # cext.winservice_start(self.name()) + # if timeout: + # giveup_at = time.time() + timeout + # while True: + # if self.status() == "running": + # return + # else: + # if time.time() > giveup_at: + # raise TimeoutExpired(timeout) + # else: + # time.sleep(.1) + + # def stop(self): + # # Note: timeout is not implemented because it's just not + # # possible, see: + # # http://stackoverflow.com/questions/11973228/ + # with self._wrap_exceptions(): + # return cext.winservice_stop(self.name()) + + +# ===================================================================== +# --- processes +# ===================================================================== + + +pids = cext.pids +pid_exists = cext.pid_exists +ppid_map = cext.ppid_map # used internally by Process.children() + + +def is_permission_err(exc): + """Return True if this is a permission error.""" + assert isinstance(exc, OSError), exc + return isinstance(exc, PermissionError) or exc.winerror in { + cext.ERROR_ACCESS_DENIED, + cext.ERROR_PRIVILEGE_NOT_HELD, + } + + +def convert_oserror(exc, pid=None, name=None): + """Convert OSError into NoSuchProcess or AccessDenied.""" + assert isinstance(exc, OSError), exc + if is_permission_err(exc): + return AccessDenied(pid=pid, name=name) + if isinstance(exc, ProcessLookupError): + return NoSuchProcess(pid=pid, name=name) + raise exc + + +def wrap_exceptions(fun): + """Decorator which converts OSError into NoSuchProcess or AccessDenied.""" + + @functools.wraps(fun) + def wrapper(self, *args, **kwargs): + try: + return fun(self, *args, **kwargs) + except OSError as err: + raise convert_oserror(err, pid=self.pid, name=self._name) from err + + return wrapper + + +def retry_error_partial_copy(fun): + """Workaround for https://github.com/giampaolo/psutil/issues/875. + See: https://stackoverflow.com/questions/4457745#4457745. + """ + + @functools.wraps(fun) + def wrapper(self, *args, **kwargs): + delay = 0.0001 + times = 33 + for _ in range(times): # retries for roughly 1 second + try: + return fun(self, *args, **kwargs) + except OSError as _: + err = _ + if err.winerror == ERROR_PARTIAL_COPY: + time.sleep(delay) + delay = min(delay * 2, 0.04) + continue + raise + msg = ( + f"{fun} retried {times} times, converted to AccessDenied as it's " + f"still returning {err}" + ) + raise AccessDenied(pid=self.pid, name=self._name, msg=msg) + + return wrapper + + +class Process: + """Wrapper class around underlying C implementation.""" + + __slots__ = ["_cache", "_name", "_ppid", "pid"] + + def __init__(self, pid): + self.pid = pid + self._name = None + self._ppid = None + + # --- oneshot() stuff + + def oneshot_enter(self): + self._proc_info.cache_activate(self) + self.exe.cache_activate(self) + + def oneshot_exit(self): + self._proc_info.cache_deactivate(self) + self.exe.cache_deactivate(self) + + @memoize_when_activated + def _proc_info(self): + """Return multiple information about this process as a + raw tuple. + """ + ret = cext.proc_info(self.pid) + assert len(ret) == len(pinfo_map) + return ret + + def name(self): + """Return process name, which on Windows is always the final + part of the executable. + """ + # This is how PIDs 0 and 4 are always represented in taskmgr + # and process-hacker. + if self.pid == 0: + return "System Idle Process" + if self.pid == 4: + return "System" + return os.path.basename(self.exe()) + + @wrap_exceptions + @memoize_when_activated + def exe(self): + if PYPY: + try: + exe = cext.proc_exe(self.pid) + except OSError as err: + # 24 = ERROR_TOO_MANY_OPEN_FILES. Not sure why this happens + # (perhaps PyPy's JIT delaying garbage collection of files?). + if err.errno == 24: + debug(f"{err!r} translated into AccessDenied") + raise AccessDenied(self.pid, self._name) from err + raise + else: + exe = cext.proc_exe(self.pid) + if exe.startswith('\\'): + return convert_dos_path(exe) + return exe # May be "Registry", "MemCompression", ... + + @wrap_exceptions + @retry_error_partial_copy + def cmdline(self): + if cext.WINVER >= cext.WINDOWS_8_1: + # PEB method detects cmdline changes but requires more + # privileges: https://github.com/giampaolo/psutil/pull/1398 + try: + return cext.proc_cmdline(self.pid, use_peb=True) + except OSError as err: + if is_permission_err(err): + return cext.proc_cmdline(self.pid, use_peb=False) + else: + raise + else: + return cext.proc_cmdline(self.pid, use_peb=True) + + @wrap_exceptions + @retry_error_partial_copy + def environ(self): + s = cext.proc_environ(self.pid) + return parse_environ_block(s) + + def ppid(self): + try: + return ppid_map()[self.pid] + except KeyError: + raise NoSuchProcess(self.pid, self._name) from None + + def _get_raw_meminfo(self): + try: + return cext.proc_memory_info(self.pid) + except OSError as err: + if is_permission_err(err): + # TODO: the C ext can probably be refactored in order + # to get this from cext.proc_info() + debug("attempting memory_info() fallback (slower)") + info = self._proc_info() + return ( + info[pinfo_map['num_page_faults']], + info[pinfo_map['peak_wset']], + info[pinfo_map['wset']], + info[pinfo_map['peak_paged_pool']], + info[pinfo_map['paged_pool']], + info[pinfo_map['peak_non_paged_pool']], + info[pinfo_map['non_paged_pool']], + info[pinfo_map['pagefile']], + info[pinfo_map['peak_pagefile']], + info[pinfo_map['mem_private']], + ) + raise + + @wrap_exceptions + def memory_info(self): + # on Windows RSS == WorkingSetSize and VSM == PagefileUsage. + # Underlying C function returns fields of PROCESS_MEMORY_COUNTERS + # struct. + t = self._get_raw_meminfo() + rss = t[2] # wset + vms = t[7] # pagefile + return pmem(*(rss, vms) + t) + + @wrap_exceptions + def memory_full_info(self): + basic_mem = self.memory_info() + uss = cext.proc_memory_uss(self.pid) + uss *= getpagesize() + return pfullmem(*basic_mem + (uss,)) + + def memory_maps(self): + try: + raw = cext.proc_memory_maps(self.pid) + except OSError as err: + # XXX - can't use wrap_exceptions decorator as we're + # returning a generator; probably needs refactoring. + raise convert_oserror(err, self.pid, self._name) from err + else: + for addr, perm, path, rss in raw: + path = convert_dos_path(path) + addr = hex(addr) + yield (addr, perm, path, rss) + + @wrap_exceptions + def kill(self): + return cext.proc_kill(self.pid) + + @wrap_exceptions + def send_signal(self, sig): + if sig == signal.SIGTERM: + cext.proc_kill(self.pid) + elif sig in {signal.CTRL_C_EVENT, signal.CTRL_BREAK_EVENT}: + os.kill(self.pid, sig) + else: + msg = ( + "only SIGTERM, CTRL_C_EVENT and CTRL_BREAK_EVENT signals " + "are supported on Windows" + ) + raise ValueError(msg) + + @wrap_exceptions + def wait(self, timeout=None): + if timeout is None: + cext_timeout = cext.INFINITE + else: + # WaitForSingleObject() expects time in milliseconds. + cext_timeout = int(timeout * 1000) + + timer = getattr(time, 'monotonic', time.time) + stop_at = timer() + timeout if timeout is not None else None + + try: + # Exit code is supposed to come from GetExitCodeProcess(). + # May also be None if OpenProcess() failed with + # ERROR_INVALID_PARAMETER, meaning PID is already gone. + exit_code = cext.proc_wait(self.pid, cext_timeout) + except cext.TimeoutExpired as err: + # WaitForSingleObject() returned WAIT_TIMEOUT. Just raise. + raise TimeoutExpired(timeout, self.pid, self._name) from err + except cext.TimeoutAbandoned: + # WaitForSingleObject() returned WAIT_ABANDONED, see: + # https://github.com/giampaolo/psutil/issues/1224 + # We'll just rely on the internal polling and return None + # when the PID disappears. Subprocess module does the same + # (return None): + # https://github.com/python/cpython/blob/ + # be50a7b627d0aa37e08fa8e2d5568891f19903ce/ + # Lib/subprocess.py#L1193-L1194 + exit_code = None + + # At this point WaitForSingleObject() returned WAIT_OBJECT_0, + # meaning the process is gone. Stupidly there are cases where + # its PID may still stick around so we do a further internal + # polling. + delay = 0.0001 + while True: + if not pid_exists(self.pid): + return exit_code + if stop_at and timer() >= stop_at: + raise TimeoutExpired(timeout, pid=self.pid, name=self._name) + time.sleep(delay) + delay = min(delay * 2, 0.04) # incremental delay + + @wrap_exceptions + def username(self): + if self.pid in {0, 4}: + return 'NT AUTHORITY\\SYSTEM' + domain, user = cext.proc_username(self.pid) + return f"{domain}\\{user}" + + @wrap_exceptions + def create_time(self, fast_only=False): + # Note: proc_times() not put under oneshot() 'cause create_time() + # is already cached by the main Process class. + try: + _user, _system, created = cext.proc_times(self.pid) + return created + except OSError as err: + if is_permission_err(err): + if fast_only: + raise + debug("attempting create_time() fallback (slower)") + return self._proc_info()[pinfo_map['create_time']] + raise + + @wrap_exceptions + def num_threads(self): + return self._proc_info()[pinfo_map['num_threads']] + + @wrap_exceptions + def threads(self): + rawlist = cext.proc_threads(self.pid) + retlist = [] + for thread_id, utime, stime in rawlist: + ntuple = _common.pthread(thread_id, utime, stime) + retlist.append(ntuple) + return retlist + + @wrap_exceptions + def cpu_times(self): + try: + user, system, _created = cext.proc_times(self.pid) + except OSError as err: + if not is_permission_err(err): + raise + debug("attempting cpu_times() fallback (slower)") + info = self._proc_info() + user = info[pinfo_map['user_time']] + system = info[pinfo_map['kernel_time']] + # Children user/system times are not retrievable (set to 0). + return _common.pcputimes(user, system, 0.0, 0.0) + + @wrap_exceptions + def suspend(self): + cext.proc_suspend_or_resume(self.pid, True) + + @wrap_exceptions + def resume(self): + cext.proc_suspend_or_resume(self.pid, False) + + @wrap_exceptions + @retry_error_partial_copy + def cwd(self): + if self.pid in {0, 4}: + raise AccessDenied(self.pid, self._name) + # return a normalized pathname since the native C function appends + # "\\" at the and of the path + path = cext.proc_cwd(self.pid) + return os.path.normpath(path) + + @wrap_exceptions + def open_files(self): + if self.pid in {0, 4}: + return [] + ret = set() + # Filenames come in in native format like: + # "\Device\HarddiskVolume1\Windows\systemew\file.txt" + # Convert the first part in the corresponding drive letter + # (e.g. "C:\") by using Windows's QueryDosDevice() + raw_file_names = cext.proc_open_files(self.pid) + for file in raw_file_names: + file = convert_dos_path(file) + if isfile_strict(file): + ntuple = _common.popenfile(file, -1) + ret.add(ntuple) + return list(ret) + + @wrap_exceptions + def net_connections(self, kind='inet'): + return net_connections(kind, _pid=self.pid) + + @wrap_exceptions + def nice_get(self): + value = cext.proc_priority_get(self.pid) + value = Priority(value) + return value + + @wrap_exceptions + def nice_set(self, value): + return cext.proc_priority_set(self.pid, value) + + @wrap_exceptions + def ionice_get(self): + ret = cext.proc_io_priority_get(self.pid) + ret = IOPriority(ret) + return ret + + @wrap_exceptions + def ionice_set(self, ioclass, value): + if value: + msg = "value argument not accepted on Windows" + raise TypeError(msg) + if ioclass not in { + IOPriority.IOPRIO_VERYLOW, + IOPriority.IOPRIO_LOW, + IOPriority.IOPRIO_NORMAL, + IOPriority.IOPRIO_HIGH, + }: + msg = f"{ioclass} is not a valid priority" + raise ValueError(msg) + cext.proc_io_priority_set(self.pid, ioclass) + + @wrap_exceptions + def io_counters(self): + try: + ret = cext.proc_io_counters(self.pid) + except OSError as err: + if not is_permission_err(err): + raise + debug("attempting io_counters() fallback (slower)") + info = self._proc_info() + ret = ( + info[pinfo_map['io_rcount']], + info[pinfo_map['io_wcount']], + info[pinfo_map['io_rbytes']], + info[pinfo_map['io_wbytes']], + info[pinfo_map['io_count_others']], + info[pinfo_map['io_bytes_others']], + ) + return pio(*ret) + + @wrap_exceptions + def status(self): + suspended = cext.proc_is_suspended(self.pid) + if suspended: + return _common.STATUS_STOPPED + else: + return _common.STATUS_RUNNING + + @wrap_exceptions + def cpu_affinity_get(self): + def from_bitmask(x): + return [i for i in range(64) if (1 << i) & x] + + bitmask = cext.proc_cpu_affinity_get(self.pid) + return from_bitmask(bitmask) + + @wrap_exceptions + def cpu_affinity_set(self, value): + def to_bitmask(ls): + if not ls: + msg = f"invalid argument {ls!r}" + raise ValueError(msg) + out = 0 + for b in ls: + out |= 2**b + return out + + # SetProcessAffinityMask() states that ERROR_INVALID_PARAMETER + # is returned for an invalid CPU but this seems not to be true, + # therefore we check CPUs validy beforehand. + allcpus = list(range(len(per_cpu_times()))) + for cpu in value: + if cpu not in allcpus: + if not isinstance(cpu, int): + msg = f"invalid CPU {cpu!r}; an integer is required" + raise TypeError(msg) + msg = f"invalid CPU {cpu!r}" + raise ValueError(msg) + + bitmask = to_bitmask(value) + cext.proc_cpu_affinity_set(self.pid, bitmask) + + @wrap_exceptions + def num_handles(self): + try: + return cext.proc_num_handles(self.pid) + except OSError as err: + if is_permission_err(err): + debug("attempting num_handles() fallback (slower)") + return self._proc_info()[pinfo_map['num_handles']] + raise + + @wrap_exceptions + def num_ctx_switches(self): + ctx_switches = self._proc_info()[pinfo_map['ctx_switches']] + # only voluntary ctx switches are supported + return _common.pctxsw(ctx_switches, 0) diff --git a/venv/lib/python3.10/site-packages/ray/train/__init__.py b/venv/lib/python3.10/site-packages/ray/train/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7713ccb705afc01bc9880f08e56bef578fe819b8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/__init__.py @@ -0,0 +1,84 @@ +# Try import ray[train] core requirements (defined in setup.py) +# isort: off +try: + import fsspec # noqa: F401 + import pandas # noqa: F401 + import pyarrow # noqa: F401 + import requests # noqa: F401 +except ImportError as exc: + raise ImportError( + "Can't import ray.train as some dependencies are missing. " + 'Run `pip install "ray[train]"` to fix.' + ) from exc +# isort: on + + +from ray.air.config import CheckpointConfig, FailureConfig, RunConfig, ScalingConfig +from ray.air.result import Result + +# Import this first so it can be used in other modules +from ray.train._checkpoint import Checkpoint +from ray.train._internal.data_config import DataConfig +from ray.train._internal.session import get_checkpoint, get_dataset_shard, report +from ray.train._internal.syncer import SyncConfig +from ray.train.backend import BackendConfig +from ray.train.constants import TRAIN_DATASET_KEY +from ray.train.context import get_context +from ray.train.trainer import TrainingIterator +from ray.train.v2._internal.constants import is_v2_enabled + +if is_v2_enabled(): + from ray.train.v2.api.callback import UserCallback # noqa: F811 + from ray.train.v2.api.config import ( # noqa: F811 + FailureConfig, + RunConfig, + ScalingConfig, + ) + from ray.train.v2.api.result import Result # noqa: F811 + from ray.train.v2.api.train_fn_utils import ( # noqa: F811 + get_checkpoint, + get_context, + get_dataset_shard, + report, + ) + + +__all__ = [ + "get_checkpoint", + "get_context", + "get_dataset_shard", + "report", + "BackendConfig", + "Checkpoint", + "CheckpointConfig", + "DataConfig", + "FailureConfig", + "Result", + "RunConfig", + "ScalingConfig", + "SyncConfig", + "TrainingIterator", + "TRAIN_DATASET_KEY", +] + +get_checkpoint.__module__ = "ray.train" +get_context.__module__ = "ray.train" +get_dataset_shard.__module__ = "ray.train" +report.__module__ = "ray.train" +BackendConfig.__module__ = "ray.train" +Checkpoint.__module__ = "ray.train" +CheckpointConfig.__module__ = "ray.train" +DataConfig.__module__ = "ray.train" +FailureConfig.__module__ = "ray.train" +Result.__module__ = "ray.train" +RunConfig.__module__ = "ray.train" +ScalingConfig.__module__ = "ray.train" +SyncConfig.__module__ = "ray.train" +TrainingIterator.__module__ = "ray.train" + +if is_v2_enabled(): + __all__.append("UserCallback") + UserCallback.__module__ = "ray.train" + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8f96553e7ec6e16793c2169c7b9b3e601a91d2d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/_checkpoint.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/_checkpoint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2da43c602fd002eed94ae6e2cf44e2c12d48f4b4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/_checkpoint.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/backend.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/backend.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba271edf62851b4fbacb59f883edf79325e1bbda Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/backend.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/base_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/base_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69c9e6cfa06d3183610206e5f868863f2c791386 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/base_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/constants.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1091c7e70f3ea3e41932f6648bf02f76244dd298 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/constants.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/context.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a476cbe3f6dee7fccc54212fb98c3ab33ee708a Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/context.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/data_parallel_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/data_parallel_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24753bba635a43ca1481dc1d16420c853d298926 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/data_parallel_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/error.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/error.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a708e9eab525c0bc54cb2b59e34a0870dabd9b0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/error.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/predictor.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/predictor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c20934e867c25257b2eaf6d9b55a96d46c4b914 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/predictor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/session.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/session.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7afa64cc2d5a17bccdc2363c0e8b821f36ee9d6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/session.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3a8101e99a9fb0b82e348f3f52b1a74a54763dc Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bff7c42ef5f95a4ab42e5b8183ad3d6eff78c130 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_checkpoint.py b/venv/lib/python3.10/site-packages/ray/train/_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..5ee65be4f20fe17126b315726bcfb825e9c89e45 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_checkpoint.py @@ -0,0 +1,424 @@ +import contextlib +import glob +import json +import logging +import os +import platform +import shutil +import tempfile +import traceback +import uuid +from pathlib import Path +from typing import Any, Dict, Iterator, List, Optional, Union + +import pyarrow.fs + +from ray.air._internal.filelock import TempFileLock +from ray.train._internal.storage import _download_from_fs_path, _exists_at_fs_path +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + +# The filename of the file that stores user metadata set on the checkpoint. +_METADATA_FILE_NAME = ".metadata.json" + +# The prefix of the temp checkpoint directory that `to_directory` downloads to +# on the local filesystem. +_CHECKPOINT_TEMP_DIR_PREFIX = "checkpoint_tmp_" + + +class _CheckpointMetaClass(type): + def __getattr__(self, item): + try: + return super().__getattribute__(item) + except AttributeError as exc: + if item in { + "from_dict", + "to_dict", + "from_bytes", + "to_bytes", + "get_internal_representation", + }: + raise _get_migration_error(item) from exc + elif item in { + "from_uri", + "to_uri", + "uri", + }: + raise _get_uri_error(item) from exc + elif item in {"get_preprocessor", "set_preprocessor"}: + raise _get_preprocessor_error(item) from exc + + raise exc + + +@PublicAPI(stability="beta") +class Checkpoint(metaclass=_CheckpointMetaClass): + """A reference to data persisted as a directory in local or remote storage. + + Access the checkpoint contents locally using ``checkpoint.to_directory()`` + or ``checkpoint.as_directory``. + + Attributes + ---------- + path: A path on the filesystem containing the checkpoint contents. + filesystem: PyArrow FileSystem that can be used to access data at the `path`. + + See Also + -------- + ray.train.report : Report a checkpoint during training (with Ray Train/Tune). + ray.train.get_checkpoint : Get the latest checkpoint during training + (for restoration). + + :ref:`train-checkpointing` + :ref:`persistent-storage-guide` + + Examples + -------- + + Creating a checkpoint using ``Checkpoint.from_directory``: + + >>> from ray.train import Checkpoint + >>> checkpoint = Checkpoint.from_directory("/tmp/example_checkpoint_dir") + >>> checkpoint.filesystem # doctest: +ELLIPSIS + >> checkpoint.path + '/tmp/example_checkpoint_dir' + + Creating a checkpoint from a remote URI: + + >>> checkpoint = Checkpoint("s3://bucket/path/to/checkpoint") + >>> checkpoint.filesystem # doctest: +ELLIPSIS + >> checkpoint.path + 'bucket/path/to/checkpoint' + + Creating a checkpoint with a custom filesystem: + + >>> checkpoint = Checkpoint( + ... path="bucket/path/to/checkpoint", + ... filesystem=pyarrow.fs.S3FileSystem(), + ... ) + >>> checkpoint.filesystem # doctest: +ELLIPSIS + >> checkpoint.path + 'bucket/path/to/checkpoint' + + Accessing a checkpoint's contents: + + >>> import os # doctest: +SKIP + >>> with checkpoint.as_directory() as local_checkpoint_dir: # doctest: +SKIP + ... print(os.listdir(local_checkpoint_dir)) # doctest: +SKIP + ['model.pt', 'optimizer.pt', 'misc.pt'] + """ + + def __init__( + self, + path: Union[str, os.PathLike], + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + ): + """Construct a Checkpoint. + + Args: + path: A local path or remote URI containing the checkpoint data. + If a filesystem is provided, then this path must NOT be a URI. + It should be a path on the filesystem with the prefix already stripped. + filesystem: PyArrow FileSystem to use to access data at the path. + If not specified, this is inferred from the URI scheme. + """ + self.path = str(path) + self.filesystem = filesystem + + if path and not filesystem: + self.filesystem, self.path = pyarrow.fs.FileSystem.from_uri(path) + + # This random UUID is used to create a temporary directory name on the + # local filesystem, which will be used for downloading checkpoint data. + # This ensures that if multiple processes download the same checkpoint object + # only one process performs the actual download while the others wait. + # This prevents duplicated download efforts and data. + # NOTE: Calling `to_directory` from multiple `Checkpoint` objects + # that point to the same (fs, path) will still download the data multiple times. + # This only ensures a canonical temp directory name for a single `Checkpoint`. + self._uuid = uuid.uuid4() + + def __repr__(self): + return f"Checkpoint(filesystem={self.filesystem.type_name}, path={self.path})" + + def get_metadata(self) -> Dict[str, Any]: + """Return the metadata dict stored with the checkpoint. + + If no metadata is stored, an empty dict is returned. + """ + metadata_path = Path(self.path, _METADATA_FILE_NAME).as_posix() + if not _exists_at_fs_path(self.filesystem, metadata_path): + return {} + + with self.filesystem.open_input_file(metadata_path) as f: + return json.loads(f.readall().decode("utf-8")) + + def set_metadata(self, metadata: Dict[str, Any]) -> None: + """Set the metadata stored with this checkpoint. + + This will overwrite any existing metadata stored with this checkpoint. + """ + metadata_path = Path(self.path, _METADATA_FILE_NAME).as_posix() + with self.filesystem.open_output_stream(metadata_path) as f: + f.write(json.dumps(metadata).encode("utf-8")) + + def update_metadata(self, metadata: Dict[str, Any]) -> None: + """Update the metadata stored with this checkpoint. + + This will update any existing metadata stored with this checkpoint. + """ + existing_metadata = self.get_metadata() + existing_metadata.update(metadata) + self.set_metadata(existing_metadata) + + @classmethod + def from_directory(cls, path: Union[str, os.PathLike]) -> "Checkpoint": + """Create checkpoint object from a local directory. + + Args: + path: Local directory containing checkpoint data. + + Returns: + A ray.train.Checkpoint object. + """ + return cls(path, filesystem=pyarrow.fs.LocalFileSystem()) + + def to_directory(self, path: Optional[Union[str, os.PathLike]] = None) -> str: + """Write checkpoint data to a local directory. + + *If multiple processes on the same node call this method simultaneously,* + only a single process will perform the download, while the others + wait for the download to finish. Once the download finishes, all processes + receive the same local directory to read from. + + Args: + path: Target directory to download data to. If not specified, + this method will use a temporary directory. + + Returns: + str: Directory containing checkpoint data. + """ + user_provided_path = path is not None + local_path = ( + path if user_provided_path else self._get_temporary_checkpoint_dir() + ) + local_path = os.path.normpath(os.path.expanduser(str(local_path))) + os.makedirs(local_path, exist_ok=True) + + try: + # Timeout 0 means there will be only one attempt to acquire + # the file lock. If it cannot be acquired, throw a TimeoutError + with TempFileLock(local_path, timeout=0): + _download_from_fs_path( + fs=self.filesystem, fs_path=self.path, local_path=local_path + ) + except TimeoutError: + # if the directory is already locked, then wait but do not do anything. + with TempFileLock(local_path, timeout=-1): + pass + if not os.path.exists(local_path): + raise RuntimeError( + f"Checkpoint directory {local_path} does not exist, " + "even though it should have been created by " + "another process. Please raise an issue on GitHub: " + "https://github.com/ray-project/ray/issues" + ) + + return local_path + + @contextlib.contextmanager + def as_directory(self) -> Iterator[str]: + """Returns checkpoint contents in a local directory as a context. + + This function makes checkpoint data available as a directory while avoiding + unnecessary copies and left-over temporary data. + + *If the checkpoint points to a local directory*, this method just returns the + local directory path without making a copy, and nothing will be cleaned up + after exiting the context. + + *If the checkpoint points to a remote directory*, this method will download the + checkpoint to a local temporary directory and return the path + to the temporary directory. + + *If multiple processes on the same node call this method simultaneously,* + only a single process will perform the download, while the others + wait for the download to finish. Once the download finishes, all processes + receive the same local (temporary) directory to read from. + + Once all processes have finished working with the checkpoint, + the temporary directory is cleaned up. + + Users should treat the returned checkpoint directory as read-only and avoid + changing any data within it, as it may be deleted when exiting the context. + + Example: + + .. testcode:: + :hide: + + from pathlib import Path + import tempfile + + from ray.train import Checkpoint + + temp_dir = tempfile.mkdtemp() + (Path(temp_dir) / "example.txt").write_text("example checkpoint data") + checkpoint = Checkpoint.from_directory(temp_dir) + + .. testcode:: + + with checkpoint.as_directory() as checkpoint_dir: + # Do some read-only processing of files within checkpoint_dir + pass + + # At this point, if a temporary directory was created, it will have + # been deleted. + + """ + if isinstance(self.filesystem, pyarrow.fs.LocalFileSystem): + yield self.path + else: + del_lock_path = _get_del_lock_path(self._get_temporary_checkpoint_dir()) + open(del_lock_path, "a").close() + + temp_dir = self.to_directory() + try: + yield temp_dir + finally: + # Always cleanup the del lock after we're done with the directory. + # This avoids leaving a lock file behind in the case of an exception + # in the user code. + try: + os.remove(del_lock_path) + except Exception: + logger.warning( + f"Could not remove {del_lock_path} deletion file lock. " + f"Traceback:\n{traceback.format_exc()}" + ) + + # If there are no more lock files, that means there are no more + # readers of this directory, and we can safely delete it. + # In the edge case (process crash before del lock file is removed), + # we do not remove the directory at all. + # Since it's in /tmp, this is not that big of a deal. + # check if any lock files are remaining + remaining_locks = _list_existing_del_locks(temp_dir) + if not remaining_locks: + try: + # Timeout 0 means there will be only one attempt to acquire + # the file lock. If it cannot be acquired, a TimeoutError + # will be thrown. + with TempFileLock(temp_dir, timeout=0): + shutil.rmtree(temp_dir, ignore_errors=True) + except TimeoutError: + pass + + def _get_temporary_checkpoint_dir(self) -> str: + """Return the name for the temporary checkpoint dir that this checkpoint + will get downloaded to, if accessing via `to_directory` or `as_directory`. + """ + tmp_dir_path = tempfile.gettempdir() + checkpoint_dir_name = _CHECKPOINT_TEMP_DIR_PREFIX + self._uuid.hex + if platform.system() == "Windows": + # Max path on Windows is 260 chars, -1 for joining \ + # Also leave a little for the del lock + del_lock_name = _get_del_lock_path("") + checkpoint_dir_name = ( + _CHECKPOINT_TEMP_DIR_PREFIX + + self._uuid.hex[ + -259 + + len(_CHECKPOINT_TEMP_DIR_PREFIX) + + len(tmp_dir_path) + + len(del_lock_name) : + ] + ) + if not checkpoint_dir_name.startswith(_CHECKPOINT_TEMP_DIR_PREFIX): + raise RuntimeError( + "Couldn't create checkpoint directory due to length " + "constraints. Try specifying a shorter checkpoint path." + ) + return Path(tmp_dir_path, checkpoint_dir_name).as_posix() + + def __fspath__(self): + raise TypeError( + "You cannot use `Checkpoint` objects directly as paths. " + "Use `Checkpoint.to_directory()` or `Checkpoint.as_directory()` instead." + ) + + +def _get_del_lock_path(path: str, suffix: str = None) -> str: + """Get the path to the deletion lock file for a file/directory at `path`. + + Example: + + >>> _get_del_lock_path("/tmp/checkpoint_tmp") # doctest: +ELLIPSIS + '/tmp/checkpoint_tmp.del_lock_... + >>> _get_del_lock_path("/tmp/checkpoint_tmp/") # doctest: +ELLIPSIS + '/tmp/checkpoint_tmp.del_lock_... + >>> _get_del_lock_path("/tmp/checkpoint_tmp.txt") # doctest: +ELLIPSIS + '/tmp/checkpoint_tmp.txt.del_lock_... + + """ + suffix = suffix if suffix is not None else str(os.getpid()) + return f"{path.rstrip('/')}.del_lock_{suffix}" + + +def _list_existing_del_locks(path: str) -> List[str]: + """List all the deletion lock files for a file/directory at `path`. + + For example, if 2 checkpoints are being read via `as_directory`, + then this should return a list of 2 deletion lock files. + """ + return list(glob.glob(f"{_get_del_lock_path(path, suffix='*')}")) + + +def _get_migration_error(name: str): + return AttributeError( + f"The new `ray.train.Checkpoint` class does not support `{name}()`. " + f"Instead, only directories are supported.\n\n" + f"Example to store a dictionary in a checkpoint:\n\n" + f"import os, tempfile\n" + f"import ray.cloudpickle as pickle\n" + f"from ray import train\n" + f"from ray.train import Checkpoint\n\n" + f"with tempfile.TemporaryDirectory() as checkpoint_dir:\n" + f" with open(os.path.join(checkpoint_dir, 'data.pkl'), 'wb') as fp:\n" + f" pickle.dump({{'data': 'value'}}, fp)\n\n" + f" checkpoint = Checkpoint.from_directory(checkpoint_dir)\n" + f" train.report(..., checkpoint=checkpoint)\n\n" + f"Example to load a dictionary from a checkpoint:\n\n" + f"if train.get_checkpoint():\n" + f" with train.get_checkpoint().as_directory() as checkpoint_dir:\n" + f" with open(os.path.join(checkpoint_dir, 'data.pkl'), 'rb') as fp:\n" + f" data = pickle.load(fp)" + ) + + +def _get_uri_error(name: str): + return AttributeError( + f"The new `ray.train.Checkpoint` class does not support `{name}()`. " + f"To create a checkpoint from remote storage, create a `Checkpoint` using its " + f"constructor instead of `from_directory`.\n" + f'Example: `Checkpoint(path="s3://a/b/c")`.\n' + f"Then, access the contents of the checkpoint with " + f"`checkpoint.as_directory()` / `checkpoint.to_directory()`.\n" + f"To upload data to remote storage, use e.g. `pyarrow.fs.FileSystem` " + f"or your client of choice." + ) + + +def _get_preprocessor_error(name: str): + return AttributeError( + f"The new `ray.train.Checkpoint` class does not support `{name}()`. " + f"To include preprocessor information in checkpoints, " + f"pass it as metadata in the Trainer constructor.\n" + f"Example: `TorchTrainer(..., metadata={{...}})`.\n" + f"After training, access it in the checkpoint via `checkpoint.get_metadata()`. " + f"See here: https://docs.ray.io/en/master/train/user-guides/" + f"data-loading-preprocessing.html#preprocessing-structured-data" + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__init__.py b/venv/lib/python3.10/site-packages/ray/train/_internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6229640fa6eca119945fe1359e1c400aa996a8e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/accelerator.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/accelerator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..363e4becf023bbf2b6f994a01a837302d7d45409 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/accelerator.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/backend_executor.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/backend_executor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..364974c43ef18f6afbde3840c7284cd674e30d2c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/backend_executor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/checkpoint_manager.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/checkpoint_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c18723c92eab489d8d9b106cce510d801fc38bed Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/checkpoint_manager.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/data_config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/data_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5a7a91dd0c52a6068769a1312be0e01999c9612 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/data_config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/dl_predictor.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/dl_predictor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dfbfcb0c686f31bd7d86667866d6f192d1f7847 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/dl_predictor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/framework_checkpoint.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/framework_checkpoint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c265647109e0d6446a72509df5576048ba030526 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/framework_checkpoint.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/session.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/session.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ed076cb6c66a428f8f7409bfc580251e685c028 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/session.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/storage.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/storage.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37348893b65dce3c663cd51e07f89dd023d11058 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/storage.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/syncer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/syncer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfb43840fc9d826a1e747f75eb3c0b3aeb1f36c9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/syncer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..211a374d840789cb0edd297b6ff1cf93d159ba9f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/worker_group.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/worker_group.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..201b50d89ae129ccdf4dbb0856e90bcf4824138c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/__pycache__/worker_group.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/accelerator.py b/venv/lib/python3.10/site-packages/ray/train/_internal/accelerator.py new file mode 100644 index 0000000000000000000000000000000000000000..1c31098d86defc704ddef75172543813361119da --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/accelerator.py @@ -0,0 +1,5 @@ +import abc + + +class Accelerator(abc.ABC): + """A utility that contains methods to accelerate training.""" diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/backend_executor.py b/venv/lib/python3.10/site-packages/ray/train/_internal/backend_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4b7e86e06214dd6c06a15ea27de35c481e6490 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/backend_executor.py @@ -0,0 +1,833 @@ +import logging +import os +import time +from collections import defaultdict +from dataclasses import dataclass +from typing import Any, Callable, Dict, List, Optional, Tuple, Type, TypeVar + +import ray +import ray._private.ray_constants as ray_constants +from ray._private.accelerators.amd_gpu import HIP_VISIBLE_DEVICES_ENV_VAR +from ray._private.accelerators.neuron import NEURON_RT_VISIBLE_CORES_ENV_VAR +from ray._private.accelerators.npu import ASCEND_RT_VISIBLE_DEVICES_ENV_VAR +from ray._private.accelerators.nvidia_gpu import CUDA_VISIBLE_DEVICES_ENV_VAR +from ray._private.ray_constants import env_integer +from ray.data import Dataset +from ray.exceptions import RayActorError +from ray.train import Checkpoint, DataConfig +from ray.train._internal.session import ( + TrialInfo, + _TrainingResult, + get_session, + init_session, + shutdown_session, +) +from ray.train._internal.storage import StorageContext +from ray.train._internal.utils import check_for_failure +from ray.train._internal.worker_group import WorkerGroup +from ray.train.backend import BackendConfig +from ray.train.constants import ( + ENABLE_DETAILED_AUTOFILLED_METRICS_ENV, + ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV, + ENABLE_SHARE_HIP_VISIBLE_DEVICES_ENV, + ENABLE_SHARE_NEURON_CORES_ACCELERATOR_ENV, + ENABLE_SHARE_NPU_RT_VISIBLE_DEVICES_ENV, + RAY_TRAIN_ENABLE_STATE_TRACKING, + TRAIN_ENABLE_WORKER_SPREAD_ENV, + TRAIN_PLACEMENT_GROUP_TIMEOUT_S_ENV, +) +from ray.util.placement_group import get_current_placement_group, remove_placement_group + +T = TypeVar("T") + +logger = logging.getLogger(__name__) + + +class TrainBackendError(Exception): + """Errors with BackendExecutor that should not be exposed to user.""" + + +class TrainingWorkerError(Exception): + """Raised if a worker fails during training.""" + + +@dataclass +class ResourceConfig: + """ + Resource configuration for resource_ids to share between workers. + + Args: + resource_name: The name of the resource to configure + (Example: "neuron_cores" or "gpu"). + resource_enable_sharing_env_var: The environment variable to + check if the resource should be shared. + share_resource_ids_env_var: The environment variable to configure for + sharing the resources with other workers. + """ + + resource_name: str + resource_enable_sharing_env_var: str + share_resource_ids_env_var: str + + +class BackendExecutor: + """Main execution class for training backends. + + This class holds a worker group and is responsible for executing the + training function on the workers, and collecting intermediate results + from ``session.report()``. + + Args: + backend_config: The configurations for this + specific backend. + num_workers: Number of workers to use for training. + resources_per_worker (Optional[Dict[str, float]]): + Dictionary specifying the resources that will be + requested for each worker. Defaults to {"CPU": 1}. + max_retries: Number of retries when Ray actors fail. + Defaults to 3. Set to -1 for unlimited retries. + """ + + def __init__( + self, + backend_config: BackendConfig, + # TODO(xwjiang): Legacy Ray Train trainer clean up! + trial_info: Optional[TrialInfo] = None, + num_workers: int = 1, + resources_per_worker: Optional[Dict[str, float]] = None, + max_retries: int = 3, + ): + if resources_per_worker is None: + self._resources_per_worker = {"CPU": 1} + else: + self._resources_per_worker = resources_per_worker.copy() + + self._backend_config = backend_config + self._backend = backend_config.backend_cls() + self._num_workers = num_workers + self._max_failures = max_retries + if self._max_failures < 0: + self._max_failures = float("inf") + self._num_failures = 0 + self._last_failure = None + self._initialization_hook = None + self._placement_group = None + + self._trial_info = trial_info + + self.worker_group = InactiveWorkerGroup() + self.dataset_shards = None + + self._resource_configs = [ + ResourceConfig( + ray_constants.NEURON_CORES, + ENABLE_SHARE_NEURON_CORES_ACCELERATOR_ENV, + NEURON_RT_VISIBLE_CORES_ENV_VAR, + ), + ResourceConfig( + ray_constants.NPU, + ENABLE_SHARE_NPU_RT_VISIBLE_DEVICES_ENV, + ASCEND_RT_VISIBLE_DEVICES_ENV_VAR, + ), + # For AMD GPUs, they are using HIP_VISIBLE_DEVICES env var. + ResourceConfig( + ray_constants.GPU, + ENABLE_SHARE_HIP_VISIBLE_DEVICES_ENV, + HIP_VISIBLE_DEVICES_ENV_VAR, + ), + ] + + # Record the initialization time of BackendExecutor, which is + # after trainer.fit() and before worker_group executes the training function. + self._start_time_ms = int(time.time() * 1000) + + self.state_tracking_enabled = env_integer(RAY_TRAIN_ENABLE_STATE_TRACKING, 0) + + def start( + self, + initialization_hook: Optional[Callable[[], None]] = None, + train_cls: Optional[Type] = None, + train_cls_args: Optional[Tuple] = None, + train_cls_kwargs: Optional[Dict] = None, + ): + """Starts the worker group.""" + self._create_placement_group() + placement_group = self._placement_group or "default" + self.worker_group = WorkerGroup( + num_workers=self._num_workers, + resources_per_worker=self._resources_per_worker, + actor_cls=train_cls, + actor_cls_args=train_cls_args, + actor_cls_kwargs=train_cls_kwargs, + placement_group=placement_group, + ) + # Hack to avoid OOMs. + # This is just a temporary solution for Train loading entire checkpoints + # into memory by ensuring that the rank 0 worker is on the same node as + # trainable, thus allowing for lazy checkpoint transfer to be used. + # See https://github.com/ray-project/ray/issues/33073 + # for more context. + # TODO remove passing in trial_driver_ip. + + trial_driver_node_id = ( + self._trial_info.driver_node_id if self._trial_info else None + ) + self.worker_group.sort_workers_by_node_id_and_gpu_id(trial_driver_node_id) + + try: + if initialization_hook: + self._initialization_hook = initialization_hook + self.worker_group.execute(initialization_hook) + + # Always propagate the driver's DataContext to each worker in the group. + from ray.data import DataContext + + def _set_driver_dataset_context(ctx: DataContext): + DataContext._set_current(ctx) + + self.worker_group.execute( + _set_driver_dataset_context, + DataContext.get_current(), + ) + + share_cuda_visible_devices_enabled = bool( + env_integer( + ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV, + self._backend.share_cuda_visible_devices, + ) + ) + + if ( + self._resources_per_worker.get("GPU", 0) > 0 + and share_cuda_visible_devices_enabled + ): + self._share_cuda_visible_devices() + for resource_config in self._resource_configs: + if self._is_share_resources_enabled( + resource_config.resource_name, + resource_config.resource_enable_sharing_env_var, + ): + self._share_resource_ids( + resource_config.resource_name, + resource_config.share_resource_ids_env_var, + ) + self._backend.on_start(self.worker_group, self._backend_config) + except RayActorError as exc: + logger.exception(str(exc)) + logger.warning( + "Failure occurred during startup. Restarting all workers and " + "attempting to startup again." + ) + self._increment_failures() + self._restart() + + if self.state_tracking_enabled: + from ray.train._internal.state import TrainRunStateManager + from ray.train._internal.state.state_actor import get_state_actor + + self.state_manager = TrainRunStateManager(state_actor=get_state_actor()) + + def _create_placement_group(self): + """Creates a placement group if it does not exist. + + If a placement group is already detected (Tune) this will be a no-op. + + By default the placement group will be created with PACK strategy. + This is optimized for colocating GPUs on a minimal number of nodes. + This behavior can be overridden to use the SPREAD strategy by defining + ``TRAIN_ENABLE_WORKER_SPREAD_ENV`` + + If a placement group is created it will be stored as + self._placement_group. + """ + current_placement_group = get_current_placement_group() + worker = ray._private.worker.global_worker + should_capture_child_tasks_in_placement_group = ( + worker.should_capture_child_tasks_in_placement_group + ) + should_create_placement_group = ( + current_placement_group is None + or not should_capture_child_tasks_in_placement_group + ) + + if should_create_placement_group: + bundles = [ + self._resources_per_worker.copy() for _ in range(self._num_workers) + ] + + use_spread = bool(env_integer(TRAIN_ENABLE_WORKER_SPREAD_ENV, 0)) + strategy = "SPREAD" if use_spread else "PACK" + + placement_group = ray.util.placement_group(bundles, strategy=strategy) + logger.debug("Waiting for placement group to start.") + timeout = env_integer(TRAIN_PLACEMENT_GROUP_TIMEOUT_S_ENV, 100) + ready, _ = ray.wait([placement_group.ready()], timeout=timeout) + if ready: + logger.debug("Placement group has started.") + else: + raise TimeoutError( + "Placement group creation timed out. Make sure your " + "cluster either has enough resources or use an " + "autoscaling cluster. If you are running on a cluster, " + "make sure you specify an address in `ray.init()`, for example, " + '`ray.init("auto")`. You can also increase the timeout by setting ' + "the TRAIN_PLACEMENT_GROUP_TIMEOUT_S environment variable. " + "Current resources available: {}, resources requested by the " + "placement group: {}".format( + ray.available_resources(), placement_group.bundle_specs + ) + ) + self._placement_group = placement_group + + def _share_cuda_visible_devices(self): + """Sets CUDA_VISIBLE_DEVICES on all workers. + + For each worker, CUDA_VISIBLE_DEVICES will be set to the GPU IDs + visible to all workers on that worker's node. + + This allows GPU workers on the same node to communicate with one + another. + + Example: + + Setup: + - Node1: + - Worker1: {0, 1} + - Worker2: {2, 3} + - Node2: + - Worker3: {0, 1} + + CUDA_VISIBLE_DEVICES: + - Worker1: "0,1,2,3" + - Worker2: "0,1,2,3" + - Worker3: "0,1" + + """ + self._share_resource_ids(ray_constants.GPU, CUDA_VISIBLE_DEVICES_ENV_VAR) + + def _share_resource_ids(self, resource: str, env_var: str): + """Sets the given env_var on all workers. + + For each worker, the cores/devices are visible to all the + workers on that worker's node.This allows workers on the + same node to communicate with one another. + + Example: + + Setup: + - Node1: + - Worker1: {0, 1} + - Worker2: {2, 3} + - Node2: + - Worker3: {0, 1} + + NEURON_RT_VISIBLE_CORES/TPU_VISIBLE_CHIPS/...: + - Worker1: "0,1,2,3" + - Worker2: "0,1,2,3" + - Worker2: "0,1" + + Args: + resource: The name of the resource/accelerator. + env_var: The name of the environment variable to set. + """ + node_ids_and_resource_ids = [ + ( + w.metadata.node_id, + w.metadata.resource_ids[resource], + ) + for w in self.worker_group.workers + ] + node_id_to_worker_id = defaultdict(set) + node_id_to_resource_ids = defaultdict(set) + + for worker_id, (node_id, resource_ids) in enumerate(node_ids_and_resource_ids): + node_id_to_worker_id[node_id].add(worker_id) + node_id_to_resource_ids[node_id].update(resource_ids) + + futures = [] + for node_id, resource_ids in node_id_to_resource_ids.items(): + resource_ids = sorted(resource_ids) + all_resource_ids = ",".join(resource_ids) + + def set_resource_ids(): + os.environ[env_var] = all_resource_ids + + for worker_id in node_id_to_worker_id[node_id]: + futures.append( + self.worker_group.execute_single_async(worker_id, set_resource_ids) + ) + ray.get(futures) + + def _is_share_resources_enabled(self, resource_name: str, enable_sharing_env: str): + """Whether to share resource IDs on all workers + based on enable_sharing_env. + + This will return true if resources are requested and greater than 0. + Also, user can disable by configuring the `enable_sharing_env` to "0". + + Args: + resource_name: The name of the resource/accelerator. + enable_sharing_env: The name of the environment variable + to check. + """ + has_resource_requested = self._resources_per_worker.get(resource_name, 0) > 0 + return has_resource_requested and ray_constants.env_bool( + enable_sharing_env, True + ) + + def _create_rank_world_size_mappings(self) -> List[Dict]: + """Create rank and world size mappings for workers. + There are three maps returned: + - local_rank_map, which maps from worker world_rank to local_rank. + - local_world_size_map, which maps from world_rank to local_world_size + - node_rank_map, which maps from world rank to node rank + + Example: + Worker 0: node 0 + Worker 1: node 0 + Worker 2: node 1 + Worker 3: node 0 + Worker 4: node 1 + + Workers 0, 1, 3 are on node 0. + Workers 2, 4 are on node 1. + + Expected local_rank_map: + { + 0 -> 0, + 1 -> 1, + 2 -> 0, + 3 -> 2, + 4 -> 1 + } + + Expected local_world_size_map: + { + 0 -> 3, + 1 -> 3, + 2 -> 2, + 3 -> 3, + 4 -> 2 + } + + Expected node_rank_map: + { + 0 -> 0, + 1 -> 0, + 2 -> 1, + 3 -> 0, + 4 -> 1 + } + + """ + local_rank_map = {} # map from world rank to local rank + local_world_size_map = {} # map from world rank to local world size + node_rank_map = {} # map from world rank to node rank + node_ids = {} # map from node id to node index + node_cnt = 0 # count the number of nodes + + node_id_dict = defaultdict( + int + ) # map from node id to the number of workers on it. + for world_rank in range(len(self.worker_group)): + worker = self.worker_group.workers[world_rank] + node_id = worker.metadata.node_id + local_rank_map[world_rank] = node_id_dict[node_id] + node_id_dict[node_id] += 1 + + if node_id not in node_ids: + node_ids[node_id] = node_cnt + node_cnt += 1 + node_rank_map[world_rank] = node_ids[node_id] + + for world_rank in range(len(self.worker_group)): + worker = self.worker_group.workers[world_rank] + node_id = worker.metadata.node_id + local_world_size_map[world_rank] = node_id_dict[node_id] + + workers_info = "\n".join( + [ + f"- (node_id={w.metadata.node_id}, ip={w.metadata.node_ip}, " + f"pid={w.metadata.pid}) world_rank={i}, " + f"local_rank={local_rank_map[i]}, node_rank={node_rank_map[i]}" + for i, w in enumerate(self.worker_group.workers) + ] + ) + logger.info(f"Started distributed worker processes: \n{workers_info}") + + return local_rank_map, local_world_size_map, node_rank_map + + def start_training( + self, + train_func: Callable[[], T], + datasets: Dict[str, Dataset], + metadata: Dict[str, Any], + data_config: DataConfig, + storage: StorageContext, + checkpoint: Optional[Checkpoint] = None, + ) -> None: + """Executes a training function on all workers in a separate thread. + + ``finish_training`` should be called after this. + + Args: + train_func: The training function to run on each worker. + datasets: The base datasets. + data_config: The config object for creating dataset shards for workers. + checkpoint: The checkpoint data that + should be loaded onto each worker and accessed by the + training function via ``session.get_checkpoint()``. If this + is ``None`` then no checkpoint will be loaded. + """ + use_detailed_autofilled_metrics = env_integer( + ENABLE_DETAILED_AUTOFILLED_METRICS_ENV, 0 + ) + + # First initialize the session. + def initialize_session( + train_func, + world_rank, + local_rank, + node_rank, + local_world_size, + world_size, + trial_info, + checkpoint, + dataset_shard, + metadata, + storage, + ): + try: + init_session( + training_func=train_func, + world_rank=world_rank, + local_rank=local_rank, + node_rank=node_rank, + local_world_size=local_world_size, + world_size=world_size, + trial_info=trial_info, + dataset_shard=dataset_shard, + metadata=metadata, + checkpoint=checkpoint, + detailed_autofilled_metrics=use_detailed_autofilled_metrics, + storage=storage, + ) + except ValueError: + raise TrainBackendError( + "Attempting to start training but a " + "previous training run is still ongoing. " + "You must call `finish_training` before " + "calling `start_training` again." + ) + + if self.dataset_shards is None: + actors = [worker.actor for worker in self.worker_group.workers] + node_ids = [worker.metadata.node_id for worker in self.worker_group.workers] + self.dataset_shards = data_config.configure( + datasets, + world_size=len(self.worker_group), + worker_handles=actors, + worker_node_ids=node_ids, + ) + + ( + local_rank_map, + local_world_size_map, + node_rank_map, + ) = self._create_rank_world_size_mappings() + + futures = [] + for index in range(len(self.worker_group)): + futures.append( + self.worker_group.execute_single_async( + index, + initialize_session, + world_rank=index, + local_rank=local_rank_map[index], + node_rank=node_rank_map[index], + local_world_size=local_world_size_map[index], + world_size=len(self.worker_group), + trial_info=self._trial_info, + train_func=train_func, + dataset_shard=self.dataset_shards[index], + metadata=metadata, + checkpoint=checkpoint, + storage=storage, + ) + ) + + self._backend.on_training_start(self.worker_group, self._backend_config) + + self.get_with_failure_handling(futures) + + # Register Train Run before training starts + if self.state_tracking_enabled: + from ray.train._internal.state.schema import RunStatusEnum + + core_context = ray.runtime_context.get_runtime_context() + + self.state_manager.register_train_run( + run_id=self._trial_info.run_id, + run_name=self._trial_info.experiment_name, + job_id=core_context.get_job_id(), + controller_actor_id=core_context.get_actor_id(), + datasets=datasets, + worker_group=self.worker_group, + start_time_ms=self._start_time_ms, + run_status=RunStatusEnum.RUNNING, + resources=[self._resources_per_worker] * self._num_workers, + ) + + # Run the training function asynchronously in its own thread. + def train_async(): + session = get_session() + session.start() + + self.worker_group.execute_async(train_async) + + def get_next_results(self) -> Optional[List[_TrainingResult]]: + """Fetches the next ``_TrainingResult`` from each worker. + + Each ``_TrainingResult`` is expected to correspond to the same step from + each worker (e.g. the same call to ``train.report()``). + + Returns: + A list of ``_TrainingResult``s or ``None`` if there are no more results + since the training function has exited on all workers. + """ + + def get_next(): + session = _get_session("get_next_results") + try: + result = session.get_next() + except RuntimeError: + # Training thread has not been started yet. + raise TrainBackendError( + "`get_next_results` has been called " + "before `start_training`. Please call " + "`start_training` before " + "`get_next_results`." + ) + + return result + + # Get next result from each worker. + futures = self.worker_group.execute_async(get_next) + results = self.get_with_failure_handling(futures) + + # Check if any worker returned None. + if any(r is None for r in results): + # Either all workers have results or none of them do. + if not all(r is None for r in results): + raise RuntimeError( + "Some workers returned results while " + "others didn't. Make sure that " + "`session.report()` are called the " + "same number of times on all workers." + ) + else: + # Return None if all results are None. + return None + + return results + + def pause_reporting(self): + """Disable workers from enqueuing results from ``session.report()``. + + Note: Already reported results may still be enqueued at this point, + and should be handled appropriately. + """ + + def pause_session_reporting(): + session = _get_session("pause_reporting") + return session.pause_reporting() + + futures = self.worker_group.execute_async(pause_session_reporting) + self.get_with_failure_handling(futures) + + def finish_training(self): + """Finish training and return final results. Propagate any exceptions. + + Blocks until training is finished on all workers. + + Assumes `start_training` has already been called. + + Returns: + A list of return values from calling ``train_func`` on each worker. + Each item corresponds to the return value from a single worker. + """ + + def end_training(): + session = _get_session("finish_training") + try: + # session.finish raises any Exceptions from training. + output = session.finish() + finally: + # Shutdown session even if session.finish() raises an + # Exception. + shutdown_session() + + return output + + futures = self.worker_group.execute_async(end_training) + results = self.get_with_failure_handling(futures) + return results + + def report_final_run_status( + self, + errored: bool = False, + failed_rank: Optional[int] = None, + stack_trace: Optional[str] = None, + ): + """Report the final train run status, error, and end time to TrainStateActor.""" + if self.state_tracking_enabled: + from ray.train._internal.state.schema import ( + MAX_ERROR_STACK_TRACE_LENGTH, + RunStatusEnum, + ) + + if errored: + run_status = RunStatusEnum.ERRORED + status_detail = "" + if failed_rank is not None: + status_detail += f"Rank {failed_rank} worker raised an error. \n" + if stack_trace is not None: + # Keep only the last part of the stack trace if it's too long. + status_detail += stack_trace[-MAX_ERROR_STACK_TRACE_LENGTH:] + else: + run_status = RunStatusEnum.FINISHED + status_detail = "" + + self.state_manager.end_train_run( + run_id=self._trial_info.run_id, + run_status=run_status, + status_detail=status_detail, + end_time_ms=int(time.time() * 1000), + ) + + def get_with_failure_handling(self, remote_values): + """Gets the remote values while handling for worker failures. + + This method should be called instead of ``ray.get()`` directly in + order to handle worker failures. + + If a worker failure is identified, backend specific failure handling + is executed and a ``TrainingWorkerError`` is raised. + + Args: + remote_values: List of object refs representing functions + that may fail in the middle of execution. For example, running + a Train training loop in multiple parallel actor calls. + Returns: + The resolved objects represented by the passed in ObjectRefs. + """ + success, exception = check_for_failure(remote_values) + if success: + return ray.get(remote_values) + else: + self._last_failure = exception + self._increment_failures() + logger.warning( + "Failure identified during training. Restarting all workers and " + "continuing training from latest checkpoint." + ) + self._restart() + raise TrainingWorkerError + + def shutdown(self, graceful_termination: bool = True): + """Shuts down the workers in the worker group. + + Args: + graceful_termination: If set to True, attempt to clean up the backend + before terminating the Ray actors. + + """ + if graceful_termination: + try: + self._backend.on_shutdown(self.worker_group, self._backend_config) + except RayActorError: + logger.warning( + "Graceful shutdown of backend failed. This is " + "expected if one of the workers has crashed." + ) + + if graceful_termination: + self.worker_group.shutdown() + else: + self.worker_group.shutdown(patience_s=0) + self.worker_group = InactiveWorkerGroup() + + if self._placement_group: + remove_placement_group(self._placement_group) + self._placement_group = None + + self.dataset_shards = None + + def is_started(self): + return not isinstance(self.worker_group, InactiveWorkerGroup) + + def _restart(self): + self.worker_group.shutdown() + if self._initialization_hook is not None: + initialization_hook = self._initialization_hook + else: + initialization_hook = None + if self._placement_group: + remove_placement_group(self._placement_group) + self._placement_group = None + self.start(initialization_hook=initialization_hook) + + def _increment_failures(self): + self._num_failures += 1 + if self._num_failures >= self._max_failures: + failure = self._last_failure + self._last_failure = None + if self._max_failures > 0: + exc = RuntimeError( + f"Training has failed after {self._num_failures} attempts." + ) + raise exc.with_traceback(None) from failure + else: + raise failure + + def get_worker_group(self): + return self.worker_group + + def _get_num_failures(self): + return self._num_failures + + +class InactiveWorkerGroupError(Exception): + """Raised when underlying worker group is inactive.""" + + +class InactiveWorkerGroup: + # TODO: fix inheritence. perhaps create WorkerGroupInterface. + + # Need to define getstate and setstate so that getattr does not screwup + # pickling. See https://stackoverflow.com/a/50888571/11249691 + def __getstate__(self): + return vars(self) + + def __setstate__(self, state): + vars(self).update(state) + + def __getattr__(self, name): + raise InactiveWorkerGroupError() + + def __len__(self): + raise InactiveWorkerGroupError() + + +def _get_session(method_name: str): + # Get the session for this worker. + session = get_session() + if not session: + # Session is not initialized yet. + raise TrainBackendError( + f"`{method_name}` has been called " + "before `start_training`. Please call " + "`start_training` before " + f"`{method_name}`." + ) + return session diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/checkpoint_manager.py b/venv/lib/python3.10/site-packages/ray/train/_internal/checkpoint_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..6a0eb55275246b5dcc7cff0c6fda58f2318b5076 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/checkpoint_manager.py @@ -0,0 +1,185 @@ +import logging +import numbers +from typing import Any, Callable, List, Optional, Tuple + +from ray._private.dict import flatten_dict +from ray.air._internal.util import is_nan +from ray.air.config import MAX +from ray.train import CheckpointConfig +from ray.train._internal.session import _TrainingResult +from ray.train._internal.storage import _delete_fs_path + +logger = logging.getLogger(__name__) + + +def _insert_into_sorted_list(list: List[Any], item: Any, key: Callable[[Any], Any]): + """Insert an item into a sorted list with a custom key function. + + Examples: + + >>> list = [] + >>> _insert_into_sorted_list(list, {"a": 1, "b": 0}, lambda x: x["a"]) + >>> list + [{'a': 1, 'b': 0}] + >>> _insert_into_sorted_list(list, {"a": 3, "b": 1}, lambda x: x["a"]) + >>> list + [{'a': 1, 'b': 0}, {'a': 3, 'b': 1}] + >>> _insert_into_sorted_list(list, {"a": 4, "b": 2}, lambda x: x["a"]) + >>> list + [{'a': 1, 'b': 0}, {'a': 3, 'b': 1}, {'a': 4, 'b': 2}] + >>> _insert_into_sorted_list(list, {"a": 1, "b": 3}, lambda x: x["a"]) + >>> list + [{'a': 1, 'b': 0}, {'a': 1, 'b': 3}, {'a': 3, 'b': 1}, {'a': 4, 'b': 2}] + """ + i = 0 + while i < len(list): + # Insert to the right of all duplicates. + if key(list[i]) > key(item): + break + i += 1 + list.insert(i, item) + + +class _CheckpointManager: + """Checkpoint manager that handles checkpoint book-keeping for a trial. + + The main purpose of this abstraction is to keep the top K checkpoints based on + recency/a user-provided metric. + + NOTE: This class interacts with `_TrainingResult` objects, which are + (checkpoint, metrics) pairs. This is to order checkpoints by metrics. + + Args: + checkpoint_config: Defines how many and which checkpoints to keep. + """ + + def __init__(self, checkpoint_config: Optional[CheckpointConfig]): + self._checkpoint_config = checkpoint_config or CheckpointConfig() + + # List of checkpoints ordered by ascending score. + self._checkpoint_results: List[_TrainingResult] = [] + + # The latest registered checkpoint. + # This should never be immediately deleted upon registration, + # even if it's not in the top K checkpoints, based on score. + self._latest_checkpoint_result: Optional[_TrainingResult] = None + + if ( + self._checkpoint_config.num_to_keep is not None + and self._checkpoint_config.num_to_keep <= 0 + ): + raise ValueError( + f"`num_to_keep` must >= 1, got: " + f"{self._checkpoint_config.num_to_keep}" + ) + + @property + def checkpoint_config(self): + return self._checkpoint_config + + def register_checkpoint(self, checkpoint_result: _TrainingResult): + """Register new checkpoint and add to bookkeeping. + + This method will register a new checkpoint and add it to the internal + bookkeeping logic. This means the checkpoint manager will decide if + this checkpoint should be kept, and if older or worse performing + checkpoints should be deleted. + + Args: + checkpoint: Tracked checkpoint object to add to bookkeeping. + """ + self._latest_checkpoint_result = checkpoint_result + + if self._checkpoint_config.checkpoint_score_attribute is not None: + # If we're ordering by a score, insert the checkpoint + # so that the list remains sorted. + _insert_into_sorted_list( + self._checkpoint_results, + checkpoint_result, + key=self._get_checkpoint_score, + ) + else: + # If no metric is provided, just append (ordering by time of registration). + self._checkpoint_results.append(checkpoint_result) + + if self._checkpoint_config.num_to_keep is not None: + # Delete the bottom (N - K) checkpoints + worst_results = set( + self._checkpoint_results[: -self._checkpoint_config.num_to_keep] + ) + # Except for the latest checkpoint. + results_to_delete = worst_results - {self._latest_checkpoint_result} + + # Update internal state before actually deleting them. + self._checkpoint_results = [ + checkpoint_result + for checkpoint_result in self._checkpoint_results + if checkpoint_result not in results_to_delete + ] + + for checkpoint_result in results_to_delete: + checkpoint = checkpoint_result.checkpoint + logger.debug("Deleting checkpoint: ", checkpoint) + _delete_fs_path(fs=checkpoint.filesystem, fs_path=checkpoint.path) + + def _get_checkpoint_score( + self, checkpoint: _TrainingResult + ) -> Tuple[bool, numbers.Number]: + """Get the score for a checkpoint, according to checkpoint config. + + If `mode="min"`, the metric is negated so that the lowest score is + treated as the best. + + Returns: + Tuple: A tuple of (not_is_nan: bool, score: numbers.Number). + This score orders: nan values < float("-inf") < valid numeric metrics + """ + checkpoint_score_attribute = self._checkpoint_config.checkpoint_score_attribute + if checkpoint_score_attribute: + flat_metrics = flatten_dict(checkpoint.metrics) + try: + checkpoint_result = flat_metrics[checkpoint_score_attribute] + except KeyError: + valid_keys = list(flat_metrics.keys()) + logger.error( + f"Result dict has no key: {checkpoint_score_attribute}. " + f"checkpoint_score_attr must be set to a key in the " + f"result dict. Valid keys are: {valid_keys}" + ) + checkpoint_result = float("-inf") + else: + checkpoint_result = float("-inf") + + checkpoint_score_order = self._checkpoint_config.checkpoint_score_order + order_factor = 1.0 if checkpoint_score_order == MAX else -1.0 + + checkpoint_score = order_factor * checkpoint_result + + if not isinstance(checkpoint_score, numbers.Number): + raise ValueError( + f"Unable to persist checkpoint for " + f"checkpoint_score_attribute: " + f"{checkpoint_score_attribute} with value " + f"{checkpoint_score}. " + f"This attribute must be numerical." + ) + + return ( + (not is_nan(checkpoint_score), checkpoint_score) + if not is_nan(checkpoint_score) + else (False, float("-inf")) + ) + + @property + def best_checkpoint_result(self) -> Optional[_TrainingResult]: + return self._checkpoint_results[-1] if self._checkpoint_results else None + + @property + def latest_checkpoint_result(self) -> Optional[_TrainingResult]: + return self._latest_checkpoint_result + + @property + def best_checkpoint_results(self) -> List[_TrainingResult]: + if self._checkpoint_config.num_to_keep is None: + return self._checkpoint_results + return self._checkpoint_results[-self._checkpoint_config.num_to_keep :] diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/data_config.py b/venv/lib/python3.10/site-packages/ray/train/_internal/data_config.py new file mode 100644 index 0000000000000000000000000000000000000000..da52a4b8fbeca0386123d44c537d3b579cadc799 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/data_config.py @@ -0,0 +1,146 @@ +import copy +from typing import Dict, List, Literal, Optional, Union + +import ray +from ray.actor import ActorHandle +from ray.data import DataIterator, Dataset, ExecutionOptions, NodeIdStr +from ray.data._internal.execution.interfaces.execution_options import ExecutionResources +from ray.util.annotations import DeveloperAPI, PublicAPI + + +@PublicAPI(stability="stable") +class DataConfig: + """Class responsible for configuring Train dataset preprocessing. + + For advanced use cases, this class can be subclassed and the `configure()` method + overriden for custom data preprocessing. + """ + + def __init__( + self, + datasets_to_split: Union[Literal["all"], List[str]] = "all", + execution_options: Optional[ExecutionOptions] = None, + enable_shard_locality: bool = True, + ): + """Construct a DataConfig. + + Args: + datasets_to_split: Specifies which datasets should be split among workers. + Can be set to "all" or a list of dataset names. Defaults to "all", + i.e. split all datasets. + execution_options: The execution options to pass to Ray Data. By default, + the options will be optimized for data ingest. When overriding this, + base your options off of `DataConfig.default_ingest_options()`. + enable_shard_locality: If true, when sharding the datasets across Train + workers, locality will be considered to minimize cross-node data transfer. + This is on by default. + """ + if isinstance(datasets_to_split, list) or datasets_to_split == "all": + self._datasets_to_split = datasets_to_split + else: + raise TypeError( + "`datasets_to_split` should be a 'all' or a list of strings of " + "dataset names. Received " + f"{type(datasets_to_split).__name__} with value {datasets_to_split}." + ) + + self._execution_options: ExecutionOptions = ( + execution_options or DataConfig.default_ingest_options() + ) + self._enable_shard_locality = enable_shard_locality + + self._num_train_cpus = 0.0 + self._num_train_gpus = 0.0 + + def set_train_total_resources(self, num_train_cpus: float, num_train_gpus: float): + """Set the total number of CPUs and GPUs used by training. + + If CPU or GPU resource limits are not set, they will be set to the + total cluster resources minus the resources used by training. + """ + # TODO: We may also include other resources besides CPU and GPU. + self._num_train_cpus = num_train_cpus + self._num_train_gpus = num_train_gpus + + @DeveloperAPI + def configure( + self, + datasets: Dict[str, Dataset], + world_size: int, + worker_handles: Optional[List[ActorHandle]], + worker_node_ids: Optional[List[NodeIdStr]], + **kwargs, + ) -> List[Dict[str, DataIterator]]: + """Configure how Train datasets should be assigned to workers. + + Args: + datasets: The datasets dict passed to Train by the user. + world_size: The number of Train workers in total. + worker_handles: The actor handles of the Train workers. + worker_node_ids: The node ids of the Train workers. + kwargs: Forwards compatibility placeholder. + + Returns: + A list of dataset splits for each worker. The size of the list must be + equal to `world_size`. Each element of the list contains the assigned + `DataIterator` instances by name for the worker. + """ + output = [{} for _ in range(world_size)] + + for dataset_name, dataset in datasets.items(): + if dataset.name is None: + dataset.set_name(dataset_name) + + if self._datasets_to_split == "all": + datasets_to_split = set(datasets.keys()) + else: + datasets_to_split = set(self._datasets_to_split) + + locality_hints = worker_node_ids if self._enable_shard_locality else None + for name, ds in datasets.items(): + execution_options = copy.deepcopy(self._execution_options) + + if execution_options.is_resource_limits_default(): + # If "resource_limits" is not overriden by the user, + # add training-reserved resources to Data's exclude_resources. + execution_options.exclude_resources = ( + execution_options.exclude_resources.add( + ExecutionResources( + cpu=self._num_train_cpus, gpu=self._num_train_gpus + ) + ) + ) + + ds = ds.copy(ds) + ds.context.execution_options = execution_options + + if name in datasets_to_split: + for i, split in enumerate( + ds.streaming_split( + world_size, equal=True, locality_hints=locality_hints + ) + ): + output[i][name] = split + else: + for i in range(world_size): + output[i][name] = ds.iterator() + + return output + + @staticmethod + def default_ingest_options() -> ExecutionOptions: + """The default Ray Data options used for data ingest. + + By default, configurations are carried over from what is already set + in DataContext. + """ + ctx = ray.data.DataContext.get_current() + return ExecutionOptions( + # TODO(hchen): Re-enable `locality_with_output` by default after fixing + # https://github.com/ray-project/ray/issues/40607 + locality_with_output=ctx.execution_options.locality_with_output, + resource_limits=ctx.execution_options.resource_limits, + exclude_resources=ctx.execution_options.exclude_resources, + preserve_order=ctx.execution_options.preserve_order, + verbose_progress=ctx.execution_options.verbose_progress, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/dl_predictor.py b/venv/lib/python3.10/site-packages/ray/train/_internal/dl_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..a159cfe7b9e141f1d25cfdf160285505efeb80b8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/dl_predictor.py @@ -0,0 +1,103 @@ +import abc +from typing import Dict, Optional, TypeVar, Union + +import numpy as np +import pandas as pd + +from ray.air.util.data_batch_conversion import ( + BatchFormat, + _convert_batch_type_to_pandas, + _convert_pandas_to_batch_type, +) +from ray.train.predictor import Predictor +from ray.util.annotations import DeveloperAPI + +TensorType = TypeVar("TensorType") +TensorDtype = TypeVar("TensorDtype") + + +class DLPredictor(Predictor): + @abc.abstractmethod + def _arrays_to_tensors( + self, + numpy_arrays: Union[np.ndarray, Dict[str, np.ndarray]], + dtype: Optional[Union[TensorDtype, Dict[str, TensorDtype]]], + ) -> Union[TensorType, Dict[str, TensorType]]: + """Converts a NumPy ndarray batch to the tensor type for the DL framework. + + Args: + numpy_array: The numpy array to convert to a tensor. + dtype: The tensor dtype to use when creating the DL tensor. + ndarray: A (dict of) NumPy ndarray(s) that we wish to convert to a (dict of) + tensor(s). + dtype: A (dict of) tensor dtype(s) to use when creating the DL tensor; if + None, the dtype will be inferred from the NumPy ndarray data. + + Returns: + A deep learning framework specific tensor. + """ + raise NotImplementedError + + @abc.abstractmethod + def _tensor_to_array(self, tensor: TensorType) -> np.ndarray: + """Converts tensor framework specific tensor to a numpy array. + + Args: + tensor: A framework specific tensor. + + Returns: + A numpy array representing the input tensor. + """ + + raise NotImplementedError + + @abc.abstractmethod + @DeveloperAPI + def call_model( + self, inputs: Union[TensorType, Dict[str, TensorType]] + ) -> Union[TensorType, Dict[str, TensorType]]: + """Inputs the tensor to the model for this Predictor and returns the result. + + Args: + inputs: The tensor to input to the model. + + Returns: + A tensor or dictionary of tensors containing the model output. + """ + raise NotImplementedError + + @classmethod + @DeveloperAPI + def preferred_batch_format(cls) -> BatchFormat: + return BatchFormat.NUMPY + + def _predict_pandas( + self, + data: pd.DataFrame, + dtype: Optional[Union[TensorDtype, Dict[str, TensorDtype]]], + ) -> pd.DataFrame: + numpy_input = _convert_pandas_to_batch_type( + data, + BatchFormat.NUMPY, + self._cast_tensor_columns, + ) + numpy_output = self._predict_numpy(numpy_input, dtype) + return _convert_batch_type_to_pandas(numpy_output) + + def _predict_numpy( + self, + data: Union[np.ndarray, Dict[str, np.ndarray]], + dtype: Optional[Union[TensorDtype, Dict[str, TensorDtype]]], + ) -> Union[np.ndarray, Dict[str, np.ndarray]]: + # Single column selection return numpy array so preprocessors can be + # reused in both training and prediction + if isinstance(data, dict) and len(data) == 1: + data = next(iter(data.values())) + model_input = self._arrays_to_tensors(data, dtype) + model_output = self.call_model(model_input) + # TODO (jiaodong): Investigate perf implication of this. + # Move DL Tensor to CPU and convert to numpy. + if isinstance(model_output, dict): + return {k: self._tensor_to_array(v) for k, v in model_output.items()} + else: + return {"predictions": self._tensor_to_array(model_output)} diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/framework_checkpoint.py b/venv/lib/python3.10/site-packages/ray/train/_internal/framework_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..424dc0dc84be78609384668e4f95fdd6ee7d3077 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/framework_checkpoint.py @@ -0,0 +1,45 @@ +from typing import Optional + +import ray.cloudpickle as ray_pickle +from ray._common.utils import binary_to_hex, hex_to_binary +from ray.data.preprocessor import Preprocessor +from ray.train._checkpoint import Checkpoint + +PREPROCESSOR_KEY = "preprocessor_pkl" + + +class FrameworkCheckpoint(Checkpoint): + """A checkpoint to preserve the functionality of legacy + framework-specific checkpoints. + + Example: + + >>> import tempfile + >>> checkpoint = FrameworkCheckpoint(tempfile.mkdtemp()) + >>> checkpoint.get_preprocessor() is None + True + >>> preprocessor = Preprocessor() + >>> preprocessor._attr = 1234 + >>> checkpoint.set_preprocessor(preprocessor) + >>> checkpoint.get_preprocessor()._attr + 1234 + """ + + def get_preprocessor(self) -> Optional[Preprocessor]: + """Return the preprocessor stored in the checkpoint. + + Returns: + The preprocessor stored in the checkpoint, or ``None`` if no + preprocessor was stored. + """ + metadata = self.get_metadata() + preprocessor_bytes = metadata.get(PREPROCESSOR_KEY) + if preprocessor_bytes is None: + return None + return ray_pickle.loads(hex_to_binary(preprocessor_bytes)) + + def set_preprocessor(self, preprocessor: Preprocessor): + """Store a preprocessor with the checkpoint.""" + self.update_metadata( + {PREPROCESSOR_KEY: binary_to_hex(ray_pickle.dumps(preprocessor))} + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/session.py b/venv/lib/python3.10/site-packages/ray/train/_internal/session.py new file mode 100644 index 0000000000000000000000000000000000000000..dec5b062ef4ff2fb36c775ef8a426b9cb1f53e47 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/session.py @@ -0,0 +1,1179 @@ +import functools +import logging +import os +import platform +import queue +import sys +import threading +import time +import warnings +from dataclasses import dataclass +from datetime import datetime +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Set, Type + +import ray +from ray.air._internal.util import RunnerThread, StartTraceback +from ray.air.constants import ( + _ERROR_FETCH_TIMEOUT, + _RESULT_FETCH_TIMEOUT, + SESSION_MISUSE_LOG_ONCE_KEY, + TIME_THIS_ITER_S, + TIMESTAMP, +) +from ray.data import Dataset +from ray.train import Checkpoint +from ray.train._internal.accelerator import Accelerator +from ray.train._internal.storage import StorageContext +from ray.train.constants import ( + CHECKPOINT_DIR_NAME, + DETAILED_AUTOFILLED_KEYS, + RAY_CHDIR_TO_TRIAL_DIR, + TIME_TOTAL_S, + WORKER_HOSTNAME, + WORKER_NODE_IP, + WORKER_PID, + _v2_migration_warnings_enabled, +) +from ray.train.error import SessionMisuseError +from ray.train.utils import _log_deprecation_warning +from ray.util.annotations import DeveloperAPI, PublicAPI +from ray.util.debug import log_once +from ray.util.placement_group import _valid_resource_shape +from ray.util.scheduling_strategies import ( + PlacementGroupSchedulingStrategy, + SchedulingStrategyT, +) + +if TYPE_CHECKING: + from ray.data import DataIterator + from ray.tune.execution.placement_groups import PlacementGroupFactory + + +logger = logging.getLogger(__name__) + + +@dataclass +class TrialInfo: + """The trial information to propagate to TrainSession.""" + + name: str + id: str + resources: Dict[str, float] + logdir: str + driver_ip: str + driver_node_id: str + experiment_name: Optional[str] = None + run_id: Optional[str] = None + + +class _FutureTrainingResult: + """A future that will be resolved to a `_TrainingResult`. + + This is needed for specific schedulers such as PBT that schedule saves. + + This wrapper should be removed after refactoring PBT to not schedule saves anymore. + """ + + def __init__(self, future: ray.ObjectRef): + self.future = future + + def resolve(self, block: bool = True) -> Optional["_TrainingResult"]: + """Resolve into ``_TrainingResult``. + + This will return None for function trainables if no checkpoint has been + saved before. + """ + if block: + timeout = None + else: + timeout = 1e-9 + try: + return ray.get(self.future, timeout=timeout) + except TimeoutError: + # Not ready, yet + pass + except Exception as exc: + logger.error(f"Error resolving result: {exc}") + + +class _TrainingResult: + """A (checkpoint, metrics) result reported by the user.""" + + def __init__(self, checkpoint: Optional[Checkpoint], metrics: Dict[str, Any]): + self.checkpoint = checkpoint + self.metrics = metrics + + def __repr__(self) -> str: + return f"TrainingResult(checkpoint={self.checkpoint}, metrics={self.metrics})" + + +# TODO(xwjiang): This needs a better name. +@DeveloperAPI +class _TrainSession: + """Holds information for training on each worker.""" + + def __init__( + self, + training_func: Callable, + world_rank: Optional[int], + local_rank: Optional[int], + node_rank: Optional[int], + local_world_size: Optional[int], + world_size: Optional[int], + trial_info: Optional[TrialInfo] = None, + dataset_shard: Optional[Dict[str, Dataset]] = None, + metadata: Dict[str, Any] = None, + checkpoint: Optional[Checkpoint] = None, + detailed_autofilled_metrics: bool = False, + storage: Optional[StorageContext] = None, + synchronous_result_reporting: bool = False, + ): + # `synchronous_result_reporting` refers to whether or not the + # training function is immediately unblocked to continue running + # after the main thread receives its result. + # Ex 1: For 2 Ray Train workers with synchronous_result_reporting=True, + # the worker that produces a result first will immediately will continue + # onto the next iteration. + # Ex 2: For a Tune function Trainable with `synchronous_result_reporting=False`, + # training will only continue with an explicit call to `session.get_next`. + # Synchronous reporting in example 2 is needed for Tune schedulers to + # be able to stop the execution of the training function at will, + # for advanced pausing schedulers (PBT, BOHB) and actor reuse. + self.synchronous_result_reporting = synchronous_result_reporting + + # Ray Train worker properties + # Note: These are set to None for Tune function Trainables. + self.dataset_shard = dataset_shard + self.metadata = metadata + + self.world_rank = world_rank + self.local_rank = local_rank + self.node_rank = node_rank + self.local_world_size = local_world_size + self.world_size = world_size + + assert storage + logger.debug(f"StorageContext on SESSION (rank={world_rank}):\n{storage}") + + # NOTE: `reset` will initialize many properties needed to start running the + # training_func as a thread. + self.reset( + training_func=training_func, + trial_info=trial_info, + storage=storage, + loaded_checkpoint=checkpoint, + ) + + # Autofilled metrics attributes. + self.detailed_autofilled_metrics = detailed_autofilled_metrics + self.last_report_time = time.time() + self.iteration = 0 + self.time_total = 0.0 + self.local_ip = self.get_current_ip() + + self.accelerator = None + self._state = {} + + def get_state(self, key: str) -> Any: + return self._state.get(key) + + def set_state(self, key: str, value: Any): + self._state[key] = value + + def get_current_ip(self): + self.local_ip = ray.util.get_node_ip_address() + return self.local_ip + + def start(self): + """Starts the training thread.""" + self.training_started = True + self.training_thread.start() + + def reset( + self, + training_func: Callable, + trial_info: TrialInfo, + storage: StorageContext, + loaded_checkpoint=None, + ): + # This lock is used to control the execution of the training thread. + self.continue_lock = threading.Semaphore(0) + + # This event is used to signal the training thread to stop. + self.stop_event = threading.Event() + + # Queue for sending results across threads. + self.result_queue = queue.Queue(1) + + # Queue for raising exceptions from runner thread to main thread. + # The error queue has a max size of one to prevent stacking error and force + # error reporting to block until finished. + self.error_queue = queue.Queue(1) + + # The Thread object that is running the training function. + self.training_thread = RunnerThread( + target=training_func, daemon=True, error_queue=self.error_queue + ) + + # Possibly override with new state + self.trial_info = trial_info + self.storage = storage + self.loaded_checkpoint = loaded_checkpoint + + # Reset state + self._state = {} + self.ignore_report = False + self.training_started = False + self._first_report = True + + # Change the working directory to a special trial folder. + # This is to ensure that all Ray Train workers have a common working directory. + os.makedirs(storage.trial_working_directory, exist_ok=True) + if bool(int(os.environ.get(RAY_CHDIR_TO_TRIAL_DIR, "1"))): + logger.debug( + f"Changing the working directory to: {storage.trial_working_directory}" + ) + os.chdir(storage.trial_working_directory) + + def pause_reporting(self): + """Ignore all future ``session.report()`` calls.""" + self.ignore_report = True + + def finish(self, timeout: Optional[float] = None) -> Optional[Any]: + """Finishes the training thread. + + Raises any Exception from training. + """ + # Set the stop event for the training thread to gracefully exit. + self.stop_event.set() + + # Release the lock so that training thread can process this event. + self.continue_lock.release() + + # Force a final (blocking) sync of artifacts in the trial path to storage. + self.storage.persist_artifacts(force=True) + + # Wait for training to finish. + # This will raise any errors that occur during training, including SystemError + # This returns the result of the training function. + output = None + if self.training_started: + output = self.training_thread.join(timeout=timeout) + + return output + + def get_next(self) -> Optional[_TrainingResult]: + """Gets the next ``_TrainingResult`` from the result queue. + + If the result queue is empty, then this function returns ``None``. + """ + if not self.training_started: + raise RuntimeError("Please call start before calling get_next.") + + if self.synchronous_result_reporting: + # There's no need to release the lock on the first report + # since `start` already started the training thread. + if not self._first_report: + # Release the lock to trigger training to continue, + # until the next call to report. + self.continue_lock.release() + self._first_report = False + + result = None + # While training is still ongoing, attempt to get the result. + while result is None and self.training_thread.is_alive(): + try: + result = self.result_queue.get( + block=True, timeout=_RESULT_FETCH_TIMEOUT + ) + except queue.Empty: + pass + + # If no result was found, then the runner must no longer be alive. + if result is None: + # Try one last time to fetch results in case results were + # reported in between the time of the last check and the + # termination of the thread runner. + try: + result = self.result_queue.get( + block=False, timeout=_RESULT_FETCH_TIMEOUT + ) + except queue.Empty: + pass + + # check if error occurred inside the thread runner. + if result is None: + # only raise an error from the runner if all results are consumed + self._report_thread_runner_error(block=True) + else: + if not self.error_queue.empty(): + logger.debug( + ( + "Runner error waiting to be raised in main thread. " + "Logging all available results first." + ) + ) + + if not self.synchronous_result_reporting: + # At this point, the training thread has reached + # the `train.report` and is blocked there. + # If performing asynchronous result reporting, + # release the lock to allow each worker to keep training + # immediately after the coordinator fetches their result. + self.continue_lock.release() + + # Return None if there are no more results to fetch. + return result + + def _auto_fill_metrics(self, result: dict) -> dict: + """Add autofilled metrics and update attributes.""" + current_time = time.time() + current_datetime = datetime.now() + if TIME_THIS_ITER_S in result: + time_this_iter = result[TIME_THIS_ITER_S] + else: + time_this_iter = current_time - self.last_report_time + self.iteration += 1 + self.time_total += time_this_iter + self.last_report_time = current_time + + auto_filled_metrics = { + TIMESTAMP: int(time.mktime(current_datetime.timetuple())), + TIME_TOTAL_S: self.time_total, + WORKER_PID: os.getpid(), + WORKER_HOSTNAME: platform.node(), + WORKER_NODE_IP: self.local_ip, + } + + if not self.detailed_autofilled_metrics: + auto_filled_metrics = { + k: v + for k, v in auto_filled_metrics.items() + if k not in DETAILED_AUTOFILLED_KEYS + } + + result = result.copy() + result.update(auto_filled_metrics) + return result + + def _auto_fill_checkpoint_metrics(self, result: dict) -> dict: + """Add autofilled metrics and update attributes.""" + current_datetime = datetime.now() + + auto_filled_metrics = { + TIMESTAMP: int(time.mktime(current_datetime.timetuple())) + } + result = result.copy() + result.update(auto_filled_metrics) + return result + + def _report_thread_runner_error(self, block=False): + try: + e = self.error_queue.get(block=block, timeout=_ERROR_FETCH_TIMEOUT) + raise StartTraceback from e + except queue.Empty: + pass + + def _report_training_result(self, training_result: _TrainingResult) -> None: + """Place a training result on the result queue for the main thread to process, + then block until the main thread signals that training should continue. + + NOTE: This is used internally to report results from Train to Tune + without persisting checkpoints to storage 2 times. + `report` is the public API that directly persists to storage, which + should only be called by user code. + """ + if training_result.checkpoint: + # NOTE: This populates `train.get_checkpoint` + self.loaded_checkpoint = training_result.checkpoint + + # Add result to a thread-safe queue. + self.result_queue.put(training_result, block=True) + + # Acquire lock to stop the training thread until main thread + # triggers resume. + self.continue_lock.acquire() + + # If the trial should be terminated, exit gracefully. + # NOTE: This is only really useful if `synchronous_result_reporting=True`. + # Otherwise, the lock is immediately released on reporting, and this + # check is skipped before the main thread decides to set the stop event. + if self.stop_event.is_set(): + self.stop_event.clear() + sys.exit(0) + + def report(self, metrics: Dict, checkpoint: Optional[Checkpoint] = None) -> None: + # Special case: early fail for Torch tensors + if "torch" in sys.modules: + from ray.air._internal.torch_utils import contains_tensor + + if contains_tensor(metrics): + raise ValueError( + "Passing objects containg Torch tensors as metrics " + "is not supported as it will throw an exception on " + "deserialization. You can either convert the tensors " + "to Python objects or report a `train.Checkpoint` " + "with `ray.train.report` to store your Torch objects." + ) + + if self.ignore_report: + return + + metrics = self._auto_fill_metrics(metrics) + + persisted_checkpoint = None + if checkpoint: + self.storage._update_checkpoint_index(metrics) + + # Persist the reported checkpoint files to storage. + persisted_checkpoint = self.storage.persist_current_checkpoint(checkpoint) + + metrics[CHECKPOINT_DIR_NAME] = self.storage.checkpoint_dir_name + else: + metrics[CHECKPOINT_DIR_NAME] = None + + # Persist trial artifacts to storage. + force_artifact_sync = ( + persisted_checkpoint + and self.storage.sync_config.sync_artifacts_on_checkpoint + ) + self.storage.persist_artifacts(force=force_artifact_sync) + + # Set additional user metadata from the Trainer. + if persisted_checkpoint and self.metadata: + user_metadata = persisted_checkpoint.get_metadata() + for k, v in self.metadata.items(): + # Update keys not already set by the user. This gives user-set keys + # precedence over keys set at the Trainer level. + if k not in user_metadata: + user_metadata[k] = v + persisted_checkpoint.set_metadata(user_metadata) + + result = _TrainingResult(checkpoint=persisted_checkpoint, metrics=metrics) + + self._report_training_result(result) + + @property + def experiment_name(self) -> str: + return self.trial_info.experiment_name + + @property + def trial_name(self) -> str: + return self.trial_info.name + + @property + def trial_id(self) -> str: + return self.trial_info.id + + @property + def run_id(self) -> str: + return self.trial_info.run_id + + @property + def trial_resources(self) -> "PlacementGroupFactory": + return self.trial_info.resources + + @property + def trial_dir(self) -> str: + return self.trial_info.logdir + + def get_dataset_shard( + self, + dataset_name: Optional[str] = None, + ) -> Optional["DataIterator"]: + shard = self.dataset_shard + if shard is None: + warnings.warn( + "No dataset passed in. Returning None. Make sure to " + "pass in a Dataset to Trainer.run to use this " + "function." + ) + elif isinstance(shard, dict): + if not dataset_name: + raise RuntimeError( + "Multiple datasets were passed into ``Trainer``, " + "but no ``dataset_name`` is passed into " + "``get_dataset_shard``. Please specify which " + "dataset shard to retrieve." + ) + return shard.get(dataset_name) + return shard + + +# Cache of resource dicts that have been checked by the launch hook already. +_checked_resources: Set[frozenset] = set() + +# Global _TrainSession object initialized by Ray Tune function trainables +# and Ray Train V1 workers. +_session: Optional[_TrainSession] = None + + +def _tune_task_and_actor_launch_hook( + fn, resources: Dict[str, float], strategy: Optional[SchedulingStrategyT] +): + """Launch hook to catch nested tasks that can't fit in the placement group. + + This gives users a nice warning in case they launch a nested task in a Tune trial + without reserving resources in the trial placement group to fit it. + """ + + # Already checked, skip for performance reasons. + key = frozenset({(k, v) for k, v in resources.items() if v > 0}) + if not key or key in _checked_resources: + return + + # No need to check if placement group is None. + if ( + not isinstance(strategy, PlacementGroupSchedulingStrategy) + or strategy.placement_group is None + ): + return + + # Check if the resource request is targeting the current placement group. + cur_pg = ray.util.get_current_placement_group() + if not cur_pg or strategy.placement_group.id != cur_pg.id: + return + + _checked_resources.add(key) + + # Check if the request can be fulfilled by the current placement group. + pgf = get_trial_resources() + + if pgf.head_bundle_is_empty: + available_bundles = cur_pg.bundle_specs[0:] + else: + available_bundles = cur_pg.bundle_specs[1:] + + # Check if the request can be fulfilled by the current placement group. + if _valid_resource_shape(resources, available_bundles): + return + + if fn.class_name: + submitted = "actor" + name = fn.module_name + "." + fn.class_name + "." + fn.function_name + else: + submitted = "task" + name = fn.module_name + "." + fn.function_name + + # Normalize the resource spec so it looks the same as the placement group bundle. + main_resources = cur_pg.bundle_specs[0] + resources = {k: float(v) for k, v in resources.items() if v > 0} + + raise RuntimeError( + f"No trial resources are available for launching the {submitted} `{name}`. " + "To resolve this, specify the Tune option:\n\n" + "> resources_per_trial=tune.PlacementGroupFactory(\n" + f"> [{main_resources}] + [{resources}] * N\n" + "> )\n\n" + f"Where `N` is the number of slots to reserve for trial {submitted}s. " + "If you are using a Ray training library, there might be a utility function " + "to set this automatically for you. For more information, refer to " + "https://docs.ray.io/en/latest/tune/tutorials/tune-resources.html" + ) + + +def init_session(*args, **kwargs) -> None: + global _session + if _session: + raise ValueError( + "A Train session is already in use. Do not call " + "`init_session()` manually." + ) + + # Setup hooks for generating placement group resource deadlock warnings. + from ray import actor, remote_function + + if "TUNE_DISABLE_RESOURCE_CHECKS" not in os.environ: + actor._actor_launch_hook = _tune_task_and_actor_launch_hook + remote_function._task_launch_hook = _tune_task_and_actor_launch_hook + + _session = _TrainSession(*args, **kwargs) + + +def get_session() -> Optional[_TrainSession]: + return _session + + +def shutdown_session(): + """Shuts down the initialized session.""" + global _session + _session = None + + +def _raise_accelerator_session_misuse(): + """Raises a SessionMisuseError because a utility function was used improperly.""" + raise SessionMisuseError( + "prepare/accelerate utility functions should be called inside a training " + "function executed by `Trainer.run`" + ) + + +def get_accelerator(default_accelerator_cls: Type[Accelerator]) -> Accelerator: + """The accelerator for this training session. + + If an accelerator has not been set, then this method will construct an + accelerator using the provided accelerator class. + + Raises: + SessionMisuseError: if the session is uninitialized. + """ + session = get_session() + if session is None: + _raise_accelerator_session_misuse() + if session.accelerator is None: + session.accelerator = default_accelerator_cls() + return session.accelerator + + +def set_accelerator(accelerator: Accelerator) -> None: + """Sets the accelerator for this training session. + + Args: + accelerator: The accelerator to use for training. + + Raises: + SessionMisuseError: if the session is unitialized. + RuntimeError: if the accelerator has already been set. + """ + session = get_session() + if session is None: + _raise_accelerator_session_misuse() + if session.accelerator is not None: + raise RuntimeError("Cannot change accelerator once set.") + session.accelerator = accelerator + + +def _warn_session_misuse(default_value: Any = None): + """Warns if fn is being used outside of session and returns ``default_value``.""" + + def inner(fn: Callable): + fn_name = fn.__name__ + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + session = get_session() + if not session: + if log_once(f"{SESSION_MISUSE_LOG_ONCE_KEY}-{fn_name}"): + warnings.warn( + f"`{fn_name}` is meant to only be " + "called inside a function that is executed by a Tuner" + f" or Trainer. Returning `{default_value}`." + ) + return default_value + return fn(*args, **kwargs) + + return wrapper + + return inner + + +@PublicAPI(stability="stable") +@_warn_session_misuse() +def report( + metrics: Dict, + *, + checkpoint: Optional[Checkpoint] = None, + checkpoint_dir_name: Optional[str] = None, +) -> None: + """Report metrics and optionally save a checkpoint. + + If a checkpoint is provided, it will be + :ref:`persisted to storage `. + + If this is called in multiple distributed training workers: + + - Only the metrics reported by the rank 0 worker will be tracked by Ray Train. + See :ref:`the metrics logging guide `. + - A checkpoint will be registered as long as one or more workers reports + checkpoint that is not None. + See the :ref:`checkpointing guide `. + - Checkpoints from multiple workers will be merged into one directory + in persistent storage. + See :ref:`the distributed checkpointing guide `. + + .. note:: + + Each invocation of this method will automatically increment the underlying + ``training_iteration`` number. The physical meaning of this "iteration" is + defined by user depending on how often they call ``report``. + It does not necessarily map to one epoch. + + .. warning:: + + All workers must call `ray.train.report` the same number of times + so that Ray Train can properly synchronize the training state across + workers. Otherwise, your training will hang. + + .. warning:: + + This method does NOT act as a barrier for distributed training workers. + Workers will upload their checkpoint, then continue training immediately. + If you need to synchronize workers, you can use a framework-native barrier + such as `torch.distributed.barrier()`. + + Example: + + .. testcode:: + + import tempfile + + from ray import train + from ray.train import Checkpoint + from ray.train.torch import TorchTrainer + + + def train_func(config): + start_epoch = 0 + checkpoint = train.get_checkpoint() + if checkpoint: + with checkpoint.as_directory() as checkpoint_dir: + # Load back training state + ... + + for epoch in range(start_epoch, config.get("num_epochs", 10)): + # Do training... + + metrics = {"loss": ...} + + with tempfile.TemporaryDirectory() as temp_checkpoint_dir: + # Save the checkpoint... + # torch.save(...) + + checkpoint = Checkpoint.from_directory(temp_checkpoint_dir) + + # Example: Only the rank 0 worker uploads the checkpoint. + if ray.train.get_context().get_world_rank() == 0: + train.report(metrics, checkpoint=checkpoint) + else: + train.report(metrics, checkpoint=None) + + trainer = TorchTrainer( + train_func, scaling_config=train.ScalingConfig(num_workers=2) + ) + + Args: + metrics: The metrics you want to report. + checkpoint: The optional checkpoint you want to report. + """ + if checkpoint_dir_name is not None: + logger.warning( + "`checkpoint_dir_name` is only supported in the new Ray Train " + "implementation, which can be enabled with `RAY_TRAIN_V2_ENABLED=1`. " + "This argument will be ignored." + ) + + # If we are running in a Tune function, switch to `ray.tune.report`. + from ray.tune.trainable.trainable_fn_utils import _in_tune_session + + if _in_tune_session(): + import ray.tune + + if _v2_migration_warnings_enabled(): + _log_deprecation_warning( + "`ray.train.report` should be switched to " + "`ray.tune.report` when running in a function " + "passed to Ray Tune. This will be an error in the future. " + "See this issue for more context: " + "https://github.com/ray-project/ray/issues/49454" + ) + return ray.tune.report(metrics, checkpoint=checkpoint) + + get_session().report(metrics, checkpoint=checkpoint) + + +@PublicAPI(stability="stable") +@_warn_session_misuse() +def get_checkpoint() -> Optional[Checkpoint]: + """Access the latest reported checkpoint to resume from if one exists. + + Example: + + .. testcode:: + + import tempfile + + from ray import train + from ray.train import Checkpoint + from ray.train.torch import TorchTrainer + + + def train_func(config): + start_epoch = 0 + checkpoint = train.get_checkpoint() + if checkpoint: + with checkpoint.as_directory() as checkpoint_dir: + # Load back training state + ... + + for epoch in range(start_epoch, config.get("num_epochs", 10)): + # Do training... + + metrics = {"loss": ...} + + with tempfile.TemporaryDirectory() as temp_checkpoint_dir: + # Save the checkpoint... + + checkpoint = Checkpoint.from_directory(temp_checkpoint_dir) + train.report(metrics, checkpoint=checkpoint) + + trainer = TorchTrainer( + train_func, scaling_config=train.ScalingConfig(num_workers=2) + ) + + Returns: + Checkpoint object if the session is currently being resumed. + Otherwise, return None. + """ + # If we are running in a Tune function, switch to `ray.tune.get_checkpoint`. + from ray.tune.trainable.trainable_fn_utils import _in_tune_session + + if _in_tune_session(): + import ray.tune + + if _v2_migration_warnings_enabled(): + _log_deprecation_warning( + "`ray.train.get_checkpoint` should be switched to " + "`ray.tune.get_checkpoint` when running in a function " + "passed to Ray Tune. This will be an error in the future. " + "See this issue for more context: " + "https://github.com/ray-project/ray/issues/49454" + ) + return ray.tune.get_checkpoint() + + return get_session().loaded_checkpoint + + +@PublicAPI(stability="beta") +@_warn_session_misuse() +def get_metadata() -> Dict[str, Any]: + """User metadata dict passed to the Trainer constructor.""" + return get_session().metadata + + +@PublicAPI(stability="beta") +@_warn_session_misuse() +def get_experiment_name() -> str: + """Experiment name for the corresponding trial.""" + return get_session().experiment_name + + +@PublicAPI(stability="beta") +@_warn_session_misuse() +def get_trial_name() -> str: + """Trial name for the corresponding trial.""" + return get_session().trial_name + + +@PublicAPI(stability="beta") +@_warn_session_misuse() +def get_trial_id() -> str: + """Trial id for the corresponding trial.""" + return get_session().trial_id + + +@PublicAPI(stability="alpha") +@_warn_session_misuse() +def get_run_id() -> str: + """Unique Train Run id for the corresponding trial.""" + return get_session().run_id + + +@PublicAPI(stability="beta") +@_warn_session_misuse() +def get_trial_resources() -> "PlacementGroupFactory": + """Trial resources for the corresponding trial.""" + return get_session().trial_resources + + +@PublicAPI(stability="beta") +@_warn_session_misuse() +def get_trial_dir() -> str: + """Log directory corresponding to the trial directory for a Tune session. + If calling from a Train session, this will give the trial directory of its parent + Tune session. + + .. testcode:: + + import ray.tune + + def train_func(config): + print(ray.tune.get_context().get_trial_dir()) + + tuner = ray.tune.Tuner(train_func) + tuner.fit() + + .. testoutput:: + :options: +MOCK + + /Users/root/ray_results/train_func_2023-07-19_15-01-37/train_func_d620c_00000_0_2023-07-19_15-01-40 + """ + return get_session().trial_dir + + +@PublicAPI(stability="beta") +@_warn_session_misuse(default_value=1) +def get_world_size() -> int: + """Get the current world size (i.e. total number of workers) for this run. + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.tensorflow import TensorflowTrainer + + NUM_WORKERS = 2 + + def train_loop_per_worker(config): + assert train.get_context().get_world_size() == NUM_WORKERS + + train_dataset = ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv") + trainer = TensorflowTrainer( + train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=NUM_WORKERS), + datasets={"train": train_dataset} + ) + trainer.fit() + + .. testoutput:: + :hide: + + ... + """ + session = get_session() + if not hasattr(session, "world_size"): + raise RuntimeError( + "`get_world_size` can only be called for TrainSession! " + "Make sure you only use that in `train_loop_per_worker` function" + "that is passed into `DataParallelTrainer`." + ) + return session.world_size + + +@PublicAPI(stability="beta") +@_warn_session_misuse(default_value=0) +def get_world_rank() -> int: + """Get the world rank of this worker. + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.tensorflow import TensorflowTrainer + + def train_loop_per_worker(config): + if train.get_context().get_world_rank() == 0: + print("Worker 0") + + train_dataset = ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv") + trainer = TensorflowTrainer( + train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=2), + datasets={"train": train_dataset} + ) + trainer.fit() + + .. testoutput:: + :hide: + + ... + """ + session = get_session() + if not hasattr(session, "world_rank"): + raise RuntimeError( + "`get_world_rank` can only be called for TrainSession! " + "Make sure you only use that in `train_loop_per_worker` function" + "that is passed into `DataParallelTrainer`." + ) + return session.world_rank + + +@PublicAPI(stability="beta") +@_warn_session_misuse(default_value=0) +def get_local_rank() -> int: + """Get the local rank of this worker (rank of the worker on its node). + + .. testcode:: + + import torch + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.torch import TorchTrainer + + def train_loop_per_worker(config): + if torch.cuda.is_available(): + torch.cuda.set_device(train.get_context().get_local_rank()) + ... + + train_dataset = ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv") + trainer = TorchTrainer( + train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=2, use_gpu=True), + datasets={"train": train_dataset} + ) + trainer.fit() + + .. testoutput:: + :hide: + + ... + """ + session = get_session() + if not hasattr(session, "local_rank"): + raise RuntimeError( + "`get_local_rank` can only be called for TrainSession! " + "Make sure you only use that in `train_loop_per_worker` function" + "that is passed into `DataParallelTrainer`." + ) + return session.local_rank + + +@PublicAPI(stability="beta") +@_warn_session_misuse(default_value=0) +def get_local_world_size() -> int: + """Get the local world size of this node (i.e. number of workers on this node). + + Example: + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.torch import TorchTrainer + + def train_loop_per_worker(): + print(train.get_context().get_local_world_size()) + + train_dataset = ray.data.from_items( + [{"x": x, "y": x + 1} for x in range(32)]) + trainer = TorchTrainer(train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=1), + datasets={"train": train_dataset}) + trainer.fit() + + .. testoutput:: + :hide: + + ... + """ + session = get_session() + if not hasattr(session, "local_world_size"): + raise RuntimeError( + "`get_local_world_size` can only be called for TrainSession! " + "Make sure you only use that in `train_loop_per_worker` function" + "that is passed into `DataParallelTrainer`." + ) + return session.local_world_size + + +@PublicAPI(stability="beta") +@_warn_session_misuse(default_value=0) +def get_node_rank() -> int: + """Get the rank of this node. + + Example: + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.torch import TorchTrainer + + def train_loop_per_worker(): + print(train.get_context().get_node_rank()) + + train_dataset = ray.data.from_items( + [{"x": x, "y": x + 1} for x in range(32)]) + trainer = TorchTrainer(train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=1), + datasets={"train": train_dataset}) + trainer.fit() + + .. testoutput:: + :hide: + + ... + """ + session = get_session() + if not hasattr(session, "node_rank"): + raise RuntimeError( + "`get_node_rank` can only be called for TrainSession! " + "Make sure you only use that in `train_loop_per_worker` function" + "that is passed into `DataParallelTrainer`." + ) + return session.node_rank + + +@PublicAPI(stability="stable") +@_warn_session_misuse() +def get_dataset_shard( + dataset_name: Optional[str] = None, +) -> Optional["DataIterator"]: + """Returns the :class:`ray.data.DataIterator` shard for this worker. + + Call :meth:`~ray.data.DataIterator.iter_torch_batches` or + :meth:`~ray.data.DataIterator.to_tf` on this shard to convert it to the + appropriate framework-specific data type. + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.torch import TorchTrainer + + def train_loop_per_worker(config): + ... + for epoch in range(2): + # Trainer will automatically handle sharding. + data_shard = train.get_dataset_shard("train") + for batch in data_shard.iter_torch_batches(): + ... + + train_dataset = ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv") + trainer = TorchTrainer( + train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=2), + datasets={"train": train_dataset} + ) + trainer.fit() + + .. testoutput:: + :hide: + + ... + + Args: + dataset_name: If a Dictionary of Datasets was passed to ``Trainer``, then + specifies which dataset shard to return. + + Returns: + The ``DataIterator`` shard to use for this worker. + If no dataset is passed into Trainer, then return None. + """ + session = get_session() + if not hasattr(session, "get_dataset_shard"): + raise RuntimeError( + "`get_dataset_shard` can only be called for TrainSession! " + "Make sure you only use that in `train_loop_per_worker` function" + "that is passed into `DataParallelTrainer`." + ) + return session.get_dataset_shard(dataset_name) + + +@DeveloperAPI +@_warn_session_misuse() +def get_storage() -> StorageContext: + """Returns the :class:`~ray.train._internal.storage.StorageContext` storage + context which gives advanced access to the filesystem and paths + configured through `RunConfig`. + + NOTE: This is a developer API, and the `StorageContext` interface may change + without notice between minor versions. + """ + return get_session().storage diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/state/__init__.py b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..604a4fa3932930fa1d728ceb6e9bdd4619449bf6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__init__.py @@ -0,0 +1,14 @@ +from ray.train._internal.state.state_manager import TrainRunStateManager + +try: + import pydantic # noqa: F401 +except ImportError: + raise ModuleNotFoundError( + "pydantic isn't installed." + "To install pydantic, please run 'pip install pydantic'" + ) + + +__all__ = [ + "TrainRunStateManager", +] diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..306202db445201f5c59d580c4c3021efdb8a45ed Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/export.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/export.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28fb63183e6527e2905271dc239310a141db8ddc Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/export.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/schema.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/schema.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7eb72fa0d0c3d4b9ca0ba1bf4724041515d0b6a9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/schema.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/state_actor.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/state_actor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79ef4958487210a85f251aeb6ea0279a4eceb48c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/state_actor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/state_manager.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/state_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb9690f586c7ce46215d3654b39a1f404e3d55ea Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/_internal/state/__pycache__/state_manager.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/state/export.py b/venv/lib/python3.10/site-packages/ray/train/_internal/state/export.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae562dd9f814af464c7a33681b047332277cc64 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/state/export.py @@ -0,0 +1,105 @@ +from typing import Optional + +from ray.core.generated.export_train_state_pb2 import ( + ExportTrainRunAttemptEventData as ProtoTrainRunAttempt, + ExportTrainRunEventData as ProtoTrainRun, +) +from ray.train._internal.state.schema import ( + ActorStatusEnum, + RunStatusEnum, + TrainRunInfo, + TrainWorkerInfo, +) + +TRAIN_SCHEMA_VERSION = 1 +RAY_TRAIN_VERSION = 1 + +# Status mapping dictionaries +_ACTOR_STATUS_MAP = { + ActorStatusEnum.ALIVE: ProtoTrainRunAttempt.ActorStatus.ALIVE, + ActorStatusEnum.DEAD: ProtoTrainRunAttempt.ActorStatus.DEAD, +} + +_RUN_ATTEMPT_STATUS_MAP = { + RunStatusEnum.STARTED: ProtoTrainRunAttempt.RunAttemptStatus.PENDING, + RunStatusEnum.RUNNING: ProtoTrainRunAttempt.RunAttemptStatus.RUNNING, + RunStatusEnum.FINISHED: ProtoTrainRunAttempt.RunAttemptStatus.FINISHED, + RunStatusEnum.ERRORED: ProtoTrainRunAttempt.RunAttemptStatus.ERRORED, + RunStatusEnum.ABORTED: ProtoTrainRunAttempt.RunAttemptStatus.ABORTED, +} + +_RUN_STATUS_MAP = { + RunStatusEnum.STARTED: ProtoTrainRun.RunStatus.INITIALIZING, + RunStatusEnum.RUNNING: ProtoTrainRun.RunStatus.RUNNING, + RunStatusEnum.FINISHED: ProtoTrainRun.RunStatus.FINISHED, + RunStatusEnum.ERRORED: ProtoTrainRun.RunStatus.ERRORED, + RunStatusEnum.ABORTED: ProtoTrainRun.RunStatus.ABORTED, +} + + +def _ms_to_ns(ms: Optional[int]) -> Optional[int]: + if ms is None: + return None + return ms * 1000000 + + +# Helper conversion functions +def _to_proto_resources(resources: dict) -> ProtoTrainRunAttempt.TrainResources: + """Convert resources dictionary to protobuf TrainResources.""" + return ProtoTrainRunAttempt.TrainResources(resources=resources) + + +def _to_proto_worker(worker: TrainWorkerInfo) -> ProtoTrainRunAttempt.TrainWorker: + """Convert TrainWorker to protobuf format.""" + proto_worker = ProtoTrainRunAttempt.TrainWorker( + world_rank=worker.world_rank, + local_rank=worker.local_rank, + node_rank=worker.node_rank, + actor_id=bytes.fromhex(worker.actor_id), + node_id=bytes.fromhex(worker.node_id), + node_ip=worker.node_ip, + pid=worker.pid, + gpu_ids=worker.gpu_ids, + status=_ACTOR_STATUS_MAP[worker.status], + resources=_to_proto_resources(worker.resources), + ) + + return proto_worker + + +# Main conversion functions +def train_run_info_to_proto_run(run_info: TrainRunInfo) -> ProtoTrainRun: + """Convert TrainRunInfo to TrainRun protobuf format.""" + proto_run = ProtoTrainRun( + schema_version=TRAIN_SCHEMA_VERSION, + ray_train_version=RAY_TRAIN_VERSION, + id=run_info.id, + name=run_info.name, + job_id=bytes.fromhex(run_info.job_id), + controller_actor_id=bytes.fromhex(run_info.controller_actor_id), + status=_RUN_STATUS_MAP[run_info.run_status], + status_detail=run_info.status_detail, + start_time_ns=_ms_to_ns(run_info.start_time_ms), + end_time_ns=_ms_to_ns(run_info.end_time_ms), + ) + + return proto_run + + +def train_run_info_to_proto_attempt(run_info: TrainRunInfo) -> ProtoTrainRunAttempt: + """Convert TrainRunInfo to TrainRunAttempt protobuf format.""" + + proto_attempt = ProtoTrainRunAttempt( + schema_version=TRAIN_SCHEMA_VERSION, + ray_train_version=RAY_TRAIN_VERSION, + run_id=run_info.id, + attempt_id=run_info.id, # Same as run_id + status=_RUN_ATTEMPT_STATUS_MAP[run_info.run_status], + status_detail=run_info.status_detail, + start_time_ns=_ms_to_ns(run_info.start_time_ms), + end_time_ns=_ms_to_ns(run_info.end_time_ms), + resources=[_to_proto_resources(r) for r in run_info.resources], + workers=[_to_proto_worker(worker) for worker in run_info.workers], + ) + + return proto_attempt diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/state/schema.py b/venv/lib/python3.10/site-packages/ray/train/_internal/state/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..87f9f51a6c3d1bfaa8b5d333888ad971a9ce3c7f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/state/schema.py @@ -0,0 +1,164 @@ +from enum import Enum +from typing import Dict, List, Optional + +from ray._common.pydantic_compat import BaseModel, Field +from ray.dashboard.modules.job.pydantic_models import JobDetails +from ray.util.annotations import DeveloperAPI + +MAX_ERROR_STACK_TRACE_LENGTH = 50000 + + +@DeveloperAPI +class RunStatusEnum(str, Enum): + """Enumeration for the status of a train run.""" + + # (Deprecated) Replaced by RUNNING. + # The train run has started + STARTED = "STARTED" + # The train run is running + RUNNING = "RUNNING" + # The train run was terminated as expected + FINISHED = "FINISHED" + # The train run was terminated early due to errors in the training function + ERRORED = "ERRORED" + # The train run was terminated early due to system errors or controller errors + ABORTED = "ABORTED" + + +@DeveloperAPI +class ActorStatusEnum(str, Enum): + DEAD = "DEAD" + ALIVE = "ALIVE" + + +@DeveloperAPI +class TrainWorkerInfo(BaseModel): + """Metadata of a Ray Train worker.""" + + actor_id: str = Field(description="Actor ID of the worker.") + world_rank: int = Field(description="World rank of the worker.") + local_rank: int = Field(description="Local rank of the worker.") + node_rank: int = Field(description="Node rank of the worker.") + node_id: str = Field(description="ID of the node that the worker is running on.") + node_ip: str = Field( + description="IP address of the node that the worker is running on." + ) + pid: int = Field(description="Process ID of the worker.") + gpu_ids: List[int] = Field( + description="A list of GPU ids allocated to that worker." + ) + status: ActorStatusEnum = Field( + description="The status of the train worker actor. It can be ALIVE or DEAD." + ) + resources: Dict[str, float] = Field( + description="The resources allocated to the worker." + ) + + +@DeveloperAPI +class MemoryInfo(BaseModel): + rss: int + vms: int + pfaults: Optional[int] + pageins: Optional[int] + + +@DeveloperAPI +class ProcessStats(BaseModel): + cpuPercent: float + # total memory, free memory, memory used ratio + mem: Optional[List[int]] + memoryInfo: MemoryInfo + + +class ProcessGPUUsage(BaseModel): + # This gpu usage stats from a process + pid: int + gpuMemoryUsage: int + + +@DeveloperAPI +class GPUStats(BaseModel): + uuid: str + index: int + name: str + utilizationGpu: Optional[float] + memoryUsed: float + memoryTotal: float + processInfo: ProcessGPUUsage + + +@DeveloperAPI +class TrainWorkerInfoWithDetails(TrainWorkerInfo): + """Metadata of a Ray Train worker.""" + + processStats: Optional[ProcessStats] = Field( + None, description="Process stats of the worker." + ) + gpus: List[GPUStats] = Field( + default_factory=list, + description=( + "GPU stats of the worker. " + "Only returns GPUs that are attached to the worker process." + ), + ) + + +@DeveloperAPI +class TrainDatasetInfo(BaseModel): + name: str = Field( + description="The key of the dataset dict specified in Ray Train Trainer." + ) + dataset_uuid: str = Field(description="The uuid of the dataset.") + dataset_name: Optional[str] = Field(description="The name of the dataset.") + + +@DeveloperAPI +class TrainRunInfo(BaseModel): + """Metadata for a Ray Train run and information about its workers.""" + + name: str = Field(description="The name of the Train run.") + id: str = Field(description="The unique identifier for each Train run.") + job_id: str = Field(description="The Ray Job ID.") + controller_actor_id: str = Field(description="Actor Id of the Train controller.") + workers: List[TrainWorkerInfo] = Field( + description="A List of Train workers sorted by global ranks." + ) + datasets: List[TrainDatasetInfo] = Field( + description="A List of dataset info for this Train run." + ) + run_status: RunStatusEnum = Field( + description="The current status of the train run. It can be one of the " + "following: RUNNING, FINISHED, ERRORED, or ABORTED." + ) + status_detail: str = Field( + description="Detailed information about the current run status, " + "such as error messages." + ) + start_time_ms: int = Field( + description="The UNIX timestamp of the start time of this Train run." + ) + end_time_ms: Optional[int] = Field( + description="The UNIX timestamp of the end time of this Train run. " + "If null, the Train run has not ended yet." + ) + resources: List[Dict[str, float]] = Field( + description="The resources allocated to the worker." + ) + + +@DeveloperAPI +class TrainRunInfoWithDetails(TrainRunInfo): + """Metadata for a Ray Train run and information about its workers.""" + + workers: List[TrainWorkerInfoWithDetails] = Field( + description="A List of Train workers sorted by global ranks." + ) + job_details: Optional[JobDetails] = Field( + None, description="Details of the job that started this Train run." + ) + + +@DeveloperAPI +class TrainRunsResponse(BaseModel): + train_runs: List[TrainRunInfoWithDetails] diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/state/state_actor.py b/venv/lib/python3.10/site-packages/ray/train/_internal/state/state_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..4001d31129c1eba07a8b38d5b485db0f75647e7f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/state/state_actor.py @@ -0,0 +1,152 @@ +import logging +import os +import threading +from typing import Dict, Optional + +import ray +from ray._private.event.export_event_logger import ( + EventLogType, + check_export_api_enabled, + get_export_event_logger, +) +from ray.actor import ActorHandle +from ray.train._internal.state.schema import TrainRunInfo + +logger = logging.getLogger(__name__) + + +@ray.remote(num_cpus=0) +class TrainStateActor: + def __init__(self): + self._run_infos: Dict[str, TrainRunInfo] = {} + + ( + self._export_logger, + self._is_train_run_export_api_enabled, + self._is_train_run_attempt_export_api_enabled, + ) = self._init_export_logger() + + def register_train_run(self, run_info: TrainRunInfo) -> None: + # Register a new train run. + self._run_infos[run_info.id] = run_info + + self._maybe_export_train_run(run_info) + self._maybe_export_train_run_attempt(run_info) + + def get_train_run(self, run_id: str) -> Optional[TrainRunInfo]: + # Retrieve a registered run with its id + return self._run_infos.get(run_id, None) + + def get_all_train_runs(self) -> Dict[str, TrainRunInfo]: + # Retrieve all registered train runs + return self._run_infos + + # ============================ + # Export API + # ============================ + + def is_export_api_enabled(self) -> bool: + return self._export_logger is not None + + def _init_export_logger(self) -> tuple[Optional[logging.Logger], bool, bool]: + """Initialize the export logger and check if the export API is enabled. + + Returns: + A tuple containing: + - The export logger (or None if export API is not enabled). + - A boolean indicating if the export API is enabled for train runs. + - A boolean indicating if the export API is enabled for train run attempts. + """ + # Proto schemas should be imported within the scope of TrainStateActor to + # prevent serialization errors. + from ray.core.generated.export_event_pb2 import ExportEvent + + is_train_run_export_api_enabled = check_export_api_enabled( + ExportEvent.SourceType.EXPORT_TRAIN_RUN + ) + is_train_run_attempt_export_api_enabled = check_export_api_enabled( + ExportEvent.SourceType.EXPORT_TRAIN_RUN_ATTEMPT + ) + export_api_enabled = ( + is_train_run_export_api_enabled or is_train_run_attempt_export_api_enabled + ) + + if not export_api_enabled: + return None, False, False + + log_directory = os.path.join( + ray._private.worker._global_node.get_session_dir_path(), "logs" + ) + logger = None + try: + logger = get_export_event_logger( + EventLogType.TRAIN_STATE, + log_directory, + ) + except Exception: + logger.exception( + "Unable to initialize the export event logger, so no Train export " + "events will be written." + ) + + if logger is None: + return None, False, False + + return ( + logger, + is_train_run_export_api_enabled, + is_train_run_attempt_export_api_enabled, + ) + + def _maybe_export_train_run(self, run_info: TrainRunInfo) -> None: + if not self._is_train_run_export_api_enabled: + return + + from ray.train._internal.state.export import train_run_info_to_proto_run + + run_proto = train_run_info_to_proto_run(run_info) + self._export_logger.send_event(run_proto) + + def _maybe_export_train_run_attempt(self, run_info: TrainRunInfo) -> None: + if not self._is_train_run_attempt_export_api_enabled: + return + + from ray.train._internal.state.export import train_run_info_to_proto_attempt + + run_attempt_proto = train_run_info_to_proto_attempt(run_info) + self._export_logger.send_event(run_attempt_proto) + + +TRAIN_STATE_ACTOR_NAME = "train_state_actor" +TRAIN_STATE_ACTOR_NAMESPACE = "_train_state_actor" + +_state_actor_lock: threading.RLock = threading.RLock() + + +def get_or_create_state_actor() -> ActorHandle: + """Get or create a `TrainStateActor` on the head node.""" + with _state_actor_lock: + state_actor = TrainStateActor.options( + name=TRAIN_STATE_ACTOR_NAME, + namespace=TRAIN_STATE_ACTOR_NAMESPACE, + get_if_exists=True, + lifetime="detached", + resources={"node:__internal_head__": 0.001}, + # Escape from the parent's placement group + scheduling_strategy="DEFAULT", + ).remote() + + # Ensure the state actor is ready + ray.get(state_actor.__ray_ready__.remote()) + return state_actor + + +def get_state_actor() -> Optional[ActorHandle]: + """Get the `TrainStateActor` if exists, otherwise return None.""" + try: + return ray.get_actor( + name=TRAIN_STATE_ACTOR_NAME, + namespace=TRAIN_STATE_ACTOR_NAMESPACE, + ) + except ValueError: + return None diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/state/state_manager.py b/venv/lib/python3.10/site-packages/ray/train/_internal/state/state_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..5684606c601ac5df77ce40e7a22d6ce86ee86998 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/state/state_manager.py @@ -0,0 +1,130 @@ +import logging +import os +from collections import defaultdict +from typing import Any, Dict, List + +import ray +from ray.data import Dataset +from ray.train._internal.state.schema import ( + ActorStatusEnum, + RunStatusEnum, + TrainDatasetInfo, + TrainRunInfo, + TrainWorkerInfo, +) +from ray.train._internal.utils import check_for_failure +from ray.train._internal.worker_group import WorkerGroup + +logger = logging.getLogger(__name__) + + +class TrainRunStateManager: + """A class that aggregates and reports train run info to TrainStateActor. + + This manager class is created on the train controller layer for each run. + """ + + def __init__(self, state_actor) -> None: + self.state_actor = state_actor + self.train_run_info_dict = defaultdict(dict) + + def register_train_run( + self, + run_id: str, + job_id: str, + run_name: str, + run_status: str, + controller_actor_id: str, + datasets: Dict[str, Dataset], + worker_group: WorkerGroup, + start_time_ms: float, + resources: List[Dict[str, float]], + status_detail: str = "", + ) -> None: + """Collect Train Run Info and report to StateActor.""" + + if not self.state_actor: + logger.warning( + "Unable to register train run since `TrainStateActor` is not started." + ) + return + + def collect_train_worker_info(): + train_context = ray.train.get_context() + core_context = ray.runtime_context.get_runtime_context() + return TrainWorkerInfo( + world_rank=train_context.get_world_rank(), + local_rank=train_context.get_local_rank(), + node_rank=train_context.get_node_rank(), + actor_id=core_context.get_actor_id(), + node_id=core_context.get_node_id(), + node_ip=ray.util.get_node_ip_address(), + gpu_ids=ray.get_gpu_ids(), + pid=os.getpid(), + resources=resources[0], + status=ActorStatusEnum.ALIVE, + ) + + futures = [ + worker_group.execute_single_async(index, collect_train_worker_info) + for index in range(len(worker_group)) + ] + success, exception = check_for_failure(futures) + + if not success: + logger.error( + "Failed to collect run information from the Ray Train " + f"workers:\n{exception}" + ) + return + + worker_info_list = ray.get(futures) + worker_info_list = sorted(worker_info_list, key=lambda info: info.world_rank) + + dataset_info_list = [ + TrainDatasetInfo( + name=ds_name, + dataset_name=ds._plan._dataset_name, + dataset_uuid=ds._plan._dataset_uuid, + ) + for ds_name, ds in datasets.items() + ] + + updates = dict( + id=run_id, + job_id=job_id, + name=run_name, + controller_actor_id=controller_actor_id, + workers=worker_info_list, + datasets=dataset_info_list, + start_time_ms=start_time_ms, + run_status=run_status, + status_detail=status_detail, + resources=resources, + ) + + # Clear the cached info to avoid registering the same run twice + self.train_run_info_dict[run_id] = {} + self._update_train_run_info(run_id, updates) + + def end_train_run( + self, + run_id: str, + run_status: RunStatusEnum, + status_detail: str, + end_time_ms: int, + ): + """Update the train run status when the training is finished.""" + updates = dict( + run_status=run_status, + status_detail=status_detail, + end_time_ms=end_time_ms, + ) + self._update_train_run_info(run_id, updates) + + def _update_train_run_info(self, run_id: str, updates: Dict[str, Any]) -> None: + """Update specific fields of a registered TrainRunInfo instance.""" + if run_id in self.train_run_info_dict: + self.train_run_info_dict[run_id].update(updates) + train_run_info = TrainRunInfo(**self.train_run_info_dict[run_id]) + ray.get(self.state_actor.register_train_run.remote(train_run_info)) diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/storage.py b/venv/lib/python3.10/site-packages/ray/train/_internal/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..35332963f46bb2918ac85fedee27708d6ca88793 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/storage.py @@ -0,0 +1,724 @@ +# Try import ray[train] core requirements (defined in setup.py) +# isort: off +try: + import fsspec # noqa + from fsspec.implementations.local import LocalFileSystem + +except (ImportError, ModuleNotFoundError) as e: + raise RuntimeError( + "fsspec is a required dependency of Ray Train and Ray Tune. " + "Please install with: `pip install fsspec`" + ) from e + +try: + import pyarrow + import pyarrow.fs + +except (ImportError, ModuleNotFoundError) as e: + raise RuntimeError( + "pyarrow is a required dependency of Ray Train and Ray Tune. " + "Please install with: `pip install pyarrow`" + ) from e + +try: + # check if Arrow has S3 support + from pyarrow.fs import S3FileSystem +except ImportError: + S3FileSystem = None +# isort: on + +import fnmatch +import logging +import os +import shutil +from pathlib import Path +from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Tuple, Type, Union + +from ray.air._internal.filelock import TempFileLock +from ray.train._internal.syncer import SyncConfig, Syncer, _BackgroundSyncer +from ray.train.constants import _get_ray_train_session_dir +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + from ray.train._checkpoint import Checkpoint + + +logger = logging.getLogger(__name__) + + +_VALIDATE_STORAGE_MARKER_FILENAME = ".validate_storage_marker" + + +class _ExcludingLocalFilesystem(LocalFileSystem): + """LocalFileSystem wrapper to exclude files according to patterns. + + Args: + root_path: Root path to strip when matching with the exclude pattern. + Ex: root_path="/tmp/a/b/c", exclude=["*a*"], will exclude + /tmp/a/b/c/_a_.txt but not ALL of /tmp/a/*. + exclude: List of patterns that are applied to files returned by + ``self.find()``. If a file path matches this pattern, it will + be excluded. + + """ + + def __init__(self, root_path: Path, exclude: List[str], **kwargs): + super().__init__(**kwargs) + self._exclude = exclude + self._root_path = root_path + + @property + def fsid(self): + return "_excluding_local" + + def _should_exclude(self, path: str) -> bool: + """Return True if `path` (relative to `root_path`) matches any of the + `self._exclude` patterns.""" + path = Path(path) + relative_path = path.relative_to(self._root_path).as_posix() + match_candidates = [relative_path] + if path.is_dir(): + # Everything is in posix path format ('/') + match_candidates.append(relative_path + "/") + + for excl in self._exclude: + if any(fnmatch.fnmatch(candidate, excl) for candidate in match_candidates): + return True + return False + + def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + """Call parent find() and exclude from result.""" + paths = super().find( + path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs + ) + if detail: + return { + path: out + for path, out in paths.items() + if not self._should_exclude(path) + } + else: + return [path for path in paths if not self._should_exclude(path)] + + +def _pyarrow_fs_copy_files( + source, destination, source_filesystem=None, destination_filesystem=None, **kwargs +): + if S3FileSystem and isinstance(destination_filesystem, pyarrow.fs.S3FileSystem): + # Workaround multi-threading issue with pyarrow. Note that use_threads=True + # is safe for download, just not for uploads, see: + # https://github.com/apache/arrow/issues/32372 + kwargs.setdefault("use_threads", False) + + # Use a large chunk size to speed up large checkpoint transfers. + kwargs.setdefault("chunk_size", 64 * 1024 * 1024) + + return pyarrow.fs.copy_files( + source, + destination, + source_filesystem=source_filesystem, + destination_filesystem=destination_filesystem, + **kwargs, + ) + + +# TODO(justinvyu): Add unit tests for all these utils. + + +def _delete_fs_path(fs: pyarrow.fs.FileSystem, fs_path: str): + is_dir = _is_directory(fs, fs_path) + + try: + if is_dir: + fs.delete_dir(fs_path) + else: + fs.delete_file(fs_path) + except Exception: + logger.exception(f"Caught exception when deleting path at ({fs}, {fs_path}):") + + +def _download_from_fs_path( + fs: pyarrow.fs.FileSystem, + fs_path: str, + local_path: str, + filelock: bool = True, +): + """Downloads a directory or file from (fs, fs_path) to a local path. + + If fs_path points to a directory: + - The full directory contents are downloaded directly into `local_path`, + rather than to a subdirectory of `local_path`. + + If fs_path points to a file: + - The file is downloaded to `local_path`, which is expected to be a file path. + + If the download fails, the `local_path` contents are + cleaned up before raising, if the directory did not previously exist. + + NOTE: This method creates `local_path`'s parent directories if they do not + already exist. If the download fails, this does NOT clean up all the parent + directories that were created. + + Args: + fs: The filesystem to download from. + fs_path: The filesystem path (either a directory or a file) to download. + local_path: The local path to download to. + filelock: Whether to require a file lock before downloading, useful for + multiple downloads to the same directory that may be happening in parallel. + + Raises: + FileNotFoundError: if (fs, fs_path) doesn't exist. + """ + + _local_path = Path(local_path).resolve() + exists_before = _local_path.exists() + if _is_directory(fs=fs, fs_path=fs_path): + _local_path.mkdir(parents=True, exist_ok=True) + else: + _local_path.parent.mkdir(parents=True, exist_ok=True) + + try: + if filelock: + with TempFileLock(f"{os.path.normpath(local_path)}.lock"): + _pyarrow_fs_copy_files(fs_path, local_path, source_filesystem=fs) + else: + _pyarrow_fs_copy_files(fs_path, local_path, source_filesystem=fs) + except Exception as e: + # Clean up the directory if downloading was unsuccessful + if not exists_before: + shutil.rmtree(local_path, ignore_errors=True) + raise e + + +def _upload_to_fs_path( + local_path: str, + fs: pyarrow.fs.FileSystem, + fs_path: str, + exclude: Optional[List[str]] = None, +) -> None: + """Uploads a local directory or file to (fs, fs_path). + + NOTE: This will create all necessary parent directories at the destination. + + Args: + local_path: The local path to upload. + fs: The filesystem to upload to. + fs_path: The filesystem path where the dir/file will be uploaded to. + exclude: A list of filename matches to exclude from upload. This includes + all files under subdirectories as well. + This pattern will match with the relative paths of all files under + `local_path`. + Ex: ["*.png"] to exclude all .png images. + """ + + if not exclude: + # TODO(justinvyu): uploading a single file doesn't work + # (since we always create a directory at fs_path) + _create_directory(fs=fs, fs_path=fs_path) + _pyarrow_fs_copy_files(local_path, fs_path, destination_filesystem=fs) + return + + _upload_to_uri_with_exclude_fsspec( + local_path=local_path, fs=fs, fs_path=fs_path, exclude=exclude + ) + + +def _upload_to_uri_with_exclude_fsspec( + local_path: str, fs: "pyarrow.fs", fs_path: str, exclude: Optional[List[str]] +) -> None: + local_fs = _ExcludingLocalFilesystem(root_path=local_path, exclude=exclude) + handler = pyarrow.fs.FSSpecHandler(local_fs) + source_fs = pyarrow.fs.PyFileSystem(handler) + + _create_directory(fs=fs, fs_path=fs_path) + _pyarrow_fs_copy_files( + local_path, fs_path, source_filesystem=source_fs, destination_filesystem=fs + ) + + +def _list_at_fs_path( + fs: pyarrow.fs.FileSystem, + fs_path: str, + file_filter: Optional[Callable[[pyarrow.fs.FileInfo], bool]] = None, +) -> List[str]: + """Returns the list of filenames at (fs, fs_path), similar to os.listdir. + + If the path doesn't exist, returns an empty list. + """ + if file_filter is None: + file_filter = lambda x: True # noqa: E731 + + selector = pyarrow.fs.FileSelector(fs_path, allow_not_found=True, recursive=False) + return [ + os.path.relpath(file_info.path.lstrip("/"), start=fs_path.lstrip("/")) + for file_info in fs.get_file_info(selector) + if file_filter(file_info) + ] + + +def _exists_at_fs_path(fs: pyarrow.fs.FileSystem, fs_path: str) -> bool: + """Returns True if (fs, fs_path) exists.""" + + valid = fs.get_file_info(fs_path) + return valid.type != pyarrow.fs.FileType.NotFound + + +def _is_directory(fs: pyarrow.fs.FileSystem, fs_path: str) -> bool: + """Checks if (fs, fs_path) is a directory or a file. + + Raises: + FileNotFoundError: if (fs, fs_path) doesn't exist. + """ + + file_info = fs.get_file_info(fs_path) + if file_info.type == pyarrow.fs.FileType.NotFound: + raise FileNotFoundError(f"Path not found: ({fs}, {fs_path})") + + return not file_info.is_file + + +def _create_directory(fs: pyarrow.fs.FileSystem, fs_path: str) -> None: + """Create directory at (fs, fs_path). + + Some external filesystems require directories to already exist, or at least + the `netloc` to be created (e.g. PyArrows ``mock://`` filesystem). + + Generally this should be done before and outside of Ray applications. This + utility is thus primarily used in testing, e.g. of ``mock://` URIs. + """ + try: + fs.create_dir(fs_path) + except Exception: + logger.exception( + f"Caught exception when creating directory at ({fs}, {fs_path}):" + ) + + +def get_fs_and_path( + storage_path: Union[str, os.PathLike], + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, +) -> Tuple[pyarrow.fs.FileSystem, str]: + """Returns the fs and path from a storage path and an optional custom fs. + + Args: + storage_path: A storage path or URI. (ex: s3://bucket/path or /tmp/ray_results) + storage_filesystem: A custom filesystem to use. If not provided, + this will be auto-resolved by pyarrow. If provided, the storage_path + is assumed to be prefix-stripped already, and must be a valid path + on the filesystem. + """ + storage_path = str(storage_path) + + if storage_filesystem: + return storage_filesystem, storage_path + + return pyarrow.fs.FileSystem.from_uri(storage_path) + + +class _FilesystemSyncer(_BackgroundSyncer): + """Syncer between local filesystem and a `storage_filesystem`.""" + + def __init__(self, storage_filesystem: Optional["pyarrow.fs.FileSystem"], **kwargs): + self.storage_filesystem = storage_filesystem + super().__init__(**kwargs) + + def _sync_up_command( + self, local_path: str, uri: str, exclude: Optional[List] = None + ) -> Tuple[Callable, Dict]: + # TODO(justinvyu): Defer this cleanup up as part of the + # external-facing Syncer deprecation. + fs_path = uri + return ( + _upload_to_fs_path, + dict( + local_path=local_path, + fs=self.storage_filesystem, + fs_path=fs_path, + exclude=exclude, + ), + ) + + def _sync_down_command(self, uri: str, local_path: str) -> Tuple[Callable, Dict]: + fs_path = uri + return ( + _download_from_fs_path, + dict( + fs=self.storage_filesystem, + fs_path=fs_path, + local_path=local_path, + ), + ) + + def _delete_command(self, uri: str) -> Tuple[Callable, Dict]: + fs_path = uri + return _delete_fs_path, dict(fs=self.storage_filesystem, fs_path=fs_path) + + +@DeveloperAPI +class StorageContext: + """Shared context that holds the source of truth for all paths and + storage utilities, passed along from the driver to workers. + + This object defines a few types of paths: + 1. *_fs_path: A path on the `storage_filesystem`. This is a regular path + which has been prefix-stripped by pyarrow.fs.FileSystem.from_uri and + can be joined with `Path(...).as_posix()`. + 2. *_driver_staging_path: The temporary staging directory on the local filesystem + where driver artifacts are saved to before persisting them to storage. + 3. trial_working_directory: The local filesystem path that the remote + actors' working directories are moved to by default. + This is separated from the driver staging path so that driver syncing + does not implicitly upload the trial working directory, for trials on the + driver node. + + Example with storage_path="mock:///bucket/path?param=1": + + >>> import ray + >>> from ray.train._internal.storage import StorageContext + >>> import os + >>> _ = ray.init() + >>> storage = StorageContext( + ... storage_path="mock://netloc/bucket/path?param=1", + ... experiment_dir_name="exp_name", + ... ) + >>> storage.storage_filesystem # Auto-resolved # doctest: +ELLIPSIS + >> storage.experiment_fs_path + 'bucket/path/exp_name' + >>> storage.experiment_driver_staging_path # doctest: +ELLIPSIS + '/tmp/ray/session_.../artifacts/.../exp_name/driver_artifacts' + >>> storage.trial_dir_name = "trial_dir" + >>> storage.trial_fs_path + 'bucket/path/exp_name/trial_dir' + >>> storage.trial_driver_staging_path # doctest: +ELLIPSIS + '/tmp/ray/session_.../artifacts/.../exp_name/driver_artifacts/trial_dir' + >>> storage.trial_working_directory # doctest: +ELLIPSIS + '/tmp/ray/session_.../artifacts/.../exp_name/working_dirs/trial_dir' + >>> storage.current_checkpoint_index = 1 + >>> storage.checkpoint_fs_path + 'bucket/path/exp_name/trial_dir/checkpoint_000001' + >>> ray.shutdown() + + Example with storage_path="/tmp/ray_results": + + >>> from ray.train._internal.storage import StorageContext + >>> storage = StorageContext( + ... storage_path="/tmp/ray_results", + ... experiment_dir_name="exp_name", + ... ) + >>> storage.storage_fs_path + '/tmp/ray_results' + >>> storage.experiment_fs_path + '/tmp/ray_results/exp_name' + >>> storage.storage_filesystem # Auto-resolved # doctest: +ELLIPSIS + " + ) + + def _create_validation_file(self): + """On the creation of a storage context, create a validation file at the + storage path to verify that the storage path can be written to. + This validation file is also used to check whether the storage path is + accessible by all nodes in the cluster.""" + valid_file = Path( + self.experiment_fs_path, _VALIDATE_STORAGE_MARKER_FILENAME + ).as_posix() + self.storage_filesystem.create_dir(self.experiment_fs_path) + with self.storage_filesystem.open_output_stream(valid_file): + pass + + def _check_validation_file(self): + """Checks that the validation file exists at the storage path.""" + valid_file = Path( + self.experiment_fs_path, _VALIDATE_STORAGE_MARKER_FILENAME + ).as_posix() + if not _exists_at_fs_path(fs=self.storage_filesystem, fs_path=valid_file): + raise RuntimeError( + f"Unable to set up cluster storage with the following settings:\n{self}" + "\nCheck that all nodes in the cluster have read/write access " + "to the configured storage path. `RunConfig(storage_path)` should be " + "set to a cloud storage URI or a shared filesystem path accessible " + "by all nodes in your cluster ('s3://bucket' or '/mnt/nfs'). " + "A local path on the head node is not accessible by worker nodes. " + "See: https://docs.ray.io/en/latest/train/user-guides/persistent-storage.html" # noqa: E501 + ) + + def _update_checkpoint_index(self, metrics: Dict): + # Per default, increase by 1. This can be overwritten to customize checkpoint + # directories. + self.current_checkpoint_index += 1 + + def persist_current_checkpoint(self, checkpoint: "Checkpoint") -> "Checkpoint": + """Persists a given checkpoint to the current checkpoint path on the filesystem. + + "Current" is defined by the `current_checkpoint_index` attribute of the + storage context. + + This method copies the checkpoint files to the storage location. + It's up to the user to delete the original checkpoint files if desired. + + For example, the original directory is typically a local temp directory. + + Args: + checkpoint: The checkpoint to persist to (fs, checkpoint_fs_path). + + Returns: + Checkpoint: A Checkpoint pointing to the persisted checkpoint location. + """ + # TODO(justinvyu): Fix this cyclical import. + + logger.debug( + "Copying checkpoint files to storage path:\n" + "({source_fs}, {source}) -> ({dest_fs}, {destination})".format( + source=checkpoint.path, + destination=self.checkpoint_fs_path, + source_fs=checkpoint.filesystem, + dest_fs=self.storage_filesystem, + ) + ) + + # Raise an error if the storage path is not accessible when + # attempting to upload a checkpoint from a remote worker. + # Ex: If storage_path is a local path, then a validation marker + # will only exist on the head node but not the worker nodes. + self._check_validation_file() + + self.storage_filesystem.create_dir(self.checkpoint_fs_path) + _pyarrow_fs_copy_files( + source=checkpoint.path, + destination=self.checkpoint_fs_path, + source_filesystem=checkpoint.filesystem, + destination_filesystem=self.storage_filesystem, + ) + + persisted_checkpoint = checkpoint.__class__( + filesystem=self.storage_filesystem, + path=self.checkpoint_fs_path, + ) + logger.info(f"Checkpoint successfully created at: {persisted_checkpoint}") + return persisted_checkpoint + + def persist_artifacts(self, force: bool = False) -> None: + """Persists all artifacts within `trial_local_dir` to storage. + + This method possibly launches a background task to sync the trial dir, + depending on the `sync_period` + `sync_artifacts_on_checkpoint` + settings of `SyncConfig`. + + `(local_fs, trial_working_dir) -> (storage_filesystem, trial_fs_path)` + + Args: + force: If True, wait for a previous sync to finish, launch a new one, + and wait for that one to finish. By the end of a `force=True` call, the + latest version of the trial artifacts will be persisted. + """ + if not self.sync_config.sync_artifacts: + return + + # Skip if there are no artifacts to sync + is_empty = not any(os.scandir(self.trial_working_directory)) + if is_empty: + return + + if force: + self.syncer.wait() + self.syncer.sync_up( + local_dir=self.trial_working_directory, remote_dir=self.trial_fs_path + ) + self.syncer.wait() + else: + self.syncer.sync_up_if_needed( + local_dir=self.trial_working_directory, remote_dir=self.trial_fs_path + ) + + @property + def experiment_fs_path(self) -> str: + """The path on the `storage_filesystem` to the experiment directory. + + NOTE: This does not have a URI prefix anymore, since it has been stripped + by pyarrow.fs.FileSystem.from_uri already. The URI scheme information is + kept in `storage_filesystem` instead. + """ + return Path(self.storage_fs_path, self.experiment_dir_name).as_posix() + + def _get_session_path(self) -> str: + """The Ray Train/Tune session local directory used to stage files + before persisting to the storage filesystem.""" + return Path( + _get_ray_train_session_dir(), self._timestamp, self.experiment_dir_name + ).as_posix() + + @property + def experiment_driver_staging_path(self) -> str: + """The local filesystem path of the experiment directory on the driver node. + + The driver is the node where `Trainer.fit`/`Tuner.fit` is being called. + + This path is of the form: + `/tmp/ray/session_/artifacts// + /driver_artifacts` + + This should be used as the temporary staging location for files *on the driver* + before syncing them to `experiment_fs_path`. + For example, the search algorithm should dump its state to this directory. + See `trial_driver_staging_path` for writing trial-specific artifacts. + + The directory is synced to + `{storage_path}/{experiment_dir_name}` periodically. + See `_ExperimentCheckpointManager.checkpoint` for where that happens. + """ + return Path(self._get_session_path(), "driver_artifacts").as_posix() + + @property + def trial_fs_path(self) -> str: + """The trial directory path on the `storage_filesystem`. + + Raises a ValueError if `trial_dir_name` is not set beforehand. + """ + if self.trial_dir_name is None: + raise RuntimeError( + "Should not access `trial_fs_path` without setting `trial_dir_name`" + ) + return Path(self.experiment_fs_path, self.trial_dir_name).as_posix() + + @property + def trial_driver_staging_path(self) -> str: + """The local filesystem path of the trial directory on the driver. + + The driver is the node where `Trainer.fit`/`Tuner.fit` is being called. + + This path is of the form: + `/tmp/ray/session_/artifacts// + /driver_artifacts/` + + This should be used as the temporary location for files on the driver + before persisting them to `trial_fs_path`. + + For example, callbacks (e.g., JsonLoggerCallback) should write trial-specific + logfiles within this directory. + """ + if self.trial_dir_name is None: + raise RuntimeError( + "Should not access `trial_driver_staging_path` " + "without setting `trial_dir_name`" + ) + return Path(self.experiment_driver_staging_path, self.trial_dir_name).as_posix() + + @property + def trial_working_directory(self) -> str: + """The local filesystem path to trial working directory. + + This path is of the form: + `/tmp/ray/session_/artifacts// + /working_dirs/` + + Ray Train/Tune moves the remote actor's working directory to this path + by default, unless disabled by `RAY_CHDIR_TO_TRIAL_DIR` environment variable. + + Writing files to this directory allows users to persist training artifacts + if `SyncConfig(sync_artifacts=True)` is set. + """ + if self.trial_dir_name is None: + raise RuntimeError( + "Cannot access `trial_working_directory` without " + "setting `trial_dir_name`" + ) + return Path( + self._get_session_path(), "working_dirs", self.trial_dir_name + ).as_posix() + + @property + def checkpoint_fs_path(self) -> str: + """The current checkpoint directory path on the `storage_filesystem`. + + "Current" refers to the checkpoint that is currently being created/persisted. + The user of this class is responsible for setting the `current_checkpoint_index` + (e.g., incrementing when needed). + """ + return Path(self.trial_fs_path, self.checkpoint_dir_name).as_posix() + + @property + def checkpoint_dir_name(self) -> str: + """The current checkpoint directory name, based on the checkpoint index.""" + return StorageContext._make_checkpoint_dir_name(self.current_checkpoint_index) + + @staticmethod + def get_experiment_dir_name(run_obj: Union[str, Callable, Type]) -> str: + from ray.tune.experiment import Experiment + from ray.tune.utils import date_str + + run_identifier = Experiment.get_trainable_name(run_obj) + + if bool(int(os.environ.get("TUNE_DISABLE_DATED_SUBDIR", 0))): + dir_name = run_identifier + else: + dir_name = "{}_{}".format(run_identifier, date_str()) + return dir_name + + @staticmethod + def _make_checkpoint_dir_name(index: int): + """Get the name of the checkpoint directory, given an index.""" + return f"checkpoint_{index:06d}" diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/syncer.py b/venv/lib/python3.10/site-packages/ray/train/_internal/syncer.py new file mode 100644 index 0000000000000000000000000000000000000000..8321552e5fbaa3e13bea6648df5ee960079dc0a1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/syncer.py @@ -0,0 +1,423 @@ +import abc +import logging +import threading +import time +import traceback +from dataclasses import dataclass +from typing import Any, Callable, Dict, List, Optional, Tuple + +from ray._private.thirdparty.tabulate.tabulate import tabulate +from ray.util.annotations import Deprecated, DeveloperAPI +from ray.widgets import Template + +logger = logging.getLogger(__name__) + +# Syncing period for syncing checkpoints between nodes or to cloud. +DEFAULT_SYNC_PERIOD = 300 + +# Default sync timeout after which syncing processes are aborted +DEFAULT_SYNC_TIMEOUT = 1800 + + +@Deprecated +@dataclass +class SyncConfig: + sync_period: int = DEFAULT_SYNC_PERIOD + sync_timeout: int = DEFAULT_SYNC_TIMEOUT + sync_artifacts: bool = False + sync_artifacts_on_checkpoint: bool = True + + def _repr_html_(self) -> str: + """Generate an HTML representation of the SyncConfig.""" + return Template("scrollableTable.html.j2").render( + table=tabulate( + { + "Setting": ["Sync period", "Sync timeout"], + "Value": [self.sync_period, self.sync_timeout], + }, + tablefmt="html", + showindex=False, + headers="keys", + ), + max_height="none", + ) + + +class _BackgroundProcess: + def __init__(self, fn: Callable): + self._fn = fn + self._process = None + self._result = {} + self._start_time = float("-inf") + + @property + def is_running(self): + return self._process and self._process.is_alive() + + @property + def start_time(self): + return self._start_time + + def start(self, *args, **kwargs): + if self.is_running: + return False + + self._result = {} + + def entrypoint(): + try: + result = self._fn(*args, **kwargs) + except Exception as e: + self._result["exception"] = e + return + + self._result["result"] = result + + self._process = threading.Thread(target=entrypoint) + self._process.daemon = True + self._process.start() + self._start_time = time.time() + + def wait(self, timeout: Optional[float] = None) -> Any: + """Waits for the background process to finish running. Waits until the + background process has run for at least `timeout` seconds, counting from + the time when the process was started.""" + if not self._process: + return None + + time_remaining = None + if timeout: + elapsed = time.time() - self.start_time + time_remaining = max(timeout - elapsed, 0) + + self._process.join(timeout=time_remaining) + + if self._process.is_alive(): + self._process = None + raise TimeoutError( + f"{getattr(self._fn, '__name__', str(self._fn))} did not finish " + f"running within the timeout of {timeout} seconds." + ) + + self._process = None + + exception = self._result.get("exception") + if exception: + raise exception + + result = self._result.get("result") + + self._result = {} + return result + + +@DeveloperAPI +class Syncer(abc.ABC): + """Syncer class for synchronizing data between Ray nodes and remote (cloud) storage. + + This class handles data transfer for two cases: + + 1. Synchronizing data such as experiment state snapshots from the driver to + cloud storage. + 2. Synchronizing data such as trial checkpoints from remote trainables to + cloud storage. + + Synchronizing tasks are usually asynchronous and can be awaited using ``wait()``. + The base class implements a ``wait_or_retry()`` API that will retry a failed + sync command. + + The base class also exposes an API to only kick off syncs every ``sync_period`` + seconds. + + Args: + sync_period: The minimum time in seconds between sync operations, as + used by ``sync_up/down_if_needed``. + sync_timeout: The maximum time to wait for a sync process to finish before + issuing a new sync operation. Ex: should be used by ``wait`` if launching + asynchronous sync tasks. + """ + + def __init__( + self, + sync_period: float = DEFAULT_SYNC_PERIOD, + sync_timeout: float = DEFAULT_SYNC_TIMEOUT, + ): + self.sync_period = sync_period + self.sync_timeout = sync_timeout + self.last_sync_up_time = float("-inf") + self.last_sync_down_time = float("-inf") + + @abc.abstractmethod + def sync_up( + self, local_dir: str, remote_dir: str, exclude: Optional[List] = None + ) -> bool: + """Synchronize local directory to remote directory. + + This function can spawn an asynchronous process that can be awaited in + ``wait()``. + + Args: + local_dir: Local directory to sync from. + remote_dir: Remote directory to sync up to. This is an URI + (``protocol://remote/path``). + exclude: Pattern of files to exclude, e.g. + ``["*/checkpoint_*]`` to exclude trial checkpoints. + + Returns: + True if sync process has been spawned, False otherwise. + + """ + raise NotImplementedError + + @abc.abstractmethod + def sync_down( + self, remote_dir: str, local_dir: str, exclude: Optional[List] = None + ) -> bool: + """Synchronize remote directory to local directory. + + This function can spawn an asynchronous process that can be awaited in + ``wait()``. + + Args: + remote_dir: Remote directory to sync down from. This is an URI + (``protocol://remote/path``). + local_dir: Local directory to sync to. + exclude: Pattern of files to exclude, e.g. + ``["*/checkpoint_*]`` to exclude trial checkpoints. + + Returns: + True if sync process has been spawned, False otherwise. + + """ + raise NotImplementedError + + @abc.abstractmethod + def delete(self, remote_dir: str) -> bool: + """Delete directory on remote storage. + + This function can spawn an asynchronous process that can be awaited in + ``wait()``. + + Args: + remote_dir: Remote directory to delete. This is an URI + (``protocol://remote/path``). + + Returns: + True if sync process has been spawned, False otherwise. + + """ + raise NotImplementedError + + def retry(self): + """Retry the last sync up, sync down, or delete command. + + You should implement this method if you spawn asynchronous syncing + processes. + """ + pass + + def wait(self, timeout: Optional[float] = None): + """Wait for asynchronous sync command to finish. + + You should implement this method if you spawn asynchronous syncing + processes. This method should timeout after the asynchronous command + has run for `sync_timeout` seconds and raise a `TimeoutError`. + """ + pass + + def sync_up_if_needed( + self, local_dir: str, remote_dir: str, exclude: Optional[List] = None + ) -> bool: + """Syncs up if time since last sync up is greater than sync_period. + + Args: + local_dir: Local directory to sync from. + remote_dir: Remote directory to sync up to. This is an URI + (``protocol://remote/path``). + exclude: Pattern of files to exclude, e.g. + ``["*/checkpoint_*]`` to exclude trial checkpoints. + """ + now = time.time() + if now - self.last_sync_up_time >= self.sync_period: + result = self.sync_up( + local_dir=local_dir, remote_dir=remote_dir, exclude=exclude + ) + self.last_sync_up_time = now + return result + + def sync_down_if_needed( + self, remote_dir: str, local_dir: str, exclude: Optional[List] = None + ): + """Syncs down if time since last sync down is greater than sync_period. + + Args: + remote_dir: Remote directory to sync down from. This is an URI + (``protocol://remote/path``). + local_dir: Local directory to sync to. + exclude: Pattern of files to exclude, e.g. + ``["*/checkpoint_*]`` to exclude trial checkpoints. + """ + now = time.time() + if now - self.last_sync_down_time >= self.sync_period: + result = self.sync_down( + remote_dir=remote_dir, local_dir=local_dir, exclude=exclude + ) + self.last_sync_down_time = now + return result + + def wait_or_retry(self, max_retries: int = 2, backoff_s: int = 5): + assert max_retries > 0 + last_error_traceback = None + for i in range(max_retries + 1): + try: + self.wait() + except Exception as e: + attempts_remaining = max_retries - i + + # If we're out of retries, then save the full traceback of the last + # error and show it when raising an exception. + if attempts_remaining == 0: + last_error_traceback = traceback.format_exc() + break + + logger.error( + f"The latest sync operation failed with the following error: " + f"{repr(e)}\n" + f"Retrying {attempts_remaining} more time(s) after sleeping " + f"for {backoff_s} seconds..." + ) + time.sleep(backoff_s) + self.retry() + continue + # Succeeded! + return + raise RuntimeError( + f"Failed sync even after {max_retries} retries. " + f"The latest sync failed with the following error:\n{last_error_traceback}" + ) + + def reset(self): + self.last_sync_up_time = float("-inf") + self.last_sync_down_time = float("-inf") + + def close(self): + pass + + def _repr_html_(self) -> str: + return + + +class _BackgroundSyncer(Syncer): + """Syncer using a background process for asynchronous file transfer.""" + + def __init__( + self, + sync_period: float = DEFAULT_SYNC_PERIOD, + sync_timeout: float = DEFAULT_SYNC_TIMEOUT, + ): + super(_BackgroundSyncer, self).__init__( + sync_period=sync_period, sync_timeout=sync_timeout + ) + self._sync_process = None + self._current_cmd = None + + def _should_continue_existing_sync(self): + """Returns whether a previous sync is still running within the timeout.""" + return ( + self._sync_process + and self._sync_process.is_running + and time.time() - self._sync_process.start_time < self.sync_timeout + ) + + def _launch_sync_process(self, sync_command: Tuple[Callable, Dict]): + """Waits for the previous sync process to finish, + then launches a new process that runs the given command.""" + if self._sync_process: + try: + self.wait() + except Exception: + logger.warning( + f"Last sync command failed with the following error:\n" + f"{traceback.format_exc()}" + ) + + self._current_cmd = sync_command + self.retry() + + def sync_up( + self, local_dir: str, remote_dir: str, exclude: Optional[List] = None + ) -> bool: + if self._should_continue_existing_sync(): + logger.debug( + f"Last sync still in progress, " + f"skipping sync up of {local_dir} to {remote_dir}" + ) + return False + + sync_up_cmd = self._sync_up_command( + local_path=local_dir, uri=remote_dir, exclude=exclude + ) + self._launch_sync_process(sync_up_cmd) + + return True + + def _sync_up_command( + self, local_path: str, uri: str, exclude: Optional[List] = None + ) -> Tuple[Callable, Dict]: + raise NotImplementedError + + def sync_down( + self, remote_dir: str, local_dir: str, exclude: Optional[List] = None + ) -> bool: + if self._should_continue_existing_sync(): + logger.warning( + f"Last sync still in progress, " + f"skipping sync down of {remote_dir} to {local_dir}" + ) + return False + + sync_down_cmd = self._sync_down_command(uri=remote_dir, local_path=local_dir) + self._launch_sync_process(sync_down_cmd) + + return True + + def _sync_down_command(self, uri: str, local_path: str) -> Tuple[Callable, Dict]: + raise NotImplementedError + + def delete(self, remote_dir: str) -> bool: + if self._should_continue_existing_sync(): + logger.warning( + f"Last sync still in progress, skipping deletion of {remote_dir}" + ) + return False + + delete_cmd = self._delete_command(uri=remote_dir) + self._launch_sync_process(delete_cmd) + + return True + + def _delete_command(self, uri: str) -> Tuple[Callable, Dict]: + raise NotImplementedError + + def wait(self, timeout: Optional[float] = None): + if self._sync_process: + try: + self._sync_process.wait(timeout=timeout or self.sync_timeout) + except Exception as e: + raise e + finally: + # Regardless of whether the sync process succeeded within the timeout, + # clear the sync process so a new one can be created. + self._sync_process = None + + def retry(self): + if not self._current_cmd: + raise RuntimeError("No sync command set, cannot retry.") + cmd, kwargs = self._current_cmd + self._sync_process = _BackgroundProcess(cmd) + self._sync_process.start(**kwargs) + + def __getstate__(self): + state = self.__dict__.copy() + state["_sync_process"] = None + return state diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/utils.py b/venv/lib/python3.10/site-packages/ray/train/_internal/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1e9946789ef18a33d506e4be4d811a1f3dd901d8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/utils.py @@ -0,0 +1,239 @@ +import abc +import functools +import inspect +import logging +import os +from pathlib import Path +from typing import ( + Any, + Callable, + ContextManager, + Dict, + List, + Optional, + Tuple, + TypeVar, + Union, +) + +import ray +from ray.actor import ActorHandle +from ray.air._internal.util import ( + StartTraceback, + StartTracebackWithWorkerRank, + find_free_port, +) +from ray.exceptions import RayActorError +from ray.types import ObjectRef + +T = TypeVar("T") + +logger = logging.getLogger(__name__) + + +def check_for_failure( + remote_values: List[ObjectRef], +) -> Tuple[bool, Optional[Exception]]: + """Check for actor failure when retrieving the remote values. + + Args: + remote_values: List of object references from Ray actor methods. + + Returns: + A tuple of (bool, Exception). The bool is + True if evaluating all object references is successful, False otherwise. + """ + unfinished = remote_values.copy() + + while len(unfinished) > 0: + finished, unfinished = ray.wait(unfinished) + + # If a failure occurs the ObjectRef will be marked as finished. + # Calling ray.get will expose the failure as a RayActorError. + for object_ref in finished: + # Everything in finished has either failed or completed + # successfully. + try: + ray.get(object_ref) + except RayActorError as exc: + failed_actor_rank = remote_values.index(object_ref) + logger.info(f"Worker {failed_actor_rank} has failed.") + return False, exc + except Exception as exc: + # Other (e.g. training) errors should be directly raised + failed_worker_rank = remote_values.index(object_ref) + raise StartTracebackWithWorkerRank( + worker_rank=failed_worker_rank + ) from exc + + return True, None + + +def get_address_and_port() -> Tuple[str, int]: + """Returns the IP address and a free port on this node.""" + addr = ray.util.get_node_ip_address() + port = find_free_port() + + return addr, port + + +def construct_path(path: Path, parent_path: Path) -> Path: + """Constructs a path relative to a parent. + + Args: + path: A relative or absolute path. + parent_path: A relative path or absolute path. + + Returns: An absolute path. + """ + if path.expanduser().is_absolute(): + return path.expanduser().resolve() + else: + return parent_path.joinpath(path).expanduser().resolve() + + +def update_env_vars(env_vars: Dict[str, Any]): + """Updates the environment variables on this worker process. + + Args: + env_vars: Environment variables to set. + """ + sanitized = {k: str(v) for k, v in env_vars.items()} + os.environ.update(sanitized) + + +def count_required_parameters(fn: Callable) -> int: + """Counts the number of required parameters of a function. + + NOTE: *args counts as 1 required parameter. + + Examples + -------- + + >>> def fn(a, b, /, c, *args, d=1, e=2, **kwargs): + ... pass + >>> count_required_parameters(fn) + 4 + + >>> fn = lambda: 1 + >>> count_required_parameters(fn) + 0 + + >>> def fn(config, a, b=1, c=2): + ... pass + >>> from functools import partial + >>> count_required_parameters(partial(fn, a=0)) + 1 + """ + params = inspect.signature(fn).parameters.values() + + positional_param_kinds = { + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.VAR_POSITIONAL, + } + return len( + [ + p + for p in params + if p.default == inspect.Parameter.empty and p.kind in positional_param_kinds + ] + ) + + +def construct_train_func( + train_func: Union[Callable[[], T], Callable[[Dict[str, Any]], T]], + config: Optional[Dict[str, Any]], + train_func_context: ContextManager, + fn_arg_name: Optional[str] = "train_func", + discard_returns: bool = False, +) -> Callable[[], T]: + """Validates and constructs the training function to execute. + Args: + train_func: The training function to execute. + This can either take in no arguments or a ``config`` dict. + config (Optional[Dict]): Configurations to pass into + ``train_func``. If None then an empty Dict will be created. + train_func_context: Context manager for user's `train_func`, which executes + backend-specific logic before and after the training function. + fn_arg_name (Optional[str]): The name of training function to use for error + messages. + discard_returns: Whether to discard any returns from train_func or not. + Returns: + A valid training function. + Raises: + ValueError: if the input ``train_func`` is invalid. + """ + num_required_params = count_required_parameters(train_func) + + if discard_returns: + # Discard any returns from the function so that + # BackendExecutor doesn't try to deserialize them. + # Those returns are inaccesible with AIR anyway. + @functools.wraps(train_func) + def discard_return_wrapper(*args, **kwargs): + try: + train_func(*args, **kwargs) + except Exception as e: + raise StartTraceback from e + + wrapped_train_func = discard_return_wrapper + else: + wrapped_train_func = train_func + + if num_required_params > 1: + err_msg = ( + f"{fn_arg_name} should take in 0 or 1 required arguments, but it accepts " + f"{num_required_params} required arguments instead." + ) + raise ValueError(err_msg) + elif num_required_params == 1: + config = {} if config is None else config + + @functools.wraps(wrapped_train_func) + def train_fn(): + try: + with train_func_context(): + return wrapped_train_func(config) + except Exception as e: + raise StartTraceback from e + + else: # num_params == 0 + + @functools.wraps(wrapped_train_func) + def train_fn(): + try: + with train_func_context(): + return wrapped_train_func() + except Exception as e: + raise StartTraceback from e + + return train_fn + + +class Singleton(abc.ABCMeta): + """Singleton Abstract Base Class + + https://stackoverflow.com/questions/33364070/implementing + -singleton-as-metaclass-but-for-abstract-classes + """ + + _instances = {} + + def __call__(cls, *args, **kwargs): + if cls not in cls._instances: + cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) + return cls._instances[cls] + + +class ActorWrapper: + """Wraps an actor to provide same API as using the base class directly.""" + + def __init__(self, actor: ActorHandle): + self.actor = actor + + def __getattr__(self, item): + # The below will fail if trying to access an attribute (not a method) from the + # actor. + actor_method = getattr(self.actor, item) + return lambda *args, **kwargs: ray.get(actor_method.remote(*args, **kwargs)) diff --git a/venv/lib/python3.10/site-packages/ray/train/_internal/worker_group.py b/venv/lib/python3.10/site-packages/ray/train/_internal/worker_group.py new file mode 100644 index 0000000000000000000000000000000000000000..853502b3512fa0c844d33105c21db296484a2d87 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/_internal/worker_group.py @@ -0,0 +1,426 @@ +import logging +import os +import socket +from collections import defaultdict +from dataclasses import dataclass +from typing import Callable, Dict, List, Optional, Tuple, Type, TypeVar, Union + +import ray +from ray.actor import ActorHandle +from ray.air._internal.util import exception_cause, skip_exceptions +from ray.types import ObjectRef +from ray.util.placement_group import PlacementGroup + +T = TypeVar("T") + +logger = logging.getLogger(__name__) + + +class RayTrainWorker: + """A class to execute arbitrary functions. Does not hold any state.""" + + def __execute(self, func: Callable[..., T], *args, **kwargs) -> T: + """Executes the input function and returns the output. + + Args: + func: The function to execute. + args, kwargs: The arguments to pass into func. + """ + try: + return func(*args, **kwargs) + except Exception as e: + skipped = skip_exceptions(e) + raise skipped from exception_cause(skipped) + + +@dataclass +class WorkerMetadata: + """Metadata for each worker/actor. + + This information is expected to stay the same throughout the lifetime of + actor. + + Args: + node_id: ID of the node this worker is on. + node_ip: IP address of the node this worker is on. + hostname: Hostname that this worker is on. + resource_ids: Map of accelerator resources + ("GPU", "neuron_cores", ..) to their IDs. + pid: Process ID of this worker. + """ + + node_id: str + node_ip: str + hostname: str + resource_ids: Dict[str, List[str]] + pid: int + + +@dataclass +class Worker: + """Class representing a Worker.""" + + actor: ActorHandle + metadata: WorkerMetadata + + +def create_executable_class(executable_cls: Optional[Type] = None) -> Type: + """Create the executable class to use as the Ray actors.""" + if not executable_cls: + return RayTrainWorker + elif issubclass(executable_cls, RayTrainWorker): + return executable_cls + else: + + class _WrappedExecutable(executable_cls, RayTrainWorker): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + return _WrappedExecutable + + +def construct_metadata() -> WorkerMetadata: + """Creates metadata for this worker. + + This function is expected to be run on the actor. + """ + node_id = ray.get_runtime_context().get_node_id() + node_ip = ray.util.get_node_ip_address() + hostname = socket.gethostname() + accelerator_ids = ray.get_runtime_context().get_accelerator_ids() + pid = os.getpid() + + return WorkerMetadata( + node_id=node_id, + node_ip=node_ip, + hostname=hostname, + resource_ids=accelerator_ids, + pid=pid, + ) + + +class WorkerGroup: + """Group of Ray Actors that can execute arbitrary functions. + + ``WorkerGroup`` launches Ray actors according to the given + specification. It can then execute arbitrary Python functions in each of + these workers. + + If not enough resources are available to launch the actors, the Ray + cluster will automatically scale up if autoscaling is enabled. + + Args: + num_workers: The number of workers (Ray actors) to launch. + Defaults to 1. + resources_per_worker (Optional[Dict[str, float]]): + Dictionary specifying the resources that will be + requested for each worker. Defaults to {"CPU": 1}. + actor_cls (Optional[Type]): If specified use this class as the + remote actors. + remote_cls_args, remote_cls_kwargs: If ``remote_cls`` is provided, + these args will be used for the worker initialization. + placement_group (PlacementGroup|str): The placement group that workers + should be created in. Defaults to "default" which will inherit the + parent placement group (if child tasks should be captured). + + + Example: + + .. code_block:: python + + worker_group = WorkerGroup(num_workers=2) + output = worker_group.execute(lambda: 1) + assert len(output) == 2 + assert all(o == 1 for o in output) + """ + + def __init__( + self, + num_workers: int = 1, + resources_per_worker: Optional[Dict[str, float]] = None, + actor_cls: Type = None, + actor_cls_args: Optional[Tuple] = None, + actor_cls_kwargs: Optional[Dict] = None, + placement_group: Union[PlacementGroup, str] = "default", + ): + if resources_per_worker is None: + resources_per_worker = {"CPU": 1} + else: + resources_per_worker = resources_per_worker.copy() + + if num_workers <= 0: + raise ValueError( + "The provided `num_workers` must be greater " + f"than 0. Received num_workers={num_workers} " + f"instead." + ) + + if any(v < 0 for v in resources_per_worker.values()): + raise ValueError( + "The number of resources per worker must not be negative. " + f"Received resources_per_worker={resources_per_worker}." + ) + + if (actor_cls_args or actor_cls_kwargs) and not actor_cls: + raise ValueError( + "`actor_cls_args` or `actor_class_kwargs` are " + "passed in but no `actor_cls` is passed in." + ) + + self.num_workers = num_workers + self.num_cpus_per_worker = resources_per_worker.pop("CPU", 0) + self.num_gpus_per_worker = resources_per_worker.pop("GPU", 0) + self.memory_per_worker = resources_per_worker.pop("memory", 0) + self.workers = [] + self._base_cls = create_executable_class(actor_cls) + assert issubclass(self._base_cls, RayTrainWorker) + + self._actor_cls_args = actor_cls_args or [] + self._actor_cls_kwargs = actor_cls_kwargs or {} + + self._placement_group = placement_group + + # TODO(matt): Validate resources. Fast-fail if it is impossible to + # handle the request, rather than hang indefinitely. + self._remote_cls = ray.remote( + num_cpus=self.num_cpus_per_worker, + num_gpus=self.num_gpus_per_worker, + memory=self.memory_per_worker, + resources=resources_per_worker, + )(self._base_cls) + self.start() + + def start(self): + """Starts all the workers in this worker group.""" + if self.workers and len(self.workers) > 0: + raise RuntimeError( + "The workers have already been started. " + "Please call `shutdown` first if you want to " + "restart them." + ) + + logger.debug(f"Starting {self.num_workers} workers.") + self.add_workers(self.num_workers) + logger.debug(f"{len(self.workers)} workers have successfully started.") + + def shutdown(self, patience_s: float = 5): + """Shutdown all the workers in this worker group. + + Args: + patience_s: Attempt a graceful shutdown + of the workers for this many seconds. Fallback to force kill + if graceful shutdown is not complete after this time. If + this is less than or equal to 0, immediately force kill all + workers. + """ + logger.debug(f"Shutting down {len(self.workers)} workers.") + if patience_s <= 0: + for worker in self.workers: + ray.kill(worker.actor) + else: + done_refs = [w.actor.__ray_terminate__.remote() for w in self.workers] + # Wait for actors to die gracefully. + done, not_done = ray.wait(done_refs, timeout=patience_s) + if not_done: + logger.debug("Graceful termination failed. Falling back to force kill.") + # If all actors are not able to die gracefully, then kill them. + for worker in self.workers: + ray.kill(worker.actor) + + logger.debug("Shutdown successful.") + self.workers = [] + + def execute_async(self, func: Callable[..., T], *args, **kwargs) -> List[ObjectRef]: + """Execute ``func`` on each worker and return the futures. + + Args: + func: A function to call on each worker. + args, kwargs: Passed directly into func. + + Returns: + (List[ObjectRef]) A list of ``ObjectRef`` representing the + output of ``func`` from each worker. The order is the same + as ``self.workers``. + + """ + if len(self.workers) <= 0: + raise RuntimeError( + "There are no active workers. This worker " + "group has most likely been shut down. Please" + "create a new WorkerGroup or restart this one." + ) + + return [ + w.actor._RayTrainWorker__execute.options( + name=f"_RayTrainWorker__execute.{func.__name__}" + ).remote(func, *args, **kwargs) + for w in self.workers + ] + + def execute(self, func: Callable[..., T], *args, **kwargs) -> List[T]: + """Execute ``func`` on each worker and return the outputs of ``func``. + + Args: + func: A function to call on each worker. + args, kwargs: Passed directly into func. + + Returns: + (List[T]) A list containing the output of ``func`` from each + worker. The order is the same as ``self.workers``. + + """ + return ray.get(self.execute_async(func, *args, **kwargs)) + + def execute_single_async( + self, worker_index: int, func: Callable[..., T], *args, **kwargs + ) -> ObjectRef: + """Execute ``func`` on worker ``worker_index`` and return futures. + + Args: + worker_index: The index to execute func on. + func: A function to call on the first worker. + args, kwargs: Passed directly into func. + + Returns: + (ObjectRef) An ObjectRef representing the output of func. + + """ + if worker_index >= len(self.workers): + raise ValueError( + f"The provided worker_index {worker_index} is " + f"not valid for {self.num_workers} workers." + ) + return ( + self.workers[worker_index] + .actor._RayTrainWorker__execute.options( + name=f"_RayTrainWorker__execute.{func.__name__}" + ) + .remote(func, *args, **kwargs) + ) + + def execute_single( + self, worker_index: int, func: Callable[..., T], *args, **kwargs + ) -> T: + """Execute ``func`` on worker with index ``worker_index``. + + Args: + worker_index: The index to execute func on. + func: A function to call on the first worker. + args, kwargs: Passed directly into func. + + Returns: + (T) The output of func. + + """ + + return ray.get(self.execute_single_async(worker_index, func, *args, **kwargs)) + + def remove_workers(self, worker_indexes: List[int]): + """Removes the workers with the specified indexes. + + The removed workers will go out of scope and their actor processes + will be terminated. + + Args: + worker_indexes (List[int]): The indexes of the workers to remove. + """ + new_workers = [] + for i in range(len(self.workers)): + if i not in worker_indexes: + new_workers.append(self.workers[i]) + self.workers = new_workers + + def add_workers(self, num_workers: int): + """Adds ``num_workers`` to this WorkerGroup. + + Note: Adding workers when the cluster/placement group is at capacity + may lead to undefined hanging behavior. If you are attempting to + replace existing workers in the WorkerGroup, remove_workers() should + be called first. + + Args: + num_workers: The number of workers to add. + """ + new_actors = [] + new_actor_metadata = [] + for _ in range(num_workers): + actor = self._remote_cls.options( + placement_group=self._placement_group + ).remote(*self._actor_cls_args, **self._actor_cls_kwargs) + new_actors.append(actor) + new_actor_metadata.append( + actor._RayTrainWorker__execute.options( + name="_RayTrainWorker__execute.construct_metadata" + ).remote(construct_metadata) + ) + + # Get metadata from all actors. + metadata = ray.get(new_actor_metadata) + + for i in range(len(new_actors)): + self.workers.append(Worker(actor=new_actors[i], metadata=metadata[i])) + + def sort_workers_by_node_id_and_gpu_id(self, _first_node_id: Optional[str] = None): + """Reorder the workers by their node id and the lowest GPU id. + + This is useful for collocating workers on the same node. + + Example: + Given workers with the following attributes: + worker_0: node_id=1, gpu_ids=[1] + worker_1: node_id=0, gpu_ids=[0] + worker_2: node_id=1, gpu_ids=[0] + worker_3: node_id=0, gpu_ids=[1] + + The function will perform the following steps: + 1. Group by node ID: + node_id=0: worker_1, worker_3 + node_id=1: worker_0, worker_2 + + 2. Sort each group by GPU ID: + node_id=0: worker_1 (gpu_id=0), worker_3 (gpu_id=1) + node_id=1: worker_2 (gpu_id=0), worker_0 (gpu_id=1) + + Resulting in the order: [worker_1, worker_3, worker_2, worker_0] + + Args: + _first_node_id: The first ID to group by. + Set this to the node ID of the trainer coordinator to ensure that the + rank 0 worker is on the same node, allowing additional resources to + be specified for rank 0 workers via + `ScalingConfig(trainer_resources=)`. + """ + node_id_to_workers = defaultdict(list) + + if _first_node_id is not None: + node_id_to_workers[_first_node_id] = [] + + for worker in self.workers: + node_id_to_workers[worker.metadata.node_id].append(worker) + + # Sort workers on the same node by the lowest GPU id + # More details: https://github.com/ray-project/ray/issues/40803 + def get_lowest_gpu_id(worker) -> int: + gpu_ids = worker.metadata.resource_ids.get("GPU", []) + # If there are no GPU IDs, return 0 as a default + if not gpu_ids: + return 0 + + # Attempt to convert GPU IDs to integers and find the minimum ID. + # Fallback to return the minimum string-based ID + try: + return min(int(gpu_id) for gpu_id in gpu_ids) + except ValueError: + return min(gpu_ids) + + for node_id in node_id_to_workers: + node_id_to_workers[node_id].sort(key=get_lowest_gpu_id) + + sorted_workers = [] + for workers in node_id_to_workers.values(): + sorted_workers.extend(workers) + + self.workers = sorted_workers + + def __len__(self): + return len(self.workers) diff --git a/venv/lib/python3.10/site-packages/ray/train/backend.py b/venv/lib/python3.10/site-packages/ray/train/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..b50f5867e7a75f47b36a0778463d7a113be1585d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/backend.py @@ -0,0 +1,59 @@ +import logging +from contextlib import nullcontext +from typing import TypeVar + +from ray.train._internal.utils import Singleton +from ray.train._internal.worker_group import WorkerGroup +from ray.util.annotations import DeveloperAPI +from ray.widgets import make_table_html_repr + +EncodedData = TypeVar("EncodedData") + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class BackendConfig: + """Parent class for configurations of training backend.""" + + @property + def backend_cls(self): + return Backend + + @property + def train_func_context(self): + return nullcontext + + def _repr_html_(self) -> str: + return make_table_html_repr(obj=self, title=type(self).__name__) + + +@DeveloperAPI +class Backend(metaclass=Singleton): + """Singleton for distributed communication backend. + + Attributes: + share_cuda_visible_devices: If True, each worker + process will have CUDA_VISIBLE_DEVICES set as the visible device + IDs of all workers on the same node for this training instance. + If False, each worker will have CUDA_VISIBLE_DEVICES set to the + device IDs allocated by Ray for that worker. + """ + + share_cuda_visible_devices: bool = False + + def on_start(self, worker_group: WorkerGroup, backend_config: BackendConfig): + """Logic for starting this backend.""" + pass + + def on_shutdown(self, worker_group: WorkerGroup, backend_config: BackendConfig): + """Logic for shutting down the backend.""" + pass + + def on_training_start( + self, worker_group: WorkerGroup, backend_config: BackendConfig + ): + """Logic ran right before training is started. + + Session API is available at this point.""" + pass diff --git a/venv/lib/python3.10/site-packages/ray/train/base_trainer.py b/venv/lib/python3.10/site-packages/ray/train/base_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..b69211ddc65b02709d371709e6e46fb789a922ce --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/base_trainer.py @@ -0,0 +1,911 @@ +import abc +import copy +import inspect +import json +import logging +import os +import warnings +from functools import partial +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, Union + +import pyarrow.fs + +import ray +import ray.cloudpickle as pickle +from ray._private.dict import deep_update +from ray._private.usage import usage_lib +from ray.air._internal import usage as air_usage +from ray.air._internal.config import ensure_only_allowed_dataclass_keys_updated +from ray.air._internal.usage import AirEntrypoint +from ray.air.config import RunConfig, ScalingConfig +from ray.air.result import Result +from ray.train import Checkpoint +from ray.train._internal.session import get_session +from ray.train._internal.storage import ( + StorageContext, + _exists_at_fs_path, + get_fs_and_path, +) +from ray.train.constants import ( + V2_MIGRATION_GUIDE_MESSAGE, + _v2_migration_warnings_enabled, +) +from ray.train.context import _GET_METADATA_DEPRECATION_MESSAGE +from ray.train.utils import _log_deprecation_warning +from ray.util.annotations import Deprecated, DeveloperAPI, PublicAPI + +if TYPE_CHECKING: + from ray.data import Dataset + from ray.tune import Trainable + +_TRAINER_PKL = "trainer.pkl" + +# A type representing either a ray.data.Dataset or a function that returns a +# ray.data.Dataset and accepts no arguments. +GenDataset = Union["Dataset", Callable[[], "Dataset"]] + + +logger = logging.getLogger(__name__) + +PREPROCESSOR_DEPRECATION_MESSAGE = ( + "The `preprocessor` argument to Trainers is deprecated as of Ray 2.7. " + "Instead, use the Preprocessor `fit` and `transform` APIs directly on the Ray " + "Dataset. For any state that needs to be saved to the trained checkpoint, pass it " + "in using the `metadata` argument of the `Trainer`. " + "For a full example, see " + "https://docs.ray.io/en/master/train/user-guides/data-loading-preprocessing.html#preprocessing-structured-data " # noqa:E501 +) + +_TRAINER_RESTORE_DEPRECATION_WARNING = ( + "The `restore` and `can_restore` APIs are deprecated and " + f"will be removed in a future release. {V2_MIGRATION_GUIDE_MESSAGE}" +) + +_RESUME_FROM_CHECKPOINT_DEPRECATION_WARNING = ( + "`resume_from_checkpoint` is deprecated and will be removed in an upcoming " + f"release. {V2_MIGRATION_GUIDE_MESSAGE}" +) + + +@PublicAPI(stability="beta") +class TrainingFailedError(RuntimeError): + """An error indicating that training has failed.""" + + _RESTORE_MSG = ( + "The Ray Train run failed. Please inspect the previous error messages for a " + "cause. After fixing the issue (assuming that the error is not caused by " + "your own application logic, but rather an error such as OOM), you can restart " + "the run from scratch or continue this run.\n" + "To continue this run, you can use: " + '`trainer = {trainer_cls_name}.restore("{path}")`.' + ) + + _FAILURE_CONFIG_MSG = ( + "To start a new run that will retry on training failures, set " + "`train.RunConfig(failure_config=train.FailureConfig(max_failures))` " + "in the Trainer's `run_config` with `max_failures > 0`, or `max_failures = -1` " + "for unlimited retries." + ) + + +def _train_coordinator_fn( + config: dict, trainer_cls: Type["BaseTrainer"], metadata: dict +): + """This is the function that defines the logic of the Ray Train coordinator. + This is responsible for setting up a remote instance of the `trainer_cls` + (a different instance than the one calling `trainer.fit` on the driver!) + and running the training loop. + """ + assert metadata is not None, metadata + # Propagate user metadata from the Trainer constructor. + get_session().metadata = metadata + + # config already contains merged values. + # Instantiate new Trainer in Trainable. + trainer = trainer_cls(**config) + + # Get the checkpoint from Tune and pass it to workers later on. + checkpoint = ray.tune.get_checkpoint() + if checkpoint: + # Set `starting_checkpoint` for auto-recovery fault-tolerance + # as well as manual restoration. + trainer.starting_checkpoint = checkpoint + # else: Train will restore from the user-provided + # `resume_from_checkpoint` == `starting_checkpoint`. + + # Evaluate datasets if they are wrapped in a factory. + trainer.datasets = { + k: d() if callable(d) else d for k, d in trainer.datasets.items() + } + + trainer.setup() + trainer.training_loop() + + +@DeveloperAPI +class BaseTrainer(abc.ABC): + """Defines interface for distributed training on Ray. + + Note: The base ``BaseTrainer`` class cannot be instantiated directly. Only + one of its subclasses can be used. + + Note to developers: If a new trainer is added, please update + `air/_internal/usage.py`. + + **How does a trainer work?** + + - First, initialize the Trainer. The initialization runs locally, + so heavyweight setup should not be done in ``__init__``. + - Then, when you call ``trainer.fit()``, the Trainer is serialized + and copied to a remote Ray actor. The following methods are then + called in sequence on the remote actor. + - ``trainer.setup()``: Any heavyweight Trainer setup should be + specified here. + - ``trainer.training_loop()``: Executes the main training logic. + - Calling ``trainer.fit()`` will return a ``ray.result.Result`` + object where you can access metrics from your training run, as well + as any checkpoints that may have been saved. + + **How do I create a new Trainer?** + + Subclass ``ray.train.trainer.BaseTrainer``, and override the ``training_loop`` + method, and optionally ``setup``. + + .. testcode:: + + import torch + + from ray.train.trainer import BaseTrainer + from ray import train, tune + + + class MyPytorchTrainer(BaseTrainer): + def setup(self): + self.model = torch.nn.Linear(1, 1) + self.optimizer = torch.optim.SGD( + self.model.parameters(), lr=0.1) + + def training_loop(self): + # You can access any Trainer attributes directly in this method. + # self.datasets["train"] has already been + dataset = self.datasets["train"] + + torch_ds = dataset.iter_torch_batches(dtypes=torch.float) + loss_fn = torch.nn.MSELoss() + + for epoch_idx in range(10): + loss = 0 + num_batches = 0 + torch_ds = dataset.iter_torch_batches( + dtypes=torch.float, batch_size=2 + ) + for batch in torch_ds: + X = torch.unsqueeze(batch["x"], 1) + y = torch.unsqueeze(batch["y"], 1) + # Compute prediction error + pred = self.model(X) + batch_loss = loss_fn(pred, y) + + # Backpropagation + self.optimizer.zero_grad() + batch_loss.backward() + self.optimizer.step() + + loss += batch_loss.item() + num_batches += 1 + loss /= num_batches + + # Use Tune functions to report intermediate + # results. + train.report({"loss": loss, "epoch": epoch_idx}) + + + # Initialize the Trainer, and call Trainer.fit() + import ray + train_dataset = ray.data.from_items( + [{"x": i, "y": i} for i in range(10)]) + my_trainer = MyPytorchTrainer(datasets={"train": train_dataset}) + result = my_trainer.fit() + + .. testoutput:: + :hide: + + ... + + Args: + scaling_config: Configuration for how to scale training. + run_config: Configuration for the execution of the training run. + datasets: Any Datasets to use for training. Use the key "train" + to denote which dataset is the training dataset. + metadata: Dict that should be made available via + `train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + resume_from_checkpoint: A checkpoint to resume training from. + """ + + _scaling_config_allowed_keys: List[str] = [ + "trainer_resources", + ] + _handles_checkpoint_freq: bool = False + _handles_checkpoint_at_end: bool = False + + # fields to propagate to Tuner param_space. + # See `BaseTrainer._extract_fields_for_tuner_param_space` for more details. + _fields_for_tuner_param_space = [] + + def __init__( + self, + *, + scaling_config: Optional[ScalingConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + self.scaling_config = ( + scaling_config if scaling_config is not None else ScalingConfig() + ) + self.run_config = ( + copy.copy(run_config) if run_config is not None else RunConfig() + ) + self.metadata = metadata + self.datasets = datasets if datasets is not None else {} + self.starting_checkpoint = resume_from_checkpoint + + if _v2_migration_warnings_enabled(): + if metadata is not None: + _log_deprecation_warning(_GET_METADATA_DEPRECATION_MESSAGE) + if resume_from_checkpoint is not None: + _log_deprecation_warning(_RESUME_FROM_CHECKPOINT_DEPRECATION_WARNING) + + # These attributes should only be set through `BaseTrainer.restore` + self._restore_path = None + self._restore_storage_filesystem = None + + self._validate_attributes() + + usage_lib.record_library_usage("train") + air_usage.tag_air_trainer(self) + + @classmethod + @Deprecated(message=_TRAINER_RESTORE_DEPRECATION_WARNING) + def restore( + cls: Type["BaseTrainer"], + path: Union[str, os.PathLike], + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + scaling_config: Optional[ScalingConfig] = None, + **kwargs, + ) -> "BaseTrainer": + """Restores a Train experiment from a previously interrupted/failed run. + + Restore should be used for experiment-level fault tolerance in the event + that the head node crashes (e.g., OOM or some other runtime error) or the + entire cluster goes down (e.g., network error affecting all nodes). + + A run that has already completed successfully will not be resumed from this API. + To continue training from a successful run, launch a new run with the + ``Trainer(resume_from_checkpoint)`` API instead, passing in a + checkpoint from the previous run to start with. + + .. note:: + + Restoring an experiment from a path that's pointing to a *different* + location than the original experiment path is supported. However, Ray Train + assumes that the full experiment directory is available + (including checkpoints) so that it's possible to resume trials from their + latest state. + + For example, if the original experiment path was run locally, then the + results are uploaded to cloud storage, Ray Train expects the full contents + to be available in cloud storage if attempting to resume + via ``Trainer.restore("s3://...")``. The restored run will + continue writing results to the same cloud storage location. + + The following example can be paired with implementing job retry using + :ref:`Ray Jobs ` to produce a Train experiment that will + attempt to resume on both experiment-level and trial-level failures: + + .. testcode:: + + import os + import ray + from ray import train + from ray.train.trainer import BaseTrainer + + experiment_name = "unique_experiment_name" + storage_path = os.path.expanduser("~/ray_results") + experiment_dir = os.path.join(storage_path, experiment_name) + + # Define some dummy inputs for demonstration purposes + datasets = {"train": ray.data.from_items([{"a": i} for i in range(10)])} + + class CustomTrainer(BaseTrainer): + def training_loop(self): + pass + + if CustomTrainer.can_restore(experiment_dir): + trainer = CustomTrainer.restore( + experiment_dir, datasets=datasets + ) + else: + trainer = CustomTrainer( + datasets=datasets, + run_config=train.RunConfig( + name=experiment_name, + storage_path=storage_path, + # Tip: You can also enable retries on failure for + # worker-level fault tolerance + failure_config=train.FailureConfig(max_failures=3), + ), + ) + + result = trainer.fit() + + .. testoutput:: + :hide: + + ... + + Args: + path: The path to the experiment directory of the training run to restore. + This can be a local path or a remote URI if the experiment was + uploaded to the cloud. + storage_filesystem: Custom ``pyarrow.fs.FileSystem`` + corresponding to the ``path``. This may be necessary if the original + experiment passed in a custom filesystem. + datasets: Re-specified datasets used in the original training run. + This must include all the datasets that were passed in the + original trainer constructor. + scaling_config: Optionally re-specified scaling config. This can be + modified to be different from the original spec. + **kwargs: Other optionally re-specified arguments, passed in by subclasses. + + Raises: + ValueError: If all datasets were not re-supplied on restore. + + Returns: + BaseTrainer: A restored instance of the class that is calling this method. + """ + if _v2_migration_warnings_enabled(): + _log_deprecation_warning(_TRAINER_RESTORE_DEPRECATION_WARNING) + + if not cls.can_restore(path, storage_filesystem): + raise ValueError( + f"Invalid restore path: {path}. Make sure that this path exists and " + "is the experiment directory that results from a call to " + "`trainer.fit()`." + ) + fs, fs_path = get_fs_and_path(path, storage_filesystem) + trainer_pkl_path = Path(fs_path, _TRAINER_PKL).as_posix() + with fs.open_input_file(trainer_pkl_path) as f: + trainer_cls, param_dict = pickle.loads(f.readall()) + + if trainer_cls is not cls: + warnings.warn( + f"Invalid trainer type. You are attempting to restore a trainer of type" + f" {trainer_cls} with `{cls.__name__}.restore`, " + "which will most likely fail. " + f"Use `{trainer_cls.__name__}.restore` instead." + ) + + original_datasets = param_dict.pop("datasets", {}) + if original_datasets and not datasets: + raise ValueError( + "The following datasets need to be provided again on restore: " + f"{list(original_datasets.keys())}\n" + f"Use {cls.__name__}.restore(..., datasets=datasets) " + "with the datasets that were provided to the original trainer." + ) + datasets = datasets or {} + if set(original_datasets) != set(datasets): + raise ValueError( + "The provided datasets don't match the original dataset keys.\n" + f" Expected datasets for the keys: {list(original_datasets.keys())}\n" + f" Actual datasets provided: {list(datasets.keys())}" + ) + param_dict["datasets"] = datasets + + if scaling_config: + param_dict["scaling_config"] = scaling_config + + for param_name, val in kwargs.items(): + # Overwrite the old value if something is passed into restore + if val is not None: + param_dict[param_name] = val + + try: + trainer = cls(**param_dict) + except Exception as e: + raise ValueError( + "Trainer restoration failed (see above for the stack trace). " + "Make sure that you use the right trainer class to restore: " + f"`{cls.__name__}.restore`\n" + ) from e + trainer._restore_path = path + trainer._restore_storage_filesystem = storage_filesystem + return trainer + + @classmethod + @Deprecated( + message=_TRAINER_RESTORE_DEPRECATION_WARNING, + warning=_v2_migration_warnings_enabled(), + ) + def can_restore( + cls: Type["BaseTrainer"], + path: Union[str, os.PathLike], + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + ) -> bool: + """Checks whether a given directory contains a restorable Train experiment. + + Args: + path: The path to the experiment directory of the Train experiment. + This can be either a local directory (e.g., ~/ray_results/exp_name) + or a remote URI (e.g., s3://bucket/exp_name). + + Returns: + bool: Whether this path exists and contains the trainer state to resume from + """ + if _v2_migration_warnings_enabled(): + _log_deprecation_warning(_TRAINER_RESTORE_DEPRECATION_WARNING) + + fs, fs_path = get_fs_and_path(path, storage_filesystem) + trainer_pkl_path = Path(fs_path, _TRAINER_PKL).as_posix() + return _exists_at_fs_path(fs, trainer_pkl_path) + + def __repr__(self): + # A dictionary that maps parameters to their default values. + default_values: Dict[str, Any] = { + "scaling_config": ScalingConfig(), + "run_config": RunConfig(), + "datasets": {}, + "starting_checkpoint": None, + } + + non_default_arguments = [] + for parameter, default_value in default_values.items(): + value = getattr(self, parameter) + if value != default_value: + non_default_arguments.append(f"{parameter}={value!r}") + + if non_default_arguments: + return f"<{self.__class__.__name__} {' '.join(non_default_arguments)}>" + + return f"<{self.__class__.__name__}>" + + def __new__(cls, *args, **kwargs): + # Store the init args as attributes so this can be merged with Tune hparams. + trainer = super(BaseTrainer, cls).__new__(cls) + parameters = inspect.signature(cls.__init__).parameters + parameters = list(parameters.keys()) + # Remove self. + parameters = parameters[1:] + arg_dict = dict(zip(parameters, args)) + trainer._param_dict = {**arg_dict, **kwargs} + return trainer + + def _validate_attributes(self): + """Called on __init()__ to validate trainer attributes.""" + # Run config + if not isinstance(self.run_config, RunConfig): + raise ValueError( + f"`run_config` should be an instance of `ray.train.RunConfig`, " + f"found {type(self.run_config)} with value `{self.run_config}`." + ) + # Scaling config + if not isinstance(self.scaling_config, ScalingConfig): + raise ValueError( + "`scaling_config` should be an instance of `ScalingConfig`, " + f"found {type(self.scaling_config)} with value `{self.scaling_config}`." + ) + # Datasets + if not isinstance(self.datasets, dict): + raise ValueError( + f"`datasets` should be a dict mapping from a string to " + f"`ray.data.Dataset` objects, " + f"found {type(self.datasets)} with value `{self.datasets}`." + ) + else: + for key, dataset in self.datasets.items(): + if not isinstance(dataset, ray.data.Dataset) and not callable(dataset): + raise ValueError( + f"The Dataset under '{key}' key is not a " + "`ray.data.Dataset`. " + f"Received {dataset} instead." + ) + # Metadata. + self.metadata = self.metadata or {} + if not isinstance(self.metadata, dict): + raise TypeError( + f"The provided metadata must be a dict, was {type(self.metadata)}." + ) + try: + self.metadata = json.loads(json.dumps(self.metadata)) + except Exception as e: + raise ValueError( + "The provided metadata must be JSON-serializable: " + f"{self.metadata}: {e}" + ) + + if self.starting_checkpoint is not None and not isinstance( + self.starting_checkpoint, Checkpoint + ): + raise ValueError( + f"`resume_from_checkpoint` should be an instance of " + f"`ray.train.Checkpoint`, found {type(self.starting_checkpoint)} " + f"with value `{self.starting_checkpoint}`." + ) + + self._log_v2_deprecation_warnings() + + def _log_v2_deprecation_warnings(self): + """Logs deprecation warnings for v2 migration. + + Log them here in the Ray Train case rather than in the configuration + constructors to avoid logging incorrect deprecation warnings when + `ray.train.RunConfig` is passed to Ray Tune. + """ + + if not _v2_migration_warnings_enabled(): + return + + from ray.train.v2._internal.migration_utils import ( + CALLBACKS_DEPRECATION_MESSAGE, + FAIL_FAST_DEPRECATION_MESSAGE, + LOG_TO_FILE_DEPRECATION_MESSAGE, + PROGRESS_REPORTER_DEPRECATION_MESSAGE, + STOP_DEPRECATION_MESSAGE, + SYNC_CONFIG_DEPRECATION_MESSAGE, + TRAINER_RESOURCES_DEPRECATION_MESSAGE, + VERBOSE_DEPRECATION_MESSAGE, + ) + + # ScalingConfig deprecations + if self.scaling_config.trainer_resources is not None: + _log_deprecation_warning(TRAINER_RESOURCES_DEPRECATION_MESSAGE) + + # FailureConfig deprecations + if self.run_config.failure_config.fail_fast: + _log_deprecation_warning(FAIL_FAST_DEPRECATION_MESSAGE) + + # RunConfig deprecations + # NOTE: _verbose is the original verbose value passed by the user + if self.run_config._verbose is not None: + _log_deprecation_warning(VERBOSE_DEPRECATION_MESSAGE) + + if self.run_config.log_to_file: + _log_deprecation_warning(LOG_TO_FILE_DEPRECATION_MESSAGE) + + if self.run_config.stop is not None: + _log_deprecation_warning(STOP_DEPRECATION_MESSAGE) + + if self.run_config.callbacks is not None: + _log_deprecation_warning(CALLBACKS_DEPRECATION_MESSAGE) + + if self.run_config.progress_reporter is not None: + _log_deprecation_warning(PROGRESS_REPORTER_DEPRECATION_MESSAGE) + + if self.run_config.sync_config != ray.train.SyncConfig(): + _log_deprecation_warning(SYNC_CONFIG_DEPRECATION_MESSAGE) + + @classmethod + def _validate_scaling_config(cls, scaling_config: ScalingConfig) -> ScalingConfig: + """Returns scaling config dataclass after validating updated keys.""" + ensure_only_allowed_dataclass_keys_updated( + dataclass=scaling_config, + allowed_keys=cls._scaling_config_allowed_keys, + ) + return scaling_config + + def setup(self) -> None: + """Called during fit() to perform initial setup on the Trainer. + + .. note:: This method is run on a remote process. + + This method will not be called on the driver, so any expensive setup + operations should be placed here and not in ``__init__``. + + This method is called prior to ``preprocess_datasets`` and + ``training_loop``. + """ + pass + + def preprocess_datasets(self) -> None: + """Deprecated.""" + raise DeprecationWarning( + "`preprocess_datasets` is no longer used, since preprocessors " + f"are no longer accepted by Trainers.\n{PREPROCESSOR_DEPRECATION_MESSAGE}" + ) + + @abc.abstractmethod + def training_loop(self) -> None: + """Loop called by fit() to run training and report results to Tune. + + .. note:: This method runs on a remote process. + + ``self.datasets`` have already been evaluated if they were wrapped in a factory. + + You can use the :ref:`Ray Train utilities ` + (:func:`train.report() ` and + :func:`train.get_checkpoint() `) inside + this training loop. + + Example: + + .. testcode:: + + from ray.train.trainer import BaseTrainer + from ray import train + + class MyTrainer(BaseTrainer): + def training_loop(self): + for epoch_idx in range(5): + ... + train.report({"epoch": epoch_idx}) + + """ + raise NotImplementedError + + @PublicAPI(stability="beta") + def fit(self) -> Result: + """Runs training. + + Returns: + A Result object containing the training result. + + Raises: + ray.train.base_trainer.TrainingFailedError: If any failures during the execution + of ``self.as_trainable()``, or during the Tune execution loop. + """ + from ray.tune import ResumeConfig, TuneError + from ray.tune.tuner import Tuner + + trainable = self.as_trainable() + param_space = self._extract_fields_for_tuner_param_space() + + self.run_config.name = ( + self.run_config.name or StorageContext.get_experiment_dir_name(trainable) + ) + # The storage context here is only used to access the resolved + # storage fs and experiment path, in order to avoid duplicating that logic. + # This is NOT the storage context object that gets passed to remote workers. + storage = StorageContext( + storage_path=self.run_config.storage_path, + experiment_dir_name=self.run_config.name, + storage_filesystem=self.run_config.storage_filesystem, + ) + + if self._restore_path: + tuner = Tuner.restore( + path=self._restore_path, + trainable=trainable, + param_space=param_space, + _resume_config=ResumeConfig( + finished=ResumeConfig.ResumeType.RESUME, + unfinished=ResumeConfig.ResumeType.RESUME, + errored=ResumeConfig.ResumeType.RESUME, + ), + storage_filesystem=self._restore_storage_filesystem, + ) + else: + tuner = Tuner( + trainable=trainable, + param_space=param_space, + run_config=self.run_config, + _entrypoint=AirEntrypoint.TRAINER, + ) + + self._save(storage.storage_filesystem, storage.experiment_fs_path) + + restore_msg = TrainingFailedError._RESTORE_MSG.format( + trainer_cls_name=self.__class__.__name__, + path=str(storage.experiment_fs_path), + ) + + try: + result_grid = tuner.fit() + except TuneError as e: + # Catch any `TuneError`s raised by the `Tuner.fit` call. + # Unwrap the `TuneError` if needed. + parent_error = e.__cause__ or e + + # Raise it to the user as a `TrainingFailedError` with a message to restore. + raise TrainingFailedError(restore_msg) from parent_error + # Other exceptions get passed through directly (ex: on `fail_fast='raise'`) + + assert len(result_grid) == 1 + result = result_grid[0] + if result.error: + # Raise trainable errors to the user with a message to restore + # or configure `FailureConfig` in a new run. + raise TrainingFailedError( + "\n".join([restore_msg, TrainingFailedError._FAILURE_CONFIG_MSG]) + ) from result.error + return result + + def _save(self, fs: pyarrow.fs.FileSystem, experiment_path: str): + """Saves the current trainer's class along with the `param_dict` of + parameters passed to this trainer's constructor. + + This is used to recreate the trainer on restore. + Unless a parameter is re-specified during restoration (only a subset + of parameters can be passed in again), that parameter will be loaded + from the saved copy. + + Datasets should not be saved as part of the state. Instead, we save the + keys and replace the dataset values with dummy functions that will + raise an error if invoked. The error only serves as a guardrail for + misuse (e.g., manually unpickling and constructing the Trainer again) + and is not typically surfaced, since datasets must be re-specified + upon restoration. + """ + param_dict = self._param_dict.copy() + datasets = param_dict.pop("datasets", {}) + + def raise_fn(): + raise RuntimeError + + if datasets: + param_dict["datasets"] = { + dataset_name: raise_fn for dataset_name in datasets + } + + cls_and_param_dict = (self.__class__, param_dict) + + fs.create_dir(experiment_path) + with fs.open_output_stream(Path(experiment_path, _TRAINER_PKL).as_posix()) as f: + f.write(pickle.dumps(cls_and_param_dict)) + + def _extract_fields_for_tuner_param_space(self) -> Dict: + """Extracts fields to be included in `Tuner.param_space`. + + This is needed to leverage the full logging/integration offerings from Tune. + For example, `param_space` is logged automatically to wandb integration. + + Currently only done for `train_loop_config`. + + Returns: + A dictionary that should be passed to Tuner.param_space. + """ + result = {} + for key in self._fields_for_tuner_param_space: + if key in self._param_dict.keys(): + result[key] = copy.deepcopy(self._param_dict[key]) + return result + + def _generate_trainable_cls(self) -> Type["Trainable"]: + """Generates the base Trainable class. + + Returns: + A Trainable class to use for training. + """ + + from ray.tune.execution.placement_groups import PlacementGroupFactory + from ray.tune.trainable import wrap_function + + trainer_cls = self.__class__ + scaling_config = self.scaling_config + metadata = self.metadata + + train_coordinator_fn = partial( + _train_coordinator_fn, trainer_cls=trainer_cls, metadata=metadata + ) + # Change the name of the training function to match the name of the Trainer + # class. This will mean the Tune trial name will match the name of Trainer on + # stdout messages and the results directory. + train_coordinator_fn.__name__ = trainer_cls.__name__ + + trainable_cls = wrap_function(train_coordinator_fn) + has_base_dataset = bool(self.datasets) + if has_base_dataset: + from ray.data.context import DataContext + + dataset_context = DataContext.get_current() + else: + dataset_context = None + + class TrainTrainable(trainable_cls): + """Adds default resources to the Trainable.""" + + _handles_checkpoint_freq = trainer_cls._handles_checkpoint_freq + _handles_checkpoint_at_end = trainer_cls._handles_checkpoint_at_end + + @classmethod + def has_base_dataset(cls) -> bool: + """Whether a dataset is provided through the Trainer.""" + return has_base_dataset + + @classmethod + def base_scaling_config(cls) -> ScalingConfig: + """Returns the unchanged scaling config provided through the Trainer.""" + return scaling_config + + def setup(self, config, **kwargs): + base_config = dict(kwargs) + # Merge Tuner param space hyperparameters in `config` into the + # base config passed to the Trainer constructor, which is `base_config`. + # `base_config` is pulled from the object store from the usage of + # tune.with_parameters in `BaseTrainer.as_trainable`. + + # run_config is not a tunable hyperparameter so it does not need to be + # merged. + run_config = base_config.pop("run_config", None) + self._merged_config = deep_update( + base_config, self.config, new_keys_allowed=True + ) + self._merged_config["run_config"] = run_config + merged_scaling_config = self._merged_config.get( + "scaling_config", ScalingConfig() + ) + if isinstance(merged_scaling_config, dict): + merged_scaling_config = ScalingConfig(**merged_scaling_config) + self._merged_config[ + "scaling_config" + ] = self._reconcile_scaling_config_with_trial_resources( + merged_scaling_config + ) + if self.has_base_dataset(): + # Set the DataContext on the Trainer actor to the DataContext + # specified on the driver. + DataContext._set_current(dataset_context) + super(TrainTrainable, self).setup(config) + + def _reconcile_scaling_config_with_trial_resources( + self, scaling_config: ScalingConfig + ) -> ScalingConfig: + """ + ResourceChangingScheduler workaround. + + Ensures that the scaling config matches trial resources. + + This should be replaced with RCS returning a ScalingConfig + in the future. + """ + + trial_resources = self.trial_resources + # This will be false if the resources are default + if not isinstance(trial_resources, PlacementGroupFactory): + return scaling_config + + # Ignore ResourceChangingScheduler workaround when resource bundles + # are unchanged + if self.trial_resources == scaling_config.as_placement_group_factory(): + return scaling_config + + trainer_cls._validate_scaling_config(scaling_config) + + return ScalingConfig.from_placement_group_factory(trial_resources) + + def _trainable_func(self, config): + # We ignore the config passed by Tune and instead use the merged + # config which includes the initial Trainer args. + super()._trainable_func(self._merged_config) + + @classmethod + def default_resource_request(cls, config): + # `config["scaling_config"] is a dataclass when passed via the + # `scaling_config` argument in `Trainer` and is a dict when passed + # via the `scaling_config` key of `param_spec`. + + # Conversion logic must be duplicated in `TrainTrainable.__init__` + # because this is a class method. + updated_scaling_config = config.get("scaling_config", scaling_config) + if isinstance(updated_scaling_config, dict): + updated_scaling_config = ScalingConfig(**updated_scaling_config) + validated_scaling_config = trainer_cls._validate_scaling_config( + updated_scaling_config + ) + return validated_scaling_config.as_placement_group_factory() + + return TrainTrainable + + def as_trainable(self) -> Type["Trainable"]: + """Converts self to a ``tune.Trainable`` class.""" + from ray import tune + + base_config = self._param_dict + trainable_cls = self._generate_trainable_cls() + + # Wrap with `tune.with_parameters` to handle very large values in base_config + return tune.with_parameters(trainable_cls, **base_config) diff --git a/venv/lib/python3.10/site-packages/ray/train/collective/__init__.py b/venv/lib/python3.10/site-packages/ray/train/collective/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6cffcda40d745eb695e24db0959c3e8ab2134d18 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/collective/__init__.py @@ -0,0 +1,19 @@ +from ray.train.v2._internal.constants import is_v2_enabled + +if is_v2_enabled(): + from ray.train.collective.collectives import barrier, broadcast_from_rank_zero + + __all__ = [ + "broadcast_from_rank_zero", + "barrier", + ] + + broadcast_from_rank_zero.__module__ = "ray.train.collective" + barrier.__module__ = "ray.train.collective" +else: + raise ImportError( + "`ray.train.collective` is only available in Ray Train v2. " + "To enable it, please set `RAY_TRAIN_V2_ENABLED=1`." + ) + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/collective/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/collective/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d704b553292f206399cb6eb3c027daa130eda54 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/collective/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/collective/__pycache__/collectives.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/collective/__pycache__/collectives.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1f732bb914f80cf91a98f71f6d007ef8af27c56 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/collective/__pycache__/collectives.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/collective/collectives.py b/venv/lib/python3.10/site-packages/ray/train/collective/collectives.py new file mode 100644 index 0000000000000000000000000000000000000000..c35c43564bbe38e40e7e8ac868ad864f31d7c691 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/collective/collectives.py @@ -0,0 +1,115 @@ +import logging +from typing import Optional, TypeVar + +import ray +import ray.cloudpickle as pickle +from ray.train.v2._internal.execution.context import get_train_context +from ray.util.annotations import PublicAPI + +# For reference, {1:1} is 19 bytes, {"1":"1"} is 21 bytes, +# and {"12345": "12345"} is 25 bytes. +_MAX_BROADCAST_SIZE_BYTES = 1000 + +T = TypeVar("T", bound=Optional[object]) + + +logger = logging.getLogger(__file__) + + +@PublicAPI(stability="alpha") +def broadcast_from_rank_zero(data: T) -> T: + """Broadcast small (<1kb) data from the rank 0 worker to all other workers. + + Serves as a barrier, meaning that all workers must call this method before + the training function can continue. + + Example: + + .. testcode: + :skipif: True + + from ray.train import get_context + from ray.train.collective import broadcast_from_rank_zero + from ray.train.torch import TorchTrainer + + def train_func(): + ... + if get_context().get_world_rank() == 0: + data = {"some_key": "some_value"} + else: + data = None + data = broadcast_from_rank_zero(data) + ... + + trainer = TorchTrainer(train_func) + trainer.fit() + + Args: + data: The small (1kb) data to broadcast from the rank 0 worker to all + other workers. + + Returns: + The data broadcasted from the rank 0 worker. + + Raises: + ValueError: If the data is too big. + pickle.PicklingError: If the data is not pickleable. + TypeError: If the data is not pickleable. + """ + # Validate data. + if data is not None: + data_bytes = len(pickle.dumps(data)) + if data_bytes > _MAX_BROADCAST_SIZE_BYTES: + logger.warning( + f"Data size {data_bytes} bytes exceeds the maximum broadcast " + f"size of {_MAX_BROADCAST_SIZE_BYTES} bytes" + ) + + # Send data to all workers. + train_context = get_train_context() + sync_actor = train_context.get_synchronization_actor() + return ray.get( + sync_actor.broadcast_from_rank_zero.remote( + world_rank=train_context.get_world_rank(), + world_size=train_context.get_world_size(), + data=data, + caller_method_name="ray.train.collective.broadcast_from_rank_zero", + ) + ) + + +@PublicAPI(stability="alpha") +def barrier() -> None: + """Create a barrier across all workers. + + All workers must call this method before the training function can continue. + + Example: + + .. testcode: + :skipif: True + + from ray.train import get_context + from ray.train.collective import barrier + from ray.train.torch import TorchTrainer + + def train_func(): + ... + print(f"Rank {get_context().get_world_rank()} is waiting at the barrier.") + barrier() + print(f"Rank {get_context().get_world_rank()} has passed the barrier.") + ... + + trainer = TorchTrainer(train_func) + trainer.fit() + """ + train_context = get_train_context() + sync_actor = train_context.get_synchronization_actor() + return ray.get( + sync_actor.broadcast_from_rank_zero.remote( + world_rank=train_context.get_world_rank(), + world_size=train_context.get_world_size(), + data=None, + caller_method_name="ray.train.collective.barrier", + ) + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/constants.py b/venv/lib/python3.10/site-packages/ray/train/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..d444e2cf046135e873f8e251752c5dcee58c9b2a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/constants.py @@ -0,0 +1,132 @@ +from pathlib import Path + +import ray +from ray._private.ray_constants import env_bool +from ray.air.constants import ( # noqa: F401 + COPY_DIRECTORY_CHECKPOINTS_INSTEAD_OF_MOVING_ENV, + EVALUATION_DATASET_KEY, + MODEL_KEY, + PREPROCESSOR_KEY, + TRAIN_DATASET_KEY, +) + + +def _get_ray_train_session_dir() -> str: + assert ray.is_initialized(), "Ray must be initialized to get the session dir." + return Path( + ray._private.worker._global_node.get_session_dir_path(), "artifacts" + ).as_posix() + + +DEFAULT_STORAGE_PATH = Path("~/ray_results").expanduser().as_posix() + +# Autofilled ray.train.report() metrics. Keys should be consistent with Tune. +CHECKPOINT_DIR_NAME = "checkpoint_dir_name" +TIME_TOTAL_S = "_time_total_s" +WORKER_HOSTNAME = "_hostname" +WORKER_NODE_IP = "_node_ip" +WORKER_PID = "_pid" + +# Will not be reported unless ENABLE_DETAILED_AUTOFILLED_METRICS_ENV +# env var is not 0 +DETAILED_AUTOFILLED_KEYS = {WORKER_HOSTNAME, WORKER_NODE_IP, WORKER_PID, TIME_TOTAL_S} + +# Default filename for JSON logger +RESULT_FILE_JSON = "results.json" + +# The name of the subdirectory inside the trainer run_dir to store checkpoints. +TRAIN_CHECKPOINT_SUBDIR = "checkpoints" + +# The key to use to specify the checkpoint id for Tune. +# This needs to be added to the checkpoint dictionary so if the Tune trial +# is restarted, the checkpoint_id can continue to increment. +TUNE_CHECKPOINT_ID = "_current_checkpoint_id" + +# Deprecated configs can use this value to detect if the user has set it. +_DEPRECATED_VALUE = "DEPRECATED" + + +# ================================================== +# Train V2 constants +# ================================================== + +# Set this to 1 to enable deprecation warnings for V2 migration. +ENABLE_V2_MIGRATION_WARNINGS_ENV_VAR = "RAY_TRAIN_ENABLE_V2_MIGRATION_WARNINGS" + + +V2_MIGRATION_GUIDE_MESSAGE = ( + "See this issue for more context and migration options: " + "https://github.com/ray-project/ray/issues/49454. " + "Disable these warnings by setting the environment variable: " + f"{ENABLE_V2_MIGRATION_WARNINGS_ENV_VAR}=0" +) + + +def _v2_migration_warnings_enabled() -> bool: + return env_bool(ENABLE_V2_MIGRATION_WARNINGS_ENV_VAR, True) + + +# ================================================== +# Environment Variables +# ================================================== + +ENABLE_DETAILED_AUTOFILLED_METRICS_ENV = ( + "TRAIN_RESULT_ENABLE_DETAILED_AUTOFILLED_METRICS" +) + +# Integer value which if set will override the value of +# Backend.share_cuda_visible_devices. 1 for True, 0 for False. +ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV = "TRAIN_ENABLE_SHARE_CUDA_VISIBLE_DEVICES" + +# Integer value which if set will not share HIP accelerator visible devices +# across workers. 1 for True (default), 0 for False. +ENABLE_SHARE_HIP_VISIBLE_DEVICES_ENV = "TRAIN_ENABLE_SHARE_HIP_VISIBLE_DEVICES" + +# Integer value which if set will not share neuron-core accelerator visible cores +# across workers. 1 for True (default), 0 for False. +ENABLE_SHARE_NEURON_CORES_ACCELERATOR_ENV = ( + "TRAIN_ENABLE_SHARE_NEURON_CORES_ACCELERATOR" +) + +# Integer value which if set will not share npu visible devices +# across workers. 1 for True (default), 0 for False. +ENABLE_SHARE_NPU_RT_VISIBLE_DEVICES_ENV = "TRAIN_ENABLE_SHARE_ASCEND_RT_VISIBLE_DEVICES" + +# Integer value which indicates the number of seconds to wait when creating +# the worker placement group before timing out. +TRAIN_PLACEMENT_GROUP_TIMEOUT_S_ENV = "TRAIN_PLACEMENT_GROUP_TIMEOUT_S" + +# Integer value which if set will change the placement group strategy from +# PACK to SPREAD. 1 for True, 0 for False. +TRAIN_ENABLE_WORKER_SPREAD_ENV = "TRAIN_ENABLE_WORKER_SPREAD" + +# Set this to 0 to disable changing the working directory of each Tune Trainable +# or Train worker to the trial directory. Defaults to 1. +RAY_CHDIR_TO_TRIAL_DIR = "RAY_CHDIR_TO_TRIAL_DIR" + +# Set this to 1 to count preemption errors toward `FailureConfig(max_failures)`. +# Defaults to 0, which always retries on node preemption failures. +RAY_TRAIN_COUNT_PREEMPTION_AS_FAILURE = "RAY_TRAIN_COUNT_PREEMPTION_AS_FAILURE" + +# Set this to 1 to start a StateActor and collect information Train Runs +# Defaults to 0 +RAY_TRAIN_ENABLE_STATE_TRACKING = "RAY_TRAIN_ENABLE_STATE_TRACKING" + + +# NOTE: When adding a new environment variable, please track it in this list. +TRAIN_ENV_VARS = { + ENABLE_DETAILED_AUTOFILLED_METRICS_ENV, + ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV, + ENABLE_SHARE_NEURON_CORES_ACCELERATOR_ENV, + TRAIN_PLACEMENT_GROUP_TIMEOUT_S_ENV, + TRAIN_ENABLE_WORKER_SPREAD_ENV, + RAY_CHDIR_TO_TRIAL_DIR, + RAY_TRAIN_COUNT_PREEMPTION_AS_FAILURE, + RAY_TRAIN_ENABLE_STATE_TRACKING, +} + +# Key for AIR Checkpoint metadata in TrainingResult metadata +CHECKPOINT_METADATA_KEY = "checkpoint_metadata" + +# Key for AIR Checkpoint world rank in TrainingResult metadata +CHECKPOINT_RANK_KEY = "checkpoint_rank" diff --git a/venv/lib/python3.10/site-packages/ray/train/context.py b/venv/lib/python3.10/site-packages/ray/train/context.py new file mode 100644 index 0000000000000000000000000000000000000000..7aefb4b9005544bd8ce3e9c1f8d4e78659dee87c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/context.py @@ -0,0 +1,144 @@ +import threading +from typing import TYPE_CHECKING, Any, Dict, Optional + +from ray.train._internal import session +from ray.train._internal.storage import StorageContext +from ray.train.constants import ( + V2_MIGRATION_GUIDE_MESSAGE, + _v2_migration_warnings_enabled, +) +from ray.train.utils import _copy_doc, _log_deprecation_warning +from ray.util.annotations import Deprecated, DeveloperAPI, PublicAPI + +if TYPE_CHECKING: + from ray.tune.execution.placement_groups import PlacementGroupFactory + + +# The context singleton on this process. +_default_context: "Optional[TrainContext]" = None +_context_lock = threading.Lock() + + +_GET_METADATA_DEPRECATION_MESSAGE = ( + "`get_metadata` was an experimental API that accessed the metadata passed " + "to `Trainer(metadata=...)`. This API can be replaced by passing " + "the metadata directly to the training function (e.g., via `train_loop_config`). " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) + +_TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE = ( + "`{}` is deprecated because the concept of a `Trial` will " + "soon be removed in Ray Train." + "Ray Train will no longer assume that it's running within a Ray Tune `Trial` " + "in the future. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) + + +@PublicAPI(stability="stable") +class TrainContext: + """Context containing metadata that can be accessed within Ray Train workers.""" + + @_copy_doc(session.get_experiment_name) + def get_experiment_name(self) -> str: + return session.get_experiment_name() + + @_copy_doc(session.get_world_size) + def get_world_size(self) -> int: + return session.get_world_size() + + @_copy_doc(session.get_world_rank) + def get_world_rank(self) -> int: + return session.get_world_rank() + + @_copy_doc(session.get_local_rank) + def get_local_rank(self) -> int: + return session.get_local_rank() + + @_copy_doc(session.get_local_world_size) + def get_local_world_size(self) -> int: + return session.get_local_world_size() + + @_copy_doc(session.get_node_rank) + def get_node_rank(self) -> int: + return session.get_node_rank() + + @DeveloperAPI + @_copy_doc(session.get_storage) + def get_storage(self) -> StorageContext: + return session.get_storage() + + # Deprecated APIs + + @Deprecated( + message=_GET_METADATA_DEPRECATION_MESSAGE, + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(session.get_metadata) + def get_metadata(self) -> Dict[str, Any]: + return session.get_metadata() + + @Deprecated( + message=_TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_trial_name"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(session.get_trial_name) + def get_trial_name(self) -> str: + return session.get_trial_name() + + @Deprecated( + message=_TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_trial_id"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(session.get_trial_id) + def get_trial_id(self) -> str: + return session.get_trial_id() + + @Deprecated( + message=_TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format( + "get_trial_resources" + ), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(session.get_trial_resources) + def get_trial_resources(self) -> "PlacementGroupFactory": + return session.get_trial_resources() + + @Deprecated( + message=_TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_trial_dir"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(session.get_trial_dir) + def get_trial_dir(self) -> str: + return session.get_trial_dir() + + +@PublicAPI(stability="stable") +def get_context() -> TrainContext: + """Get or create a singleton training context. + + The context is only available within a function passed to Ray Train. + + See the :class:`~ray.train.TrainContext` API reference to see available methods. + """ + from ray.tune.trainable.trainable_fn_utils import _in_tune_session + + # If we are running in a Tune function, switch to Tune context. + if _in_tune_session(): + from ray.tune import get_context as get_tune_context + + if _v2_migration_warnings_enabled(): + _log_deprecation_warning( + "`ray.train.get_context()` should be switched to " + "`ray.tune.get_context()` when running in a function " + "passed to Ray Tune. This will be an error in the future. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" + ) + return get_tune_context() + + global _default_context + + with _context_lock: + if _default_context is None: + _default_context = TrainContext() + return _default_context diff --git a/venv/lib/python3.10/site-packages/ray/train/data_parallel_trainer.py b/venv/lib/python3.10/site-packages/ray/train/data_parallel_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..f2e6d5a5e6317cfbb85970422ab826f48101961e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/data_parallel_trainer.py @@ -0,0 +1,586 @@ +import logging +import uuid +from typing import Any, Callable, Dict, List, Optional, Type, Union + +import ray +from ray._private.ray_constants import env_integer +from ray._private.thirdparty.tabulate.tabulate import tabulate +from ray.air.config import RunConfig, ScalingConfig +from ray.train import BackendConfig, Checkpoint, TrainingIterator +from ray.train._internal import session +from ray.train._internal.backend_executor import BackendExecutor, TrialInfo +from ray.train._internal.data_config import DataConfig +from ray.train._internal.session import _TrainingResult, get_session +from ray.train._internal.utils import construct_train_func, count_required_parameters +from ray.train.base_trainer import _TRAINER_RESTORE_DEPRECATION_WARNING +from ray.train.constants import RAY_TRAIN_ENABLE_STATE_TRACKING +from ray.train.trainer import BaseTrainer, GenDataset +from ray.util.annotations import Deprecated, DeveloperAPI +from ray.widgets import Template +from ray.widgets.util import repr_with_fallback + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class DataParallelTrainer(BaseTrainer): + """A Trainer for data parallel training. + + You should subclass this Trainer if your Trainer follows SPMD (single program, + multiple data) programming paradigm - you want multiple processes to run the same + function, but on different data. + + This Trainer runs the function ``train_loop_per_worker`` on multiple Ray + Actors. + + The ``train_loop_per_worker`` function is expected to take in either 0 or 1 + arguments: + + .. testcode:: + + def train_loop_per_worker(): + ... + + .. testcode:: + + def train_loop_per_worker(config: Dict): + ... + + If ``train_loop_per_worker`` accepts an argument, then + ``train_loop_config`` will be passed in as the argument. This is useful if you + want to tune the values in ``train_loop_config`` as hyperparameters. + + If the ``datasets`` dict contains a training dataset (denoted by + the "train" key), then it will be split into multiple dataset + shards that can then be accessed by ``train.get_dataset_shard("train")`` inside + ``train_loop_per_worker``. All the other datasets will not be split and + ``train.get_dataset_shard(...)`` will return the entire Dataset. + + Inside the ``train_loop_per_worker`` function, you can use any of the + :ref:`Ray Train loop methods `. + + .. testcode:: + + from ray import train + + def train_loop_per_worker(): + # Report intermediate results for callbacks or logging and + # checkpoint data. + train.report(...) + + # Returns dict of last saved checkpoint. + train.get_checkpoint() + + # Returns the Dataset shard for the given key. + train.get_dataset_shard("my_dataset") + + # Returns the total number of workers executing training. + train.get_context().get_world_size() + + # Returns the rank of this worker. + train.get_context().get_world_rank() + + # Returns the rank of the worker on the current node. + train.get_context().get_local_rank() + + Any returns from the ``train_loop_per_worker`` will be discarded and not + used or persisted anywhere. + + **How do I use DataParallelTrainer or any of its subclasses?** + + Example: + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.data_parallel_trainer import DataParallelTrainer + + def train_loop_for_worker(): + dataset_shard_for_this_worker = train.get_dataset_shard("train") + + # 3 items for 3 workers, each worker gets 1 item + batches = list(dataset_shard_for_this_worker.iter_batches(batch_size=1)) + assert len(batches) == 1 + + train_dataset = ray.data.from_items([1, 2, 3]) + assert train_dataset.count() == 3 + trainer = DataParallelTrainer( + train_loop_for_worker, + scaling_config=ScalingConfig(num_workers=3), + datasets={"train": train_dataset}, + ) + result = trainer.fit() + + .. testoutput:: + :hide: + + ... + + **How do I develop on top of DataParallelTrainer?** + + In many cases, using DataParallelTrainer directly is sufficient to execute + functions on multiple actors. + + However, you may want to subclass ``DataParallelTrainer`` and create a custom + Trainer for the following 2 use cases: + + - **Use Case 1:** You want to do data parallel training, but want to have + a predefined ``training_loop_per_worker``. + + - **Use Case 2:** You want to implement a custom + :py:class:`~ray.train.backend.Backend` that automatically handles + additional setup or teardown logic on each actor, so that the users of this + new trainer do not have to implement this logic. For example, a + ``TensorflowTrainer`` can be built on top of ``DataParallelTrainer`` + that automatically handles setting the proper environment variables for + distributed Tensorflow on each actor. + + For 1, you can set a predefined training loop in __init__ + + .. testcode:: + + from ray.train.data_parallel_trainer import DataParallelTrainer + + class MyDataParallelTrainer(DataParallelTrainer): + def __init__(self, *args, **kwargs): + predefined_train_loop_per_worker = lambda: 1 + super().__init__(predefined_train_loop_per_worker, *args, **kwargs) + + + For 2, you can implement the ``ray.train.Backend`` and ``ray.train.BackendConfig`` + interfaces. + + .. testcode:: + + from dataclasses import dataclass + from ray.train.backend import Backend, BackendConfig + + class MyBackend(Backend): + def on_start(self, worker_group, backend_config): + def set_env_var(env_var_value): + import os + os.environ["MY_ENV_VAR"] = env_var_value + + worker_group.execute(set_env_var, backend_config.env_var) + + @dataclass + class MyBackendConfig(BackendConfig): + env_var: str = "default_value" + + def backend_cls(self): + return MyBackend + + class MyTrainer(DataParallelTrainer): + def __init__(self, train_loop_per_worker, my_backend_config: + MyBackendConfig, **kwargs): + + super().__init__( + train_loop_per_worker, + backend_config=my_backend_config, **kwargs) + + Args: + train_loop_per_worker: The training function to execute. + This can either take in no arguments or a ``config`` dict. + train_loop_config: Configurations to pass into + ``train_loop_per_worker`` if it accepts an argument. + backend_config: Configuration for setting up a Backend (e.g. Torch, + Tensorflow, Horovod) on each worker to enable distributed + communication. If no Backend should be set up, then set this to None. + scaling_config: Configuration for how to scale data parallel training. + dataset_config: Configuration for dataset ingest. This is merged with the + default dataset config for the given trainer (`cls._dataset_config`). + run_config: Configuration for the execution of the training run. + datasets: Ray Datasets to use for training and evaluation. + This is a dict where the key is the name of the dataset, which + can be accessed from within the ``train_loop_per_worker`` by calling + ``train.get_dataset_shard(dataset_key)``. + By default, all datasets are sharded equally across workers. + This can be configured via ``dataset_config``. + metadata: Dict that should be made available via + `train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + resume_from_checkpoint: A checkpoint to resume training from. + """ + + # Exposed here for testing purposes. Should never need + # to be overriden. + _backend_executor_cls: Type[BackendExecutor] = BackendExecutor + _training_iterator_cls: Type[TrainingIterator] = TrainingIterator + + _scaling_config_allowed_keys = BaseTrainer._scaling_config_allowed_keys + [ + "num_workers", + "resources_per_worker", + "use_gpu", + "placement_strategy", + "accelerator_type", + ] + + # For backwards compatibility with the legacy dataset config API. + _dataset_config = None + + _fields_for_tuner_param_space = BaseTrainer._fields_for_tuner_param_space + [ + "train_loop_config" + ] + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + backend_config: Optional[BackendConfig] = None, + scaling_config: Optional[ScalingConfig] = None, + dataset_config: Optional[DataConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + self._train_loop_per_worker = train_loop_per_worker + self._train_loop_config = train_loop_config + + if dataset_config is None: + dataset_config = DataConfig() + + if not isinstance(dataset_config, DataConfig): + raise ValueError( + "`dataset_config` must be an instance of ray.train.DataConfig, " + f"was: {dataset_config}" + ) + self._data_config = dataset_config + + backend_config = ( + backend_config if backend_config is not None else BackendConfig() + ) + self._backend_config = backend_config + + super(DataParallelTrainer, self).__init__( + scaling_config=scaling_config, + run_config=run_config, + datasets=datasets, + metadata=metadata, + resume_from_checkpoint=resume_from_checkpoint, + ) + + train_total_resources = self.scaling_config.total_resources + self._data_config.set_train_total_resources( + train_total_resources.get("CPU", 0), + train_total_resources.get("GPU", 0), + ) + + if env_integer(RAY_TRAIN_ENABLE_STATE_TRACKING, 0): + from ray.train._internal.state.state_actor import get_or_create_state_actor + + get_or_create_state_actor() + + @classmethod + @Deprecated(message=_TRAINER_RESTORE_DEPRECATION_WARNING) + def restore( + cls, + path: str, + train_loop_per_worker: Optional[ + Union[Callable[[], None], Callable[[Dict], None]] + ] = None, + train_loop_config: Optional[Dict] = None, + **kwargs, + ): + """Restores a DataParallelTrainer from a previously interrupted/failed run. + + Args: + train_loop_per_worker: Optionally re-specified train loop function. + This should be used to re-specify a function that is not + restorable in a new Ray cluster (e.g., it holds onto outdated + object references). This should be the same training loop + that was passed to the original trainer constructor. + train_loop_config: Optionally re-specified train config. + This should similarly be used if the original `train_loop_config` + contained outdated object references, and it should not be modified + from what was originally passed in. + + See :meth:`BaseTrainer.restore() ` + for descriptions of the other arguments. + + Returns a restored instance of the `DataParallelTrainer`. + """ + return super(DataParallelTrainer, cls).restore( + path=path, + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + **kwargs, + ) + + def _validate_attributes(self): + super()._validate_attributes() + + self._validate_train_loop_per_worker( + self._train_loop_per_worker, "train_loop_per_worker" + ) + + def _validate_train_loop_per_worker( + self, train_loop_per_worker: Callable, fn_name: str + ) -> None: + num_required_params = count_required_parameters(train_loop_per_worker) + if num_required_params > 1: + raise ValueError( + f"{fn_name} should take in 0 or 1 arguments, " + f"but it accepts {num_required_params} arguments instead." + ) + + @classmethod + def _validate_scaling_config(cls, scaling_config: ScalingConfig) -> ScalingConfig: + scaling_config = super(DataParallelTrainer, cls)._validate_scaling_config( + scaling_config + ) + + # This validation happens after the scaling config is updated from + # its specification in the Tuner `param_space` + if not scaling_config.use_gpu and "GPU" in ray.available_resources(): + logger.info( + "GPUs are detected in your Ray cluster, but GPU " + "training is not enabled for this trainer. To enable " + "GPU training, make sure to set `use_gpu` to True " + "in your scaling config." + ) + + if scaling_config.num_workers is None: + raise ValueError( + "You must specify the 'num_workers' in `scaling_config` as either an " + f"argument of `{cls.__name__}` or through the `param_space` of a " + "`Tuner` (if performing hyperparameter tuning)." + ) + + if scaling_config.num_workers <= 0: + raise ValueError( + "'num_workers' in `scaling_config` must be a positive " + f"integer. Received {scaling_config.num_workers}" + ) + + return scaling_config + + def _run_training(self, training_iterator: TrainingIterator) -> None: + """This method loops over the `TrainingIterator`: + The actual iteration (for ... in ...) waits for the training function + on each worker to report a result and supplies it as a list of results. + Afterwards (in the body of the loop), it will report the result + to the Tune session. + The iterator ends after the training function on each worker has finished. + """ + for training_results in training_iterator: + # TODO(ml-team): add ability to report results from multiple workers. + self._propagate_results(training_results) + + def _propagate_results(self, training_results: List[_TrainingResult]): + first_worker_result = training_results[0] + assert all(isinstance(result, _TrainingResult) for result in training_results) + + tune_session = get_session() + + # Check if any workers reported a checkpoint. + # If so, report a checkpoint pointing to the persisted location + # to Tune for book-keeping. + # NOTE: This removes the restriction for any individual worker + # (ex: global rank 0 worker) from needing to report a checkpoint. + # All workers reported a checkpoint to the same fs path, so there's + # no need to report multiple checkpoints to Tune. + worker_checkpoints = [ + result.checkpoint + for result in training_results + if result.checkpoint is not None + ] + at_least_one_reported_checkpoint = len(worker_checkpoints) > 0 + + if at_least_one_reported_checkpoint: + # Update the coordinator's checkpoint index to the latest. + # This is what keeps the checkpoint index in line with the workers. + tune_session.storage._update_checkpoint_index(first_worker_result.metrics) + + # Make sure that all workers uploaded to the same location. + assert all( + checkpoint.path == tune_session.storage.checkpoint_fs_path + for checkpoint in worker_checkpoints + ) + + checkpoint = ( + Checkpoint( + filesystem=tune_session.storage.storage_filesystem, + path=tune_session.storage.checkpoint_fs_path, + ) + if at_least_one_reported_checkpoint + else None + ) + + tracked_training_result = _TrainingResult( + checkpoint=checkpoint, + metrics=first_worker_result.metrics, + ) + + logger.debug( + "Report (metrics, checkpoint) to the Tune session:\n" + f" metrics={tracked_training_result.metrics}\n" + f" checkpoint={tracked_training_result.checkpoint}" + ) + + # Report the metrics and checkpoint to Tune. + tune_session._report_training_result(tracked_training_result) + + def training_loop(self) -> None: + scaling_config = self._validate_scaling_config(self.scaling_config) + + train_loop_per_worker = construct_train_func( + self._train_loop_per_worker, + self._train_loop_config, + train_func_context=self._backend_config.train_func_context, + fn_arg_name="train_loop_per_worker", + discard_returns=True, + ) + + trial_info = TrialInfo( + name=session.get_trial_name(), + id=session.get_trial_id(), + resources=session.get_trial_resources(), + logdir=session.get_trial_dir(), + driver_ip=ray.util.get_node_ip_address(), + driver_node_id=ray.get_runtime_context().get_node_id(), + experiment_name=session.get_experiment_name(), + run_id=uuid.uuid4().hex, + ) + + backend_executor = self._backend_executor_cls( + backend_config=self._backend_config, + trial_info=trial_info, + num_workers=scaling_config.num_workers, + resources_per_worker=scaling_config._resources_per_worker_not_none, + max_retries=0, + ) + + # Start the remote actors. + backend_executor.start() + + training_iterator = self._training_iterator_cls( + backend_executor=backend_executor, + backend_config=self._backend_config, + train_func=train_loop_per_worker, + datasets=self.datasets, + metadata=self.metadata, + data_config=self._data_config, + checkpoint=self.starting_checkpoint, + ) + + self._run_training(training_iterator) + + # Shutdown workers. + backend_executor.shutdown() + + def get_dataset_config(self) -> DataConfig: + """Returns a copy of this Trainer's final dataset configs. + + Returns: + The merged default + user-supplied dataset config. + """ + + return self._data_config + + @repr_with_fallback(["ipywidgets", "8"]) + def _repr_mimebundle_(self, **kwargs): + """Returns a mimebundle with an ipywidget repr and a simple text repr. + + Depending on the frontend where the data is being displayed, + different mimetypes will be used from this bundle. + See https://ipython.readthedocs.io/en/stable/config/integrating.html + for information about this method, and + https://ipywidgets.readthedocs.io/en/latest/embedding.html + for more information about the jupyter widget mimetype. + + Returns: + A mimebundle containing an ipywidget repr and a simple text repr. + """ + from ipywidgets import HTML, Layout, Tab, VBox + + title = HTML(f"

{self.__class__.__name__}

") + + children = [] + titles = [] + + if self.datasets: + children.append(self._datasets_repr_()) + titles.append("Datasets") + + children.append(HTML(self._data_config_repr_html_())) + titles.append("Data Config") + + if self._train_loop_config: + children.append(HTML(self._train_loop_config_repr_html_())) + titles.append("Train Loop Config") + + if self.scaling_config: + children.append(HTML(self.scaling_config._repr_html_())) + titles.append("Scaling Config") + + if self.run_config: + children.append(HTML(self.run_config._repr_html_())) + titles.append("Run Config") + + if self._backend_config: + children.append(HTML(self._backend_config._repr_html_())) + titles.append("Backend Config") + + tab = Tab(children, titles=titles) + widget = VBox([title, tab], layout=Layout(width="100%")) + bundle = widget._repr_mimebundle_(**kwargs) + bundle.update( + { + "text/plain": repr(self), + } + ) + return bundle + + def _train_loop_config_repr_html_(self) -> str: + if self._train_loop_config: + table_data = {} + for k, v in self._train_loop_config.items(): + if isinstance(v, str) or str(v).isnumeric(): + table_data[k] = v + elif hasattr(v, "_repr_html_"): + table_data[k] = v._repr_html_() + else: + table_data[k] = str(v) + + return Template("title_data.html.j2").render( + title="Train Loop Config", + data=Template("scrollableTable.html.j2").render( + table=tabulate( + table_data.items(), + headers=["Setting", "Value"], + showindex=False, + tablefmt="unsafehtml", + ), + max_height="none", + ), + ) + else: + return "" + + def _data_config_repr_html_(self) -> str: + # TODO make this rendering nicer. + content = [str(self._data_config)] + return Template("rendered_html_common.html.j2").render(content=content) + + def _datasets_repr_(self) -> str: + from ipywidgets import HTML, Layout, VBox + + content = [] + if self.datasets: + for name, config in self.datasets.items(): + tab = config._tab_repr_() + if tab: + content.append( + HTML( + Template("title_data.html.j2").render( + title=f"Dataset - {name}", data=None + ) + ) + ) + content.append(config._tab_repr_()) + + return VBox(content, layout=Layout(width="100%")) diff --git a/venv/lib/python3.10/site-packages/ray/train/error.py b/venv/lib/python3.10/site-packages/ray/train/error.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa8c82471bbe8c800b2415c8af3b1aef601d00d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/error.py @@ -0,0 +1,6 @@ +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="beta") +class SessionMisuseError(Exception): + """Indicates a method or function was used outside of a session.""" diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/__init__.py b/venv/lib/python3.10/site-packages/ray/train/examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a8104817ceae09ad42c75a882bf3dc72bab7b42 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/__pycache__/mlflow_simple_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/__pycache__/mlflow_simple_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a04f7afe901b5f78101a6b6b70cb2a43ab6e5f0b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/__pycache__/mlflow_simple_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__init__.py b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dbd16ea33c9898fd18b3bb00ca5f638adea12c4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9bf2a959ebee7bbe3adcea2881d0deb4c33ca47 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_pytorch_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_pytorch_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ce1e054d5741ea3bab2d519d9cea9b3f96146e4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_pytorch_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_tune_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_tune_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd1be275cc58139c2ecafe1311b058d439a52b69 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/__pycache__/horovod_tune_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_example.py new file mode 100644 index 0000000000000000000000000000000000000000..236814aa8afccd775c3b67ab96edf8d3da93a0c8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_example.py @@ -0,0 +1,286 @@ +import argparse +import os + +import horovod.torch as hvd +import torch.nn as nn +import torch.nn.functional as F +import torch.optim as optim +import torch.utils.data.distributed +from filelock import FileLock +from torchvision import datasets, transforms + +import ray +from ray import train +from ray.train import ScalingConfig +from ray.train.horovod import HorovodTrainer + + +def metric_average(val, name): + tensor = torch.tensor(val) + avg_tensor = hvd.allreduce(tensor, name=name) + return avg_tensor.item() + + +class Net(nn.Module): + def __init__(self): + super(Net, self).__init__() + self.conv1 = nn.Conv2d(1, 10, kernel_size=5) + self.conv2 = nn.Conv2d(10, 20, kernel_size=5) + self.conv2_drop = nn.Dropout2d() + self.fc1 = nn.Linear(320, 50) + self.fc2 = nn.Linear(50, 10) + + def forward(self, x): + x = F.relu(F.max_pool2d(self.conv1(x), 2)) + x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) + x = x.view(-1, 320) + x = F.relu(self.fc1(x)) + x = F.dropout(x, training=self.training) + x = self.fc2(x) + return F.log_softmax(x) + + +def setup(config): + data_dir = config.get("data_dir", None) + seed = config.get("seed", 42) + batch_size = config.get("batch_size", 64) + use_adasum = config.get("use_adasum", False) + lr = config.get("lr", 0.01) + momentum = config.get("momentum", 0.5) + use_cuda = config.get("use_cuda", False) + + # Horovod: initialize library. + hvd.init() + torch.manual_seed(seed) + + if use_cuda: + # Horovod: pin GPU to local rank. + torch.cuda.set_device(hvd.local_rank()) + torch.cuda.manual_seed(seed) + + # Horovod: limit # of CPU threads to be used per worker. + torch.set_num_threads(1) + + kwargs = {"num_workers": 1, "pin_memory": True} if use_cuda else {} + data_dir = data_dir or "~/data" + with FileLock(os.path.expanduser("~/.horovod_lock")): + train_dataset = datasets.MNIST( + data_dir, + train=True, + download=True, + transform=transforms.Compose( + [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))] + ), + ) + # Horovod: use DistributedSampler to partition the training data. + train_sampler = torch.utils.data.distributed.DistributedSampler( + train_dataset, num_replicas=hvd.size(), rank=hvd.rank() + ) + train_loader = torch.utils.data.DataLoader( + train_dataset, batch_size=batch_size, sampler=train_sampler, **kwargs + ) + + model = Net() + + # By default, Adasum doesn't need scaling up learning rate. + lr_scaler = hvd.size() if not use_adasum else 1 + + if use_cuda: + # Move model to GPU. + model.cuda() + # If using GPU Adasum allreduce, scale learning rate by local_size. + if use_adasum and hvd.nccl_built(): + lr_scaler = hvd.local_size() + + # Horovod: scale learning rate by lr_scaler. + optimizer = optim.SGD(model.parameters(), lr=lr * lr_scaler, momentum=momentum) + + # Horovod: wrap optimizer with DistributedOptimizer. + optimizer = hvd.DistributedOptimizer( + optimizer, + named_parameters=model.named_parameters(), + op=hvd.Adasum if use_adasum else hvd.Average, + ) + + return model, optimizer, train_loader, train_sampler + + +def train_epoch( + model, optimizer, train_sampler, train_loader, epoch, log_interval, use_cuda +): + loss = None + model.train() + # Horovod: set epoch to sampler for shuffling. + train_sampler.set_epoch(epoch) + for batch_idx, (data, target) in enumerate(train_loader): + if use_cuda: + data, target = data.cuda(), target.cuda() + optimizer.zero_grad() + output = model(data) + loss = F.nll_loss(output, target) + loss.backward() + optimizer.step() + if batch_idx % log_interval == 0: + # Horovod: use train_sampler to determine the number of + # examples in this worker's partition. + print( + "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format( + epoch, + batch_idx * len(data), + len(train_sampler), + 100.0 * batch_idx / len(train_loader), + loss.item(), + ) + ) + return loss.item() if loss else None + + +# Horovod function API. + + +def train_func(config): + num_epochs = config.get("num_epochs", 10) + log_interval = config.get("log_interval", 10) + use_cuda = config.get("use_cuda", False) + + model, optimizer, train_loader, train_sampler = setup(config) + + for epoch in range(num_epochs): + loss = train_epoch( + model, optimizer, train_sampler, train_loader, epoch, log_interval, use_cuda + ) + train.report(dict(loss=loss)) + + +def main(num_workers, use_gpu, kwargs): + trainer = HorovodTrainer( + train_func, + train_loop_config=kwargs, + scaling_config=ScalingConfig(use_gpu=use_gpu, num_workers=num_workers), + ) + results = trainer.fit() + print(results.metrics) + + +# Horovod Class API. + + +class HorovodTrainClass: + def __init__(self, config): + self.log_interval = config.get("log_interval", 10) + self.use_cuda = config.get("use_cuda", False) + + if self.use_cuda: + torch.cuda.set_device(hvd.local_rank()) + + self.model, self.optimizer, self.train_loader, self.train_sampler = setup( + config + ) + + def train(self, epoch): + loss = train_epoch( + self.model, + self.optimizer, + self.train_sampler, + self.train_loader, + epoch, + self.log_interval, + self.use_cuda, + ) + return loss + + +if __name__ == "__main__": + # Training settings + parser = argparse.ArgumentParser( + description="PyTorch MNIST Example", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "--batch-size", + type=int, + default=64, + metavar="N", + help="input batch size for training (default: 64)", + ) + parser.add_argument( + "--num-epochs", + type=int, + default=5, + metavar="N", + help="number of epochs to train (default: 10)", + ) + parser.add_argument( + "--lr", + type=float, + default=0.01, + metavar="LR", + help="learning rate (default: 0.01)", + ) + parser.add_argument( + "--momentum", + type=float, + default=0.5, + metavar="M", + help="SGD momentum (default: 0.5)", + ) + parser.add_argument( + "--use-gpu", action="store_true", default=False, help="enables CUDA training" + ) + parser.add_argument( + "--seed", type=int, default=42, metavar="S", help="random seed (default: 42)" + ) + parser.add_argument( + "--log-interval", + type=int, + default=10, + metavar="N", + help="how many batches to wait before logging training status", + ) + parser.add_argument( + "--use-adasum", + action="store_true", + default=False, + help="use adasum algorithm to do reduction", + ) + parser.add_argument( + "--num-workers", + type=int, + default=2, + help="Number of Ray workers to use for training.", + ) + parser.add_argument( + "--data-dir", + help="location of the training dataset in the local filesystem (" + "will be downloaded if needed)", + ) + parser.add_argument( + "--address", + required=False, + type=str, + default=None, + help="Address of Ray cluster.", + ) + + args = parser.parse_args() + + if args.address: + ray.init(args.address) + else: + ray.init() + + use_cuda = args.use_gpu if args.use_gpu is not None else False + + kwargs = { + "data_dir": args.data_dir, + "seed": args.seed, + "use_cuda": use_cuda, + "batch_size": args.batch_size, + "use_adasum": args.use_adasum if args.use_adasum else False, + "lr": args.lr, + "momentum": args.momentum, + "num_epochs": args.num_epochs, + "log_interval": args.log_interval, + } + + main(num_workers=args.num_workers, use_gpu=use_cuda, kwargs=kwargs) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_pytorch_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_pytorch_example.py new file mode 100644 index 0000000000000000000000000000000000000000..d20ed51e9ef7e39c467948954816e91e509cff9c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_pytorch_example.py @@ -0,0 +1,270 @@ +import argparse +import os +import tempfile + +import horovod.torch as hvd +import torch.nn as nn +import torch.nn.functional as F +import torch.optim as optim +import torch.utils.data.distributed +from filelock import FileLock +from torchvision import datasets, transforms + +import ray.train.torch +from ray import train +from ray.train import Checkpoint, ScalingConfig +from ray.train.horovod import HorovodTrainer + + +def metric_average(val, name): + tensor = torch.tensor(val) + avg_tensor = hvd.allreduce(tensor, name=name) + return avg_tensor.item() + + +class Net(nn.Module): + def __init__(self): + super(Net, self).__init__() + self.conv1 = nn.Conv2d(1, 10, kernel_size=5) + self.conv2 = nn.Conv2d(10, 20, kernel_size=5) + self.conv2_drop = nn.Dropout2d() + self.fc1 = nn.Linear(320, 50) + self.fc2 = nn.Linear(50, 10) + + def forward(self, x): + x = F.relu(F.max_pool2d(self.conv1(x), 2)) + x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) + x = x.view(-1, 320) + x = F.relu(self.fc1(x)) + x = F.dropout(x, training=self.training) + x = self.fc2(x) + return F.log_softmax(x) + + +def setup(config): + data_dir = config.get("data_dir", None) + seed = config.get("seed", 42) + batch_size = config.get("batch_size", 64) + use_adasum = config.get("use_adasum", False) + lr = config.get("lr", 0.01) + momentum = config.get("momentum", 0.5) + use_cuda = config.get("use_cuda", False) + + # Horovod: initialize library. + hvd.init() + torch.manual_seed(seed) + + if use_cuda: + # Horovod: pin GPU to local rank. + torch.cuda.set_device(hvd.local_rank()) + torch.cuda.manual_seed(seed) + + # Horovod: limit # of CPU threads to be used per worker. + torch.set_num_threads(1) + + kwargs = {"pin_memory": True} if use_cuda else {} + data_dir = data_dir or "~/data" + with FileLock(os.path.expanduser("~/.horovod_lock")): + train_dataset = datasets.MNIST( + data_dir, + train=True, + download=True, + transform=transforms.Compose( + [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))] + ), + ) + # Horovod: use DistributedSampler to partition the training data. + train_sampler = torch.utils.data.distributed.DistributedSampler( + train_dataset, num_replicas=hvd.size(), rank=hvd.rank() + ) + # Note, don't set `num_workers` in DataLoader (not even 1), + # as that will separately start multiple processes (each corresponding to 1 worker) + # to load the data. This is known to cause issues with Ray. + train_loader = torch.utils.data.DataLoader( + train_dataset, batch_size=batch_size, sampler=train_sampler, **kwargs + ) + + model = Net() + + # By default, Adasum doesn't need scaling up learning rate. + lr_scaler = hvd.size() if not use_adasum else 1 + + if use_cuda: + # Move model to GPU. + model.cuda() + # If using GPU Adasum allreduce, scale learning rate by local_size. + if use_adasum and hvd.nccl_built(): + lr_scaler = hvd.local_size() + + # Horovod: scale learning rate by lr_scaler. + optimizer = optim.SGD(model.parameters(), lr=lr * lr_scaler, momentum=momentum) + + # Horovod: wrap optimizer with DistributedOptimizer. + optimizer = hvd.DistributedOptimizer( + optimizer, + named_parameters=model.named_parameters(), + op=hvd.Adasum if use_adasum else hvd.Average, + ) + + return model, optimizer, train_loader, train_sampler + + +def train_epoch( + model, optimizer, train_sampler, train_loader, epoch, log_interval, use_cuda +): + loss = None + model.train() + # Horovod: set epoch to sampler for shuffling. + train_sampler.set_epoch(epoch) + for batch_idx, (data, target) in enumerate(train_loader): + if use_cuda: + data, target = data.cuda(), target.cuda() + optimizer.zero_grad() + output = model(data) + loss = F.nll_loss(output, target) + loss.backward() + optimizer.step() + if batch_idx % log_interval == 0: + # Horovod: use train_sampler to determine the number of + # examples in this worker's partition. + print( + "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format( + epoch, + batch_idx * len(data), + len(train_sampler), + 100.0 * batch_idx / len(train_loader), + loss.item(), + ) + ) + return loss.item() if loss else None + + +def train_func(config): + num_epochs = config.get("num_epochs", 10) + log_interval = config.get("log_interval", 10) + use_cuda = config.get("use_cuda", False) + + model, optimizer, train_loader, train_sampler = setup(config) + + results = [] + for epoch in range(num_epochs): + loss = train_epoch( + model, optimizer, train_sampler, train_loader, epoch, log_interval, use_cuda + ) + results.append(loss) + with tempfile.TemporaryDirectory() as tmpdir: + torch.save(model.state_dict(), os.path.join(tmpdir, "model.pt")) + train.report({"loss": loss}, checkpoint=Checkpoint.from_directory(tmpdir)) + + # Only used for testing. + return results + + +def main(num_workers, use_gpu, kwargs): + trainer = HorovodTrainer( + train_loop_per_worker=train_func, + train_loop_config={ + "num_epochs": kwargs["num_epochs"], + "log_interval": kwargs["log_interval"], + "use_cuda": kwargs["use_cuda"], + }, + scaling_config=ScalingConfig(num_workers=num_workers, use_gpu=use_gpu), + ) + result = trainer.fit() + print(result) + + +if __name__ == "__main__": + # Training settings + parser = argparse.ArgumentParser( + description="PyTorch MNIST Example", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "--batch-size", + type=int, + default=64, + metavar="N", + help="input batch size for training (default: 64)", + ) + parser.add_argument( + "--num-epochs", + type=int, + default=5, + metavar="N", + help="number of epochs to train (default: 10)", + ) + parser.add_argument( + "--lr", + type=float, + default=0.01, + metavar="LR", + help="learning rate (default: 0.01)", + ) + parser.add_argument( + "--momentum", + type=float, + default=0.5, + metavar="M", + help="SGD momentum (default: 0.5)", + ) + parser.add_argument( + "--use-gpu", action="store_true", default=False, help="enables CUDA training" + ) + parser.add_argument( + "--seed", type=int, default=42, metavar="S", help="random seed (default: 42)" + ) + parser.add_argument( + "--log-interval", + type=int, + default=10, + metavar="N", + help="how many batches to wait before logging training status", + ) + parser.add_argument( + "--use-adasum", + action="store_true", + default=False, + help="use adasum algorithm to do reduction", + ) + parser.add_argument( + "--num-workers", + type=int, + default=2, + help="Number of Ray workers to use for training.", + ) + parser.add_argument( + "--data-dir", + help="location of the training dataset in the local filesystem (" + "will be downloaded if needed)", + ) + parser.add_argument( + "--address", + required=False, + type=str, + default=None, + help="Address of Ray cluster.", + ) + + args = parser.parse_args() + + if args.address: + ray.init(args.address) + else: + ray.init() + + use_cuda = args.use_gpu if args.use_gpu is not None else False + + kwargs = { + "data_dir": args.data_dir, + "seed": args.seed, + "use_cuda": use_cuda, + "batch_size": args.batch_size, + "use_adasum": args.use_adasum if args.use_adasum else False, + "lr": args.lr, + "momentum": args.momentum, + "num_epochs": args.num_epochs, + "log_interval": args.log_interval, + } + + main(num_workers=args.num_workers, use_gpu=use_cuda, kwargs=kwargs) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_tune_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_tune_example.py new file mode 100644 index 0000000000000000000000000000000000000000..9433d50635ad0a8db585aefc454dd6c9649685a3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/horovod/horovod_tune_example.py @@ -0,0 +1,139 @@ +import time + +import numpy as np +import torch + +import ray +import ray.train.torch +from ray import train, tune +from ray.train import ScalingConfig +from ray.train.horovod import HorovodTrainer +from ray.tune.tune_config import TuneConfig +from ray.tune.tuner import Tuner + + +def sq(x): + m2 = 1.0 + m1 = -20.0 + m0 = 50.0 + return m2 * x * x + m1 * x + m0 + + +def qu(x): + m3 = 10.0 + m2 = 5.0 + m1 = -20.0 + m0 = -5.0 + return m3 * x * x * x + m2 * x * x + m1 * x + m0 + + +class Net(torch.nn.Module): + def __init__(self, mode="sq"): + super(Net, self).__init__() + + if mode == "square": + self.mode = 0 + self.param = torch.nn.Parameter(torch.FloatTensor([1.0, -1.0])) + else: + self.mode = 1 + self.param = torch.nn.Parameter(torch.FloatTensor([1.0, -1.0, 1.0])) + + def forward(self, x): + if ~self.mode: + return x * x + self.param[0] * x + self.param[1] + else: + return_val = 10 * x * x * x + return_val += self.param[0] * x * x + return_val += self.param[1] * x + self.param[2] + return return_val + + +def train_loop_per_worker(config): + import horovod.torch as hvd + import torch + + hvd.init() + device = ray.train.torch.get_device() + mode = config["mode"] + net = Net(mode).to(device) + optimizer = torch.optim.SGD( + net.parameters(), + lr=config["lr"], + ) + optimizer = hvd.DistributedOptimizer(optimizer) + + num_steps = 5 + print(hvd.size()) + np.random.seed(1 + hvd.rank()) + torch.manual_seed(1234) + # To ensure consistent initialization across workers, + hvd.broadcast_parameters(net.state_dict(), root_rank=0) + hvd.broadcast_optimizer_state(optimizer, root_rank=0) + + start = time.time() + x_max = config["x_max"] + for step in range(1, num_steps + 1): + features = torch.Tensor(np.random.rand(1) * 2 * x_max - x_max).to(device) + if mode == "square": + labels = sq(features) + else: + labels = qu(features) + optimizer.zero_grad() + outputs = net(features) + loss = torch.nn.MSELoss()(outputs, labels) + loss.backward() + + optimizer.step() + time.sleep(0.1) + train.report(dict(loss=loss.item())) + total = time.time() - start + print(f"Took {total:0.3f} s. Avg: {total / num_steps:0.3f} s.") + + +def tune_horovod(num_workers, num_samples, use_gpu, mode="square", x_max=1.0): + horovod_trainer = HorovodTrainer( + train_loop_per_worker=train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=num_workers, use_gpu=use_gpu), + train_loop_config={"mode": mode, "x_max": x_max}, + ) + + tuner = Tuner( + horovod_trainer, + param_space={"train_loop_config": {"lr": tune.uniform(0.1, 1)}}, + tune_config=TuneConfig(mode="min", metric="loss", num_samples=num_samples), + _tuner_kwargs={"fail_fast": True}, + ) + + result_grid = tuner.fit() + + print("Best hyperparameters found were: ", result_grid.get_best_result().config) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--mode", type=str, default="square", choices=["square", "cubic"] + ) + parser.add_argument( + "--learning_rate", type=float, default=0.1, dest="learning_rate" + ) + parser.add_argument("--x_max", type=float, default=1.0, dest="x_max") + parser.add_argument("--gpu", action="store_true") + parser.add_argument( + "--smoke-test", action="store_true", help=("Finish quickly for testing.") + ) + parser.add_argument("--num-workers", type=int, default=2) + args, _ = parser.parse_known_args() + + if args.smoke_test: + ray.init(num_cpus=3) + + tune_horovod( + num_workers=args.num_workers, + num_samples=2 if args.smoke_test else 10, + use_gpu=args.gpu, + mode=args.mode, + x_max=args.x_max, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/mlflow_simple_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/mlflow_simple_example.py new file mode 100644 index 0000000000000000000000000000000000000000..5e1a49f83bb22eb166f6aabba76b4e9968a00296 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/mlflow_simple_example.py @@ -0,0 +1,55 @@ +from pathlib import Path + +from ray import train +from ray.train import RunConfig, ScalingConfig +from ray.train.torch import TorchTrainer +from ray.tune.logger import TBXLoggerCallback +from ray.tune.logger.mlflow import MLflowLoggerCallback + + +def train_func(): + for i in range(3): + train.report(dict(epoch=i)) + + +trainer = TorchTrainer( + train_func, + scaling_config=ScalingConfig(num_workers=2), + run_config=RunConfig( + callbacks=[ + MLflowLoggerCallback(experiment_name="train_experiment"), + TBXLoggerCallback(), + ], + ), +) + +# Run the training function, logging all the intermediate results +# to MLflow and Tensorboard. +result = trainer.fit() + +# For MLFLow logs: + +# MLFlow logs will by default be saved in an `mlflow` directory +# in the current working directory. + +# $ cd mlflow +# # View the MLflow UI. +# $ mlflow ui + +# You can change the directory by setting the `tracking_uri` argument +# in `MLflowLoggerCallback`. + +# For TensorBoard logs: + +# Print the latest run directory and keep note of it. +# For example: /home/ubuntu/ray_results/TorchTrainer_2022-06-13_20-31-06 +print("Run directory:", Path(result.path).parent) # TensorBoard is saved in parent dir + +# How to visualize the logs + +# Navigate to the run directory of the trainer. +# For example `cd /home/ubuntu/ray_results/TorchTrainer_2022-06-13_20-31-06` +# $ cd +# +# # View the tensorboard UI. +# $ tensorboard --logdir . diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__init__.py b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ca5186c0c7585e9f23f408d47c9c3d61b69ac3d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_fashion_mnist_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_fashion_mnist_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63df82915896b5c77aded8de90ecf9aa32dc5f9c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_fashion_mnist_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_linear_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_linear_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5dc6039535924d0631bbbc590ac6ae5227b9e85 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_linear_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_quick_start.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_quick_start.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b8c383d14b2815c03cc1a984aa3fcb75a166dc0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_quick_start.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_regression_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_regression_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23f2a7d5b33f08986f532acbf37a47996a4b3426 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/torch_regression_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/tune_cifar_torch_pbt_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/tune_cifar_torch_pbt_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b038b3952917dbc84448629782eb60a636aada62 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/tune_cifar_torch_pbt_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/tune_torch_regression_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/tune_torch_regression_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8eb2c80da7a49ef9c5bb214df8d1ff672c7d4b8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/__pycache__/tune_torch_regression_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_data_prefetch_benchmark/__init__.py b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_data_prefetch_benchmark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_data_prefetch_benchmark/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_data_prefetch_benchmark/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51a11b5efb7cbd2aac6f9339bfb179843a7c2f64 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_data_prefetch_benchmark/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_data_prefetch_benchmark/__pycache__/auto_pipeline_for_host_to_device_data_transfer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_data_prefetch_benchmark/__pycache__/auto_pipeline_for_host_to_device_data_transfer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cf493b985b4a1e4206e24eb743841fdc514d2a3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_data_prefetch_benchmark/__pycache__/auto_pipeline_for_host_to_device_data_transfer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_data_prefetch_benchmark/auto_pipeline_for_host_to_device_data_transfer.py b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_data_prefetch_benchmark/auto_pipeline_for_host_to_device_data_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..28fe7461bc3c30dd1631bc30454b6a5dc64a9696 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_data_prefetch_benchmark/auto_pipeline_for_host_to_device_data_transfer.py @@ -0,0 +1,161 @@ +# The PyTorch data transfer benchmark script. +import argparse +import warnings + +import numpy as np +import torch +import torch.nn as nn + +import ray.train as train +from ray.train import ScalingConfig +from ray.train.torch import TorchTrainer + + +class Net(nn.Module): + def __init__(self, in_d, hidden): + # output dim = 1 + super(Net, self).__init__() + dims = [in_d] + hidden + [1] + self.layers = nn.ModuleList( + [nn.Linear(dims[i - 1], dims[i]) for i in range(len(dims))] + ) + + def forward(self, x): + for layer in self.layers: + x = layer(x) + return x + + +class BenchmarkDataset(torch.utils.data.Dataset): + """Create a naive dataset for the benchmark""" + + def __init__(self, dim, size=1000): + self.x = torch.from_numpy(np.random.normal(size=(size, dim))).float() + self.y = torch.from_numpy(np.random.normal(size=(size, 1))).float() + self.size = size + + def __getitem__(self, index): + return self.x[index, None], self.y[index, None] + + def __len__(self): + return self.size + + +def train_epoch(epoch, dataloader, model, loss_fn, optimizer): + if train.get_context().get_world_size() > 1: + dataloader.sampler.set_epoch(epoch) + + for X, y in dataloader: + # Compute prediction error + pred = model(X) + loss = loss_fn(pred, y) + + # Backpropagation + optimizer.zero_grad() + loss.backward() + optimizer.step() + + +def train_func(config): + data_size = config.get("data_size", 4096 * 50) + batch_size = config.get("batch_size", 4096) + hidden_size = config.get("hidden_size", 1) + use_auto_transfer = config.get("use_auto_transfer", False) + lr = config.get("lr", 1e-2) + epochs = config.get("epochs", 10) + + train_dataset = BenchmarkDataset(4096, size=data_size) + train_loader = torch.utils.data.DataLoader( + train_dataset, batch_size=batch_size, shuffle=True + ) + + train_loader = train.torch.prepare_data_loader( + data_loader=train_loader, move_to_device=True, auto_transfer=use_auto_transfer + ) + + model = Net(in_d=4096, hidden=[4096] * hidden_size) + model = train.torch.prepare_model(model) + + loss_fn = nn.MSELoss() + optimizer = torch.optim.SGD(model.parameters(), lr=lr) + + start = torch.cuda.Event(enable_timing=True) + end = torch.cuda.Event(enable_timing=True) + + choice = "with" if use_auto_transfer else "without" + print(f"Starting the torch data prefetch benchmark {choice} auto pipeline...") + + torch.cuda.synchronize() + start.record() + for epoch in range(epochs): + train_epoch(epoch, train_loader, model, loss_fn, optimizer) + end.record() + torch.cuda.synchronize() + + print( + f"Finished the torch data prefetch benchmark {choice} " + f"auto pipeline: {start.elapsed_time(end)} ms." + ) + + return "Experiment done." + + +def train_linear(num_workers=1, num_hidden_layers=1, use_auto_transfer=True, epochs=3): + config = { + "lr": 1e-2, + "hidden_size": num_hidden_layers, + "batch_size": 4096, + "epochs": epochs, + "use_auto_transfer": use_auto_transfer, + } + trainer = TorchTrainer( + train_func, + train_loop_config=config, + scaling_config=ScalingConfig(use_gpu=True, num_workers=num_workers), + ) + results = trainer.fit() + + print(results.metrics) + return results + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--address", required=False, type=str, help="the address to use for Ray" + ) + parser.add_argument( + "--epochs", type=int, default=1, help="Number of epochs to train for." + ) + parser.add_argument( + "--num_hidden_layers", + type=int, + default=1, + help="Number of epochs to train for.", + ) + + args, _ = parser.parse_known_args() + + import ray + + ray.init(address=args.address) + + if not torch.cuda.is_available(): + warnings.warn("GPU is not available. Skip the test using auto pipeline.") + else: + train_linear( + num_workers=1, + num_hidden_layers=args.num_hidden_layers, + use_auto_transfer=True, + epochs=args.epochs, + ) + + torch.cuda.empty_cache() + train_linear( + num_workers=1, + num_hidden_layers=args.num_hidden_layers, + use_auto_transfer=False, + epochs=args.epochs, + ) + + ray.shutdown() diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_fashion_mnist_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_fashion_mnist_example.py new file mode 100644 index 0000000000000000000000000000000000000000..ee7632d2d3a37d04eda0e8b8ce4b44f0df37deae --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_fashion_mnist_example.py @@ -0,0 +1,152 @@ +import os +from typing import Dict + +import torch +from filelock import FileLock +from torch import nn +from torch.utils.data import DataLoader +from torchvision import datasets, transforms +from torchvision.transforms import Normalize, ToTensor +from tqdm import tqdm + +import ray.train +from ray.train import ScalingConfig +from ray.train.torch import TorchTrainer + + +def get_dataloaders(batch_size): + # Transform to normalize the input images + transform = transforms.Compose([ToTensor(), Normalize((0.28604,), (0.32025,))]) + + with FileLock(os.path.expanduser("~/data.lock")): + # Download training data from open datasets + training_data = datasets.FashionMNIST( + root="~/data", + train=True, + download=True, + transform=transform, + ) + + # Download test data from open datasets + test_data = datasets.FashionMNIST( + root="~/data", + train=False, + download=True, + transform=transform, + ) + + # Create data loaders + train_dataloader = DataLoader(training_data, batch_size=batch_size, shuffle=True) + test_dataloader = DataLoader(test_data, batch_size=batch_size) + + return train_dataloader, test_dataloader + + +# Model Definition +class NeuralNetwork(nn.Module): + def __init__(self): + super(NeuralNetwork, self).__init__() + self.flatten = nn.Flatten() + self.linear_relu_stack = nn.Sequential( + nn.Linear(28 * 28, 512), + nn.ReLU(), + nn.Dropout(0.25), + nn.Linear(512, 512), + nn.ReLU(), + nn.Dropout(0.25), + nn.Linear(512, 10), + nn.ReLU(), + ) + + def forward(self, x): + x = self.flatten(x) + logits = self.linear_relu_stack(x) + return logits + + +def train_func_per_worker(config: Dict): + lr = config["lr"] + epochs = config["epochs"] + batch_size = config["batch_size_per_worker"] + + # Get dataloaders inside the worker training function + train_dataloader, test_dataloader = get_dataloaders(batch_size=batch_size) + + # [1] Prepare Dataloader for distributed training + # Shard the datasets among workers and move batches to the correct device + # ======================================================================= + train_dataloader = ray.train.torch.prepare_data_loader(train_dataloader) + test_dataloader = ray.train.torch.prepare_data_loader(test_dataloader) + + model = NeuralNetwork() + + # [2] Prepare and wrap your model with DistributedDataParallel + # Move the model to the correct GPU/CPU device + # ============================================================ + model = ray.train.torch.prepare_model(model) + + loss_fn = nn.CrossEntropyLoss() + optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9) + + # Model training loop + for epoch in range(epochs): + if ray.train.get_context().get_world_size() > 1: + # Required for the distributed sampler to shuffle properly across epochs. + train_dataloader.sampler.set_epoch(epoch) + + model.train() + for X, y in tqdm(train_dataloader, desc=f"Train Epoch {epoch}"): + pred = model(X) + loss = loss_fn(pred, y) + + optimizer.zero_grad() + loss.backward() + optimizer.step() + + model.eval() + test_loss, num_correct, num_total = 0, 0, 0 + with torch.no_grad(): + for X, y in tqdm(test_dataloader, desc=f"Test Epoch {epoch}"): + pred = model(X) + loss = loss_fn(pred, y) + + test_loss += loss.item() + num_total += y.shape[0] + num_correct += (pred.argmax(1) == y).sum().item() + + test_loss /= len(test_dataloader) + accuracy = num_correct / num_total + + # [3] Report metrics to Ray Train + # =============================== + ray.train.report(metrics={"loss": test_loss, "accuracy": accuracy}) + + +def train_fashion_mnist(num_workers=2, use_gpu=False): + global_batch_size = 32 + + train_config = { + "lr": 1e-3, + "epochs": 10, + "batch_size_per_worker": global_batch_size // num_workers, + } + + # Configure computation resources + scaling_config = ScalingConfig(num_workers=num_workers, use_gpu=use_gpu) + + # Initialize a Ray TorchTrainer + trainer = TorchTrainer( + train_loop_per_worker=train_func_per_worker, + train_loop_config=train_config, + scaling_config=scaling_config, + ) + + # [4] Start distributed training + # Run `train_func_per_worker` on all workers + # ============================================= + result = trainer.fit() + print(f"Training result: {result}") + + +if __name__ == "__main__": + train_fashion_mnist(num_workers=4, use_gpu=True) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_linear_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_linear_example.py new file mode 100644 index 0000000000000000000000000000000000000000..19d5848473b91719f488d19a3364ddc55da6d899 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_linear_example.py @@ -0,0 +1,147 @@ +import argparse +import os +import tempfile + +import numpy as np +import torch +import torch.nn as nn + +import ray.train as train +from ray.train import Checkpoint, RunConfig, ScalingConfig +from ray.train.torch import TorchTrainer + + +class LinearDataset(torch.utils.data.Dataset): + """y = a * x + b""" + + def __init__(self, a, b, size=1000): + x = np.arange(0, 10, 10 / size, dtype=np.float32) + self.x = torch.from_numpy(x) + self.y = torch.from_numpy(a * x + b) + + def __getitem__(self, index): + return self.x[index, None], self.y[index, None] + + def __len__(self): + return len(self.x) + + +def train_epoch(epoch, dataloader, model, loss_fn, optimizer): + if train.get_context().get_world_size() > 1: + dataloader.sampler.set_epoch(epoch) + + for X, y in dataloader: + # Compute prediction error + pred = model(X) + loss = loss_fn(pred, y) + + # Backpropagation + optimizer.zero_grad() + loss.backward() + optimizer.step() + + +def validate_epoch(dataloader, model, loss_fn): + num_batches = len(dataloader) + model.eval() + loss = 0 + with torch.no_grad(): + for X, y in dataloader: + pred = model(X) + loss += loss_fn(pred, y).item() + loss /= num_batches + import copy + + model_copy = copy.deepcopy(model) + return model_copy.cpu().state_dict(), loss + + +def train_func(config): + data_size = config.get("data_size", 1000) + val_size = config.get("val_size", 400) + batch_size = config.get("batch_size", 32) + hidden_size = config.get("hidden_size", 1) + lr = config.get("lr", 1e-2) + epochs = config.get("epochs", 3) + + train_dataset = LinearDataset(2, 5, size=data_size) + val_dataset = LinearDataset(2, 5, size=val_size) + train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size) + validation_loader = torch.utils.data.DataLoader(val_dataset, batch_size=batch_size) + + train_loader = train.torch.prepare_data_loader(train_loader) + validation_loader = train.torch.prepare_data_loader(validation_loader) + + model = nn.Linear(1, hidden_size) + model = train.torch.prepare_model(model) + + loss_fn = nn.MSELoss() + + optimizer = torch.optim.SGD(model.parameters(), lr=lr) + + results = [] + for epoch in range(epochs): + train_epoch(epoch, train_loader, model, loss_fn, optimizer) + state_dict, loss = validate_epoch(validation_loader, model, loss_fn) + result = dict(loss=loss) + results.append(result) + + with tempfile.TemporaryDirectory() as tmpdir: + torch.save(state_dict, os.path.join(tmpdir, "model.pt")) + train.report(result, checkpoint=Checkpoint.from_directory(tmpdir)) + + return results + + +def train_linear(num_workers=2, use_gpu=False, epochs=3, storage_path=None): + config = {"lr": 1e-2, "hidden_size": 1, "batch_size": 4, "epochs": epochs} + trainer = TorchTrainer( + train_loop_per_worker=train_func, + train_loop_config=config, + scaling_config=ScalingConfig(num_workers=num_workers, use_gpu=use_gpu), + run_config=RunConfig(storage_path=storage_path), + ) + result = trainer.fit() + + print(result.metrics) + return result.metrics + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--address", required=False, type=str, help="the address to use for Ray" + ) + parser.add_argument( + "--num-workers", + "-n", + type=int, + default=2, + help="Sets number of workers for training.", + ) + parser.add_argument( + "--use-gpu", action="store_true", help="Whether to use GPU for training." + ) + parser.add_argument( + "--epochs", type=int, default=3, help="Number of epochs to train for." + ) + parser.add_argument( + "--smoke-test", + action="store_true", + default=False, + help="Finish quickly for testing.", + ) + + args, _ = parser.parse_known_args() + + import ray + + if args.smoke_test: + # 2 workers + 1 for trainer. + ray.init(num_cpus=3) + train_linear() + else: + ray.init(address=args.address) + train_linear( + num_workers=args.num_workers, use_gpu=args.use_gpu, epochs=args.epochs + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_quick_start.py b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_quick_start.py new file mode 100644 index 0000000000000000000000000000000000000000..df1ae3461bd7aaac9d5c5d98c604115df36d3760 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_quick_start.py @@ -0,0 +1,110 @@ +# ruff: noqa +# fmt: off +# isort: skip_file + +# __torch_setup_begin__ +import torch +import torch.nn as nn +from torch.utils.data import DataLoader +from torchvision import datasets +from torchvision.transforms import ToTensor + +def get_dataset(): + return datasets.FashionMNIST( + root="/tmp/data", + train=True, + download=True, + transform=ToTensor(), + ) + +class NeuralNetwork(nn.Module): + def __init__(self): + super().__init__() + self.flatten = nn.Flatten() + self.linear_relu_stack = nn.Sequential( + nn.Linear(28 * 28, 512), + nn.ReLU(), + nn.Linear(512, 512), + nn.ReLU(), + nn.Linear(512, 10), + ) + + def forward(self, inputs): + inputs = self.flatten(inputs) + logits = self.linear_relu_stack(inputs) + return logits +# __torch_setup_end__ + +# __torch_single_begin__ +def train_func(): + num_epochs = 3 + batch_size = 64 + + dataset = get_dataset() + dataloader = DataLoader(dataset, batch_size=batch_size) + + model = NeuralNetwork() + + criterion = nn.CrossEntropyLoss() + optimizer = torch.optim.SGD(model.parameters(), lr=0.01) + + for epoch in range(num_epochs): + for inputs, labels in dataloader: + optimizer.zero_grad() + pred = model(inputs) + loss = criterion(pred, labels) + loss.backward() + optimizer.step() + print(f"epoch: {epoch}, loss: {loss.item()}") +# __torch_single_end__ + +# __torch_distributed_begin__ +import ray.train.torch + +def train_func_distributed(): + num_epochs = 3 + batch_size = 64 + + dataset = get_dataset() + dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True) + dataloader = ray.train.torch.prepare_data_loader(dataloader) + + model = NeuralNetwork() + model = ray.train.torch.prepare_model(model) + + criterion = nn.CrossEntropyLoss() + optimizer = torch.optim.SGD(model.parameters(), lr=0.01) + + for epoch in range(num_epochs): + if ray.train.get_context().get_world_size() > 1: + dataloader.sampler.set_epoch(epoch) + + for inputs, labels in dataloader: + optimizer.zero_grad() + pred = model(inputs) + loss = criterion(pred, labels) + loss.backward() + optimizer.step() + print(f"epoch: {epoch}, loss: {loss.item()}") +# __torch_distributed_end__ + + +if __name__ == "__main__": + # __torch_single_run_begin__ + train_func() + # __torch_single_run_end__ + + # __torch_trainer_begin__ + from ray.train.torch import TorchTrainer + from ray.train import ScalingConfig + + # For GPU Training, set `use_gpu` to True. + use_gpu = False + + trainer = TorchTrainer( + train_func_distributed, + scaling_config=ScalingConfig(num_workers=4, use_gpu=use_gpu) + ) + + results = trainer.fit() + # __torch_trainer_end__ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_regression_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_regression_example.py new file mode 100644 index 0000000000000000000000000000000000000000..8bd54fbcb7ab2e8c778b220c39187e0ad0430ca5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/torch_regression_example.py @@ -0,0 +1,160 @@ +import argparse +import os +import tempfile +from typing import Tuple + +import pandas as pd +import torch +import torch.nn as nn + +import ray +import ray.train as train +from ray.data import Dataset +from ray.train import Checkpoint, DataConfig, ScalingConfig +from ray.train.torch import TorchTrainer + + +def get_datasets(split: float = 0.7) -> Tuple[Dataset]: + dataset = ray.data.read_csv("s3://anonymous@air-example-data/regression.csv") + + def combine_x(batch): + return pd.DataFrame( + { + "x": batch[[f"x{i:03d}" for i in range(100)]].values.tolist(), + "y": batch["y"], + } + ) + + dataset = dataset.map_batches(combine_x, batch_format="pandas") + train_dataset, validation_dataset = dataset.repartition( + num_blocks=4 + ).train_test_split(split, shuffle=True) + return train_dataset, validation_dataset + + +def train_epoch(iterable_dataset, model, loss_fn, optimizer, device): + model.train() + for X, y in iterable_dataset: + X = X.to(device) + y = y.to(device) + + # Compute prediction error + pred = model(X) + loss = loss_fn(pred, y) + + # Backpropagation + optimizer.zero_grad() + loss.backward() + optimizer.step() + + +def validate_epoch(iterable_dataset, model, loss_fn, device): + num_batches = 0 + model.eval() + loss = 0 + with torch.no_grad(): + for X, y in iterable_dataset: + X = X.to(device) + y = y.to(device) + num_batches += 1 + pred = model(X) + loss += loss_fn(pred, y).item() + loss /= num_batches + result = {"loss": loss} + return result + + +def train_func(config): + batch_size = config.get("batch_size", 32) + hidden_size = config.get("hidden_size", 10) + lr = config.get("lr", 1e-2) + epochs = config.get("epochs", 3) + + train_dataset_shard = train.get_dataset_shard("train") + validation_dataset = train.get_dataset_shard("validation") + + model = nn.Sequential( + nn.Linear(100, hidden_size), nn.ReLU(), nn.Linear(hidden_size, 1) + ) + model = train.torch.prepare_model(model) + + loss_fn = nn.L1Loss() + + optimizer = torch.optim.SGD(model.parameters(), lr=lr) + + results = [] + + def create_torch_iterator(shard): + iterator = shard.iter_torch_batches(batch_size=batch_size) + for batch in iterator: + yield batch["x"].float(), batch["y"].float() + + for _ in range(epochs): + train_torch_dataset = create_torch_iterator(train_dataset_shard) + validation_torch_dataset = create_torch_iterator(validation_dataset) + + device = train.torch.get_device() + + train_epoch(train_torch_dataset, model, loss_fn, optimizer, device) + if train.get_context().get_world_rank() == 0: + result = validate_epoch(validation_torch_dataset, model, loss_fn, device) + else: + result = {} + results.append(result) + + with tempfile.TemporaryDirectory() as tmpdir: + torch.save(model.module.state_dict(), os.path.join(tmpdir, "model.pt")) + train.report(result, checkpoint=Checkpoint.from_directory(tmpdir)) + + return results + + +def train_regression(num_workers=2, use_gpu=False): + train_dataset, val_dataset = get_datasets() + config = {"lr": 1e-2, "hidden_size": 20, "batch_size": 4, "epochs": 3} + + trainer = TorchTrainer( + train_loop_per_worker=train_func, + train_loop_config=config, + scaling_config=ScalingConfig(num_workers=num_workers, use_gpu=use_gpu), + datasets={"train": train_dataset, "validation": val_dataset}, + dataset_config=DataConfig(datasets_to_split=["train"]), + ) + + result = trainer.fit() + print(result.metrics) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--address", required=False, type=str, help="the address to use for Ray" + ) + parser.add_argument( + "--num-workers", + "-n", + type=int, + default=2, + help="Sets number of workers for training.", + ) + parser.add_argument( + "--smoke-test", + action="store_true", + default=False, + help="Finish quickly for testing.", + ) + parser.add_argument( + "--use-gpu", action="store_true", default=False, help="Use GPU for training." + ) + + args, _ = parser.parse_known_args() + + if args.smoke_test: + # 2 workers, 1 for trainer, 1 for datasets + ray.init(num_cpus=4) + result = train_regression() + else: + ray.init(address=args.address) + result = train_regression(num_workers=args.num_workers, use_gpu=args.use_gpu) + print(result) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/tune_cifar_torch_pbt_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/tune_cifar_torch_pbt_example.py new file mode 100644 index 0000000000000000000000000000000000000000..00b5694884bd01b752b72a14a8a606fc12ad3052 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/tune_cifar_torch_pbt_example.py @@ -0,0 +1,253 @@ +import argparse +import os +import tempfile + +import torch +import torch.nn as nn +import torchvision.transforms as transforms +from filelock import FileLock +from torch.utils.data import DataLoader, Subset +from torchvision.datasets import CIFAR10 +from torchvision.models import resnet18 + +import ray +import ray.cloudpickle as cpickle +from ray import train, tune +from ray.train import Checkpoint, FailureConfig, RunConfig, ScalingConfig +from ray.train.torch import TorchTrainer +from ray.tune.schedulers import PopulationBasedTraining +from ray.tune.tune_config import TuneConfig +from ray.tune.tuner import Tuner + + +def train_epoch(epoch, dataloader, model, loss_fn, optimizer): + if ray.train.get_context().get_world_size() > 1: + dataloader.sampler.set_epoch(epoch) + + size = len(dataloader.dataset) // train.get_context().get_world_size() + model.train() + for batch, (X, y) in enumerate(dataloader): + # Compute prediction error + pred = model(X) + loss = loss_fn(pred, y) + + # Backpropagation + optimizer.zero_grad() + loss.backward() + optimizer.step() + + if batch % 100 == 0: + loss, current = loss.item(), batch * len(X) + print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]") + + +def validate_epoch(dataloader, model, loss_fn): + size = len(dataloader.dataset) // train.get_context().get_world_size() + num_batches = len(dataloader) + model.eval() + test_loss, correct = 0, 0 + with torch.no_grad(): + for X, y in dataloader: + pred = model(X) + test_loss += loss_fn(pred, y).item() + correct += (pred.argmax(1) == y).type(torch.float).sum().item() + test_loss /= num_batches + correct /= size + print( + f"Test Error: \n " + f"Accuracy: {(100 * correct):>0.1f}%, " + f"Avg loss: {test_loss:>8f} \n" + ) + return {"loss": test_loss} + + +def update_optimizer_config(optimizer, config): + for param_group in optimizer.param_groups: + for param, val in config.items(): + param_group[param] = val + + +def train_func(config): + epochs = config.get("epochs", 3) + + model = resnet18() + + # Note that `prepare_model` needs to be called before setting optimizer. + if not train.get_checkpoint(): # fresh start + model = train.torch.prepare_model(model) + + # Create optimizer. + optimizer_config = { + "lr": config.get("lr"), + "momentum": config.get("momentum"), + } + optimizer = torch.optim.SGD(model.parameters(), **optimizer_config) + + starting_epoch = 0 + if train.get_checkpoint(): + with train.get_checkpoint().as_directory() as checkpoint_dir: + with open(os.path.join(checkpoint_dir, "data.ckpt"), "rb") as fp: + checkpoint_dict = cpickle.load(fp) + + # Load in model + model_state = checkpoint_dict["model"] + model.load_state_dict(model_state) + model = train.torch.prepare_model(model) + + # Load in optimizer + optimizer_state = checkpoint_dict["optimizer_state_dict"] + optimizer.load_state_dict(optimizer_state) + + # Optimizer configs (`lr`, `momentum`) are being mutated by PBT and passed in + # through config, so we need to update the optimizer loaded from the checkpoint + update_optimizer_config(optimizer, optimizer_config) + + # The current epoch increments the loaded epoch by 1 + checkpoint_epoch = checkpoint_dict["epoch"] + starting_epoch = checkpoint_epoch + 1 + + # Load in training and validation data. + transform_train = transforms.Compose( + [ + transforms.RandomCrop(32, padding=4), + transforms.RandomHorizontalFlip(), + transforms.ToTensor(), + transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), + ] + ) # meanstd transformation + + transform_test = transforms.Compose( + [ + transforms.ToTensor(), + transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), + ] + ) + + data_dir = config.get("data_dir", os.path.expanduser("~/data")) + os.makedirs(data_dir, exist_ok=True) + with FileLock(os.path.join(data_dir, ".ray.lock")): + train_dataset = CIFAR10( + root=data_dir, train=True, download=True, transform=transform_train + ) + validation_dataset = CIFAR10( + root=data_dir, train=False, download=False, transform=transform_test + ) + + if config.get("test_mode"): + train_dataset = Subset(train_dataset, list(range(64))) + validation_dataset = Subset(validation_dataset, list(range(64))) + + worker_batch_size = config["batch_size"] // train.get_context().get_world_size() + + train_loader = DataLoader(train_dataset, batch_size=worker_batch_size, shuffle=True) + validation_loader = DataLoader(validation_dataset, batch_size=worker_batch_size) + + train_loader = train.torch.prepare_data_loader(train_loader) + validation_loader = train.torch.prepare_data_loader(validation_loader) + + # Create loss. + criterion = nn.CrossEntropyLoss() + + for epoch in range(starting_epoch, epochs): + train_epoch(epoch, train_loader, model, criterion, optimizer) + result = validate_epoch(validation_loader, model, criterion) + + with tempfile.TemporaryDirectory() as checkpoint_dir: + with open(os.path.join(checkpoint_dir, "data.ckpt"), "wb") as fp: + cpickle.dump( + { + "epoch": epoch, + "model": model.state_dict(), + "optimizer_state_dict": optimizer.state_dict(), + }, + fp, + ) + checkpoint = Checkpoint.from_directory(checkpoint_dir) + train.report(result, checkpoint=checkpoint) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--address", required=False, type=str, help="The address to use for Redis." + ) + parser.add_argument( + "--num-workers", + "-n", + type=int, + default=2, + help="Sets number of workers for training.", + ) + parser.add_argument( + "--num-epochs", type=int, default=5, help="Number of epochs to train." + ) + parser.add_argument( + "--smoke-test", + action="store_true", + default=False, + help="Finish quickly for testing.", + ) + parser.add_argument( + "--use-gpu", action="store_true", default=False, help="Enables GPU training." + ) + parser.add_argument( + "--data-dir", + required=False, + type=str, + default="~/data", + help="Root directory for storing downloaded dataset.", + ) + parser.add_argument( + "--synch", action="store_true", default=False, help="Use synchronous PBT." + ) + + args, _ = parser.parse_known_args() + if args.smoke_test: + ray.init(num_cpus=4) + else: + ray.init(address=args.address) + + trainer = TorchTrainer( + train_func, + scaling_config=ScalingConfig( + num_workers=args.num_workers, use_gpu=args.use_gpu + ), + ) + pbt_scheduler = PopulationBasedTraining( + time_attr="training_iteration", + perturbation_interval=1, + hyperparam_mutations={ + "train_loop_config": { + # distribution for resampling + "lr": tune.loguniform(0.001, 0.1), + # allow perturbations within this set of categorical values + "momentum": [0.8, 0.9, 0.99], + } + }, + synch=args.synch, + ) + + tuner = Tuner( + trainer, + param_space={ + "train_loop_config": { + "lr": tune.grid_search([0.001, 0.01, 0.05, 0.1]), + "momentum": 0.8, + "batch_size": 128 * args.num_workers, + "test_mode": args.smoke_test, # whether to to subset the data + "data_dir": args.data_dir, + "epochs": args.num_epochs, + } + }, + tune_config=TuneConfig( + num_samples=1, metric="loss", mode="min", scheduler=pbt_scheduler + ), + run_config=RunConfig( + stop={"training_iteration": 3 if args.smoke_test else args.num_epochs}, + failure_config=FailureConfig(max_failures=3), # used for fault tolerance + ), + ) + + results = tuner.fit() + + print(results.get_best_result(metric="loss", mode="min")) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/tune_torch_regression_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/tune_torch_regression_example.py new file mode 100644 index 0000000000000000000000000000000000000000..e8221c995110f5f8c5b6d48b25d87868a3f78c0c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch/tune_torch_regression_example.py @@ -0,0 +1,82 @@ +import argparse + +import ray +from ray import tune +from ray.train import DataConfig, ScalingConfig +from ray.train.examples.pytorch.torch_regression_example import get_datasets, train_func +from ray.train.torch import TorchTrainer +from ray.tune.tune_config import TuneConfig +from ray.tune.tuner import Tuner + + +def tune_linear(num_workers, num_samples, use_gpu): + train_dataset, val_dataset = get_datasets() + + config = {"lr": 1e-2, "hidden_size": 1, "batch_size": 4, "epochs": 3} + + trainer = TorchTrainer( + train_loop_per_worker=train_func, + train_loop_config=config, + scaling_config=ScalingConfig(num_workers=num_workers, use_gpu=use_gpu), + datasets={"train": train_dataset, "validation": val_dataset}, + dataset_config=DataConfig(datasets_to_split=["train"]), + ) + + tuner = Tuner( + trainer, + param_space={ + "train_loop_config": { + "lr": tune.loguniform(1e-4, 1e-1), + "batch_size": tune.choice([4, 16, 32]), + "epochs": 3, + } + }, + tune_config=TuneConfig(num_samples=num_samples, metric="loss", mode="min"), + ) + result_grid = tuner.fit() + best_result = result_grid.get_best_result() + print(best_result) + return best_result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", + action="store_true", + default=False, + help="Finish quickly for testing.", + ) + parser.add_argument( + "--address", required=False, type=str, help="the address to use for Ray" + ) + parser.add_argument( + "--num-workers", + "-n", + type=int, + default=2, + help="Sets number of workers for training.", + ) + parser.add_argument( + "--num-samples", + type=int, + default=2, + help="Sets number of samples for training.", + ) + parser.add_argument( + "--use-gpu", action="store_true", default=False, help="Use GPU for training." + ) + + args = parser.parse_args() + + if args.smoke_test: + # 2 workers, 1 for trainer, 1 for datasets + ray.init(num_cpus=4) + tune_linear(num_workers=2, num_samples=1, use_gpu=False) + else: + ray.init(address=args.address) + tune_linear( + num_workers=args.num_workers, + use_gpu=args.use_gpu, + num_samples=args.num_samples, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch_geometric/__init__.py b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch_geometric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch_geometric/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch_geometric/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..860f953b78a9b2b0a5551e7da8d81d3ca598cbbc Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch_geometric/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch_geometric/__pycache__/distributed_sage_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch_geometric/__pycache__/distributed_sage_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32bc04066a7560bccf853312b5625cf904354789 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch_geometric/__pycache__/distributed_sage_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/pytorch_geometric/distributed_sage_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch_geometric/distributed_sage_example.py new file mode 100644 index 0000000000000000000000000000000000000000..0f3b1e126d05a266b43496fa9ec3c097c3aaba19 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/pytorch_geometric/distributed_sage_example.py @@ -0,0 +1,228 @@ +# Adapted from https://github.com/pyg-team/pytorch_geometric/blob/2.1.0 +# /examples/multi_gpu/distributed_sampling.py + +import argparse +import os + +import torch +import torch.nn.functional as F +from filelock import FileLock +from torch_geometric.datasets import FakeDataset, Reddit +from torch_geometric.loader import NeighborSampler +from torch_geometric.nn import SAGEConv +from torch_geometric.transforms import RandomNodeSplit + +from ray import train +from ray.train import ScalingConfig +from ray.train.torch import TorchTrainer + + +class SAGE(torch.nn.Module): + def __init__(self, in_channels, hidden_channels, out_channels, num_layers=2): + super().__init__() + self.num_layers = num_layers + + self.convs = torch.nn.ModuleList() + self.convs.append(SAGEConv(in_channels, hidden_channels)) + for _ in range(self.num_layers - 2): + self.convs.append(SAGEConv(hidden_channels, hidden_channels)) + self.convs.append(SAGEConv(hidden_channels, out_channels)) + + def forward(self, x, adjs): + for i, (edge_index, _, size) in enumerate(adjs): + x_target = x[: size[1]] # Target nodes are always placed first. + x = self.convs[i]((x, x_target), edge_index) + if i != self.num_layers - 1: + x = F.relu(x) + x = F.dropout(x, p=0.5, training=self.training) + return x.log_softmax(dim=-1) + + @torch.no_grad() + def test(self, x_all, subgraph_loader): + for i in range(self.num_layers): + xs = [] + for batch_size, n_id, adj in subgraph_loader: + edge_index, _, size = adj + x = x_all[n_id.to(x_all.device)].to(train.torch.get_device()) + x_target = x[: size[1]] + x = self.convs[i]((x, x_target), edge_index) + if i != self.num_layers - 1: + x = F.relu(x) + xs.append(x.cpu()) + + x_all = torch.cat(xs, dim=0) + + return x_all + + +def train_loop_per_worker(train_loop_config): + dataset = train_loop_config["dataset_fn"]() + batch_size = train_loop_config["batch_size"] + num_epochs = train_loop_config["num_epochs"] + + data = dataset[0] + train_idx = data.train_mask.nonzero(as_tuple=False).view(-1) + train_idx = train_idx.split( + train_idx.size(0) // train.get_context().get_world_size() + )[train.get_context().get_world_rank()] + + train_loader = NeighborSampler( + data.edge_index, + node_idx=train_idx, + sizes=[25, 10], + batch_size=batch_size, + shuffle=True, + ) + + # Disable distributed sampler since the train_loader has already been split above. + train_loader = train.torch.prepare_data_loader(train_loader, add_dist_sampler=False) + + # Do validation on rank 0 worker only. + if train.get_context().get_world_rank() == 0: + subgraph_loader = NeighborSampler( + data.edge_index, node_idx=None, sizes=[-1], batch_size=2048, shuffle=False + ) + subgraph_loader = train.torch.prepare_data_loader( + subgraph_loader, add_dist_sampler=False + ) + + model = SAGE(dataset.num_features, 256, dataset.num_classes) + model = train.torch.prepare_model(model) + optimizer = torch.optim.Adam(model.parameters(), lr=0.01) + + x, y = data.x.to(train.torch.get_device()), data.y.to(train.torch.get_device()) + + for epoch in range(num_epochs): + model.train() + + # ``batch_size`` is the number of samples in the current batch. + # ``n_id`` are the ids of all the nodes used in the computation. This is + # needed to pull in the necessary features just for the current batch that is + # being trained on. + # ``adjs`` is a list of 3 element tuple consisting of ``(edge_index, e_id, + # size)`` for each sample in the batch, where ``edge_index``represent the + # edges of the sampled subgraph, ``e_id`` are the ids of the edges in the + # sample, and ``size`` holds the shape of the subgraph. + # See ``torch_geometric.loader.neighbor_sampler.NeighborSampler`` for more info. + for batch_size, n_id, adjs in train_loader: + optimizer.zero_grad() + out = model(x[n_id], adjs) + loss = F.nll_loss(out, y[n_id[:batch_size]]) + loss.backward() + optimizer.step() + + if train.get_context().get_world_rank() == 0: + print(f"Epoch: {epoch:03d}, Loss: {loss:.4f}") + + train_accuracy = validation_accuracy = test_accuracy = None + + # Do validation on rank 0 worker only. + if train.get_context().get_world_rank() == 0: + model.eval() + with torch.no_grad(): + out = model.module.test(x, subgraph_loader) + res = out.argmax(dim=-1) == data.y + train_accuracy = int(res[data.train_mask].sum()) / int( + data.train_mask.sum() + ) + validation_accuracy = int(res[data.val_mask].sum()) / int( + data.val_mask.sum() + ) + test_accuracy = int(res[data.test_mask].sum()) / int(data.test_mask.sum()) + + train.report( + dict( + train_accuracy=train_accuracy, + validation_accuracy=validation_accuracy, + test_accuracy=test_accuracy, + ) + ) + + +def gen_fake_dataset(): + """Returns a function to be called on each worker that returns a Fake Dataset.""" + + # For fake dataset, since the dataset is randomized, we create it once on the + # driver, and then send the same dataset to all the training workers. + # Use 10% of nodes for validation and 10% for testing. + fake_dataset = FakeDataset(transform=RandomNodeSplit(num_val=0.1, num_test=0.1)) + + def gen_dataset(): + return fake_dataset + + return gen_dataset + + +def gen_reddit_dataset(): + """Returns a function to be called on each worker that returns Reddit Dataset.""" + + # For Reddit dataset, we have to download the data on each node, so we create the + # dataset on each training worker. + with FileLock(os.path.expanduser("~/.reddit_dataset_lock")): + dataset = Reddit("./data/Reddit") + return dataset + + +def train_gnn( + num_workers=2, use_gpu=False, epochs=3, global_batch_size=32, dataset="reddit" +): + per_worker_batch_size = global_batch_size // num_workers + + trainer = TorchTrainer( + train_loop_per_worker=train_loop_per_worker, + train_loop_config={ + "num_epochs": epochs, + "batch_size": per_worker_batch_size, + "dataset_fn": gen_reddit_dataset + if dataset == "reddit" + else gen_fake_dataset(), + }, + scaling_config=ScalingConfig(num_workers=num_workers, use_gpu=use_gpu), + ) + result = trainer.fit() + print(result.metrics) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--address", required=False, type=str, help="the address to use for Ray" + ) + parser.add_argument( + "--num-workers", + "-n", + type=int, + default=2, + help="Sets number of workers for training.", + ) + parser.add_argument( + "--use-gpu", action="store_true", help="Whether to use GPU for training." + ) + parser.add_argument( + "--epochs", type=int, default=3, help="Number of epochs to train for." + ) + parser.add_argument( + "--global-batch-size", + "-b", + type=int, + default=32, + help="Global batch size to use for training.", + ) + parser.add_argument( + "--dataset", + "-d", + type=str, + choices=["reddit", "fake"], + default="reddit", + help="The dataset to use. Either 'reddit' or 'fake' Defaults to 'reddit'.", + ) + + args, _ = parser.parse_known_args() + + train_gnn( + num_workers=args.num_workers, + use_gpu=args.use_gpu, + epochs=args.epochs, + global_batch_size=args.global_batch_size, + dataset=args.dataset, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/__init__.py b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8a76ad471300162013c010bac7bff4b73a75cee Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_autoencoder_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_autoencoder_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fe61dc907c38a2a10b8d2246e783c393e39b3b1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_autoencoder_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_mnist_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_mnist_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebe2aa8fbf9b2964635b3ea5734d077108395253 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_mnist_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_quick_start.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_quick_start.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..212efdf262fba7bd05952f32d73b2faedf044539 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_quick_start.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_regression_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_regression_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0eb93ea6fd89048224a8c545b24dd41059129571 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tensorflow_regression_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tune_tensorflow_autoencoder_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tune_tensorflow_autoencoder_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..526e59089e2374a2c4de3c63a7ccd4e97cb7b2b5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tune_tensorflow_autoencoder_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tune_tensorflow_mnist_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tune_tensorflow_mnist_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efd03f794100f97df4af893705f0abbf230e04c3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/examples/tf/__pycache__/tune_tensorflow_mnist_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_autoencoder_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_autoencoder_example.py new file mode 100644 index 0000000000000000000000000000000000000000..6d976203efdc9fee5bbfbb27a8aa39d080bea994 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_autoencoder_example.py @@ -0,0 +1,174 @@ +# This example showcases how to use Tensorflow with Ray Train. +# Original code: +# https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras +# https://blog.keras.io/building-autoencoders-in-keras.html +import argparse + +import numpy as np +import pandas as pd +import tensorflow as tf +import tensorflow_datasets as tfds + +import ray +from ray import train +from ray.air.integrations.keras import ReportCheckpointCallback +from ray.data.datasource import SimpleTensorFlowDatasource +from ray.data.extensions import TensorArray +from ray.train import Result, ScalingConfig +from ray.train.tensorflow import TensorflowTrainer, prepare_dataset_shard + + +def get_dataset(split_type="train"): + def dataset_factory(): + return tfds.load("mnist", split=[split_type], as_supervised=True)[0].take(128) + + dataset = ray.data.read_datasource( + SimpleTensorFlowDatasource(), dataset_factory=dataset_factory + ) + + def normalize_images(x): + x = np.float32(x.numpy()) / 255.0 + x = np.reshape(x, (-1,)) + return x + + def preprocess_dataset(batch): + return [ + (normalize_images(image), normalize_images(image)) for image, _ in batch + ] + + dataset = dataset.map_batches(preprocess_dataset) + + def convert_batch_to_pandas(batch): + + images = [TensorArray(image) for image, _ in batch] + # because we did autoencoder here + df = pd.DataFrame({"image": images, "label": images}) + return df + + dataset = dataset.map_batches(convert_batch_to_pandas) + return dataset + + +def build_autoencoder_model() -> tf.keras.Model: + model = tf.keras.Sequential( + [ + tf.keras.Input(shape=(784,)), + # encoder + tf.keras.layers.Dense(128, activation="relu"), + tf.keras.layers.Dense(64, activation="relu"), + tf.keras.layers.Dense(32, activation="relu"), + # decoder + tf.keras.layers.Dense(64, activation="relu"), + tf.keras.layers.Dense(128, activation="relu"), + tf.keras.layers.Dense(784, activation="sigmoid"), + ] + ) + return model + + +def train_func(config: dict): + + per_worker_batch_size = config.get("batch_size", 64) + epochs = config.get("epochs", 3) + + dataset_shard = train.get_dataset_shard("train") + + strategy = tf.distribute.MultiWorkerMirroredStrategy() + + with strategy.scope(): + # Model building/compiling need to be within `strategy.scope()`. + multi_worker_model = build_autoencoder_model() + learning_rate = config.get("lr", 0.001) + multi_worker_model.compile( + loss=tf.keras.losses.BinaryCrossentropy(), + optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate), + metrics=[ + "binary_crossentropy", + ], + ) + + def to_tf_dataset(dataset, batch_size): + def to_tensor_iterator(): + for batch in dataset.iter_tf_batches( + batch_size=batch_size, dtypes=tf.float32 + ): + yield batch["image"], batch["label"] + + output_signature = ( + tf.TensorSpec(shape=(None, 784), dtype=tf.float32), + tf.TensorSpec(shape=(None, 784), dtype=tf.float32), + ) + tf_dataset = tf.data.Dataset.from_generator( + to_tensor_iterator, output_signature=output_signature + ) + return prepare_dataset_shard(tf_dataset) + + results = [] + for epoch in range(epochs): + tf_dataset = to_tf_dataset( + dataset=dataset_shard, + batch_size=per_worker_batch_size, + ) + history = multi_worker_model.fit( + tf_dataset, callbacks=[ReportCheckpointCallback()] + ) + results.append(history.history) + return results + + +def train_tensorflow_mnist( + num_workers: int = 2, use_gpu: bool = False, epochs: int = 4 +) -> Result: + train_dataset = get_dataset(split_type="train") + config = {"lr": 1e-3, "batch_size": 64, "epochs": epochs} + scaling_config = ScalingConfig(num_workers=num_workers, use_gpu=use_gpu) + trainer = TensorflowTrainer( + train_loop_per_worker=train_func, + train_loop_config=config, + datasets={"train": train_dataset}, + scaling_config=scaling_config, + ) + + results = trainer.fit() + print(results.metrics) + return results + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--address", required=False, type=str, help="the address to use for Ray" + ) + parser.add_argument( + "--num-workers", + "-n", + type=int, + default=2, + help="Sets number of workers for training.", + ) + parser.add_argument( + "--use-gpu", action="store_true", default=False, help="Enables GPU training" + ) + parser.add_argument( + "--epochs", type=int, default=3, help="Number of epochs to train for." + ) + parser.add_argument( + "--smoke-test", + action="store_true", + default=False, + help="Finish quickly for testing.", + ) + + args, _ = parser.parse_known_args() + + if args.smoke_test: + # 2 workers, 1 for trainer, 1 for datasets + num_gpus = args.num_workers if args.use_gpu else 0 + ray.init(num_cpus=4, num_gpus=num_gpus) + result = train_tensorflow_mnist(num_workers=2, use_gpu=args.use_gpu) + else: + ray.init(address=args.address) + result = train_tensorflow_mnist( + num_workers=args.num_workers, use_gpu=args.use_gpu, epochs=args.epochs + ) + print(result) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_mnist_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_mnist_example.py new file mode 100644 index 0000000000000000000000000000000000000000..3fd5d7c759df6723a7a16a622d70c743519ed638 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_mnist_example.py @@ -0,0 +1,135 @@ +# This example showcases how to use Tensorflow with Ray Train. +# Original code: +# https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras +import argparse +import json +import os + +import numpy as np +import tensorflow as tf +from filelock import FileLock + +from ray.air.integrations.keras import ReportCheckpointCallback +from ray.train import Result, RunConfig, ScalingConfig +from ray.train.tensorflow import TensorflowTrainer + + +def mnist_dataset(batch_size: int) -> tf.data.Dataset: + with FileLock(os.path.expanduser("~/.mnist_lock")): + (x_train, y_train), _ = tf.keras.datasets.mnist.load_data() + # The `x` arrays are in uint8 and have values in the [0, 255] range. + # You need to convert them to float32 with values in the [0, 1] range. + x_train = x_train / np.float32(255) + y_train = y_train.astype(np.int64) + train_dataset = ( + tf.data.Dataset.from_tensor_slices((x_train, y_train)) + .shuffle(60000) + .repeat() + .batch(batch_size) + ) + return train_dataset + + +def build_cnn_model() -> tf.keras.Model: + model = tf.keras.Sequential( + [ + tf.keras.Input(shape=(28, 28)), + tf.keras.layers.Reshape(target_shape=(28, 28, 1)), + tf.keras.layers.Conv2D(32, 3, activation="relu"), + tf.keras.layers.Flatten(), + tf.keras.layers.Dense(128, activation="relu"), + tf.keras.layers.Dense(10), + ] + ) + return model + + +def train_func(config: dict): + per_worker_batch_size = config.get("batch_size", 64) + epochs = config.get("epochs", 3) + steps_per_epoch = config.get("steps_per_epoch", 70) + + tf_config = json.loads(os.environ["TF_CONFIG"]) + num_workers = len(tf_config["cluster"]["worker"]) + + strategy = tf.distribute.MultiWorkerMirroredStrategy() + + global_batch_size = per_worker_batch_size * num_workers + multi_worker_dataset = mnist_dataset(global_batch_size) + + with strategy.scope(): + # Model building/compiling need to be within `strategy.scope()`. + multi_worker_model = build_cnn_model() + learning_rate = config.get("lr", 0.001) + multi_worker_model.compile( + loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), + optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate), + metrics=["accuracy"], + ) + + history = multi_worker_model.fit( + multi_worker_dataset, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + callbacks=[ReportCheckpointCallback()], + ) + results = history.history + return results + + +def train_tensorflow_mnist( + num_workers: int = 2, + use_gpu: bool = False, + epochs: int = 4, + storage_path: str = None, +) -> Result: + config = {"lr": 1e-3, "batch_size": 64, "epochs": epochs} + trainer = TensorflowTrainer( + train_loop_per_worker=train_func, + train_loop_config=config, + scaling_config=ScalingConfig(num_workers=num_workers, use_gpu=use_gpu), + run_config=RunConfig(storage_path=storage_path), + ) + results = trainer.fit() + return results + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--address", required=False, type=str, help="the address to use for Ray" + ) + parser.add_argument( + "--num-workers", + "-n", + type=int, + default=2, + help="Sets number of workers for training.", + ) + parser.add_argument( + "--use-gpu", action="store_true", default=False, help="Enables GPU training" + ) + parser.add_argument( + "--epochs", type=int, default=3, help="Number of epochs to train for." + ) + parser.add_argument( + "--smoke-test", + action="store_true", + default=False, + help="Finish quickly for testing.", + ) + + args, _ = parser.parse_known_args() + + import ray + + if args.smoke_test: + # 2 workers, 1 for trainer, 1 for datasets + num_gpus = args.num_workers if args.use_gpu else 0 + ray.init(num_cpus=4, num_gpus=num_gpus) + train_tensorflow_mnist(num_workers=2, use_gpu=args.use_gpu) + else: + ray.init(address=args.address) + train_tensorflow_mnist( + num_workers=args.num_workers, use_gpu=args.use_gpu, epochs=args.epochs + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_quick_start.py b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_quick_start.py new file mode 100644 index 0000000000000000000000000000000000000000..4b078675960230461f3c6d493d10a3f56ec0ddea --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_quick_start.py @@ -0,0 +1,87 @@ +# ruff: noqa +# fmt: off +# isort: skip_file + +# __tf_setup_begin__ +import sys +import numpy as np + +if sys.version_info >= (3, 12): + # Tensorflow is not installed for Python 3.12 because of keras compatibility. + sys.exit(0) +else: + import tensorflow as tf + +def mnist_dataset(batch_size): + (x_train, y_train), _ = tf.keras.datasets.mnist.load_data() + # The `x` arrays are in uint8 and have values in the [0, 255] range. + # You need to convert them to float32 with values in the [0, 1] range. + x_train = x_train / np.float32(255) + y_train = y_train.astype(np.int64) + train_dataset = tf.data.Dataset.from_tensor_slices( + (x_train, y_train)).shuffle(60000).repeat().batch(batch_size) + return train_dataset + + +def build_and_compile_cnn_model(): + model = tf.keras.Sequential([ + tf.keras.layers.InputLayer(input_shape=(28, 28)), + tf.keras.layers.Reshape(target_shape=(28, 28, 1)), + tf.keras.layers.Conv2D(32, 3, activation='relu'), + tf.keras.layers.Flatten(), + tf.keras.layers.Dense(128, activation='relu'), + tf.keras.layers.Dense(10) + ]) + model.compile( + loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), + optimizer=tf.keras.optimizers.SGD(learning_rate=0.001), + metrics=['accuracy']) + return model +# __tf_setup_end__ + +# __tf_single_begin__ +def train_func(): + batch_size = 64 + single_worker_dataset = mnist_dataset(batch_size) + single_worker_model = build_and_compile_cnn_model() + single_worker_model.fit(single_worker_dataset, epochs=3, steps_per_epoch=70) +# __tf_single_end__ + +# __tf_distributed_begin__ +import json +import os + +def train_func_distributed(): + per_worker_batch_size = 64 + # This environment variable will be set by Ray Train. + tf_config = json.loads(os.environ['TF_CONFIG']) + num_workers = len(tf_config['cluster']['worker']) + + strategy = tf.distribute.MultiWorkerMirroredStrategy() + + global_batch_size = per_worker_batch_size * num_workers + multi_worker_dataset = mnist_dataset(global_batch_size) + + with strategy.scope(): + # Model building/compiling need to be within `strategy.scope()`. + multi_worker_model = build_and_compile_cnn_model() + + multi_worker_model.fit(multi_worker_dataset, epochs=3, steps_per_epoch=70) +# __tf_distributed_end__ + +if __name__ == "__main__": + # __tf_single_run_begin__ + train_func() + # __tf_single_run_end__ + + # __tf_trainer_begin__ + from ray.train.tensorflow import TensorflowTrainer + from ray.train import ScalingConfig + + # For GPU Training, set `use_gpu` to True. + use_gpu = False + + trainer = TensorflowTrainer(train_func_distributed, scaling_config=ScalingConfig(num_workers=4, use_gpu=use_gpu)) + + trainer.fit() + # __tf_trainer_end__ diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_regression_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_regression_example.py new file mode 100644 index 0000000000000000000000000000000000000000..b4c80f88bd7f9e43a58a4561905ce1f0fe590a9a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tensorflow_regression_example.py @@ -0,0 +1,111 @@ +import argparse +import sys + +import ray +from ray import train +from ray.data.preprocessors import Concatenator +from ray.train import Result, ScalingConfig + +if sys.version_info >= (3, 12): + # Skip this test in Python 3.12+ because TensorFlow is not supported. + sys.exit(0) +else: + import tensorflow as tf + + from ray.air.integrations.keras import ReportCheckpointCallback + from ray.train.tensorflow import TensorflowTrainer + + +def build_model() -> tf.keras.Model: + model = tf.keras.Sequential( + [ + tf.keras.layers.InputLayer(input_shape=(100,)), + tf.keras.layers.Dense(10), + tf.keras.layers.Dense(1), + ] + ) + return model + + +def train_func(config: dict): + batch_size = config.get("batch_size", 64) + epochs = config.get("epochs", 3) + + strategy = tf.distribute.MultiWorkerMirroredStrategy() + with strategy.scope(): + # Model building/compiling need to be within `strategy.scope()`. + multi_worker_model = build_model() + multi_worker_model.compile( + optimizer=tf.keras.optimizers.SGD(learning_rate=config.get("lr", 1e-3)), + loss=tf.keras.losses.mean_absolute_error, + metrics=[tf.keras.metrics.mean_squared_error], + ) + + dataset = train.get_dataset_shard("train") + + results = [] + for _ in range(epochs): + tf_dataset = dataset.to_tf( + feature_columns="x", label_columns="y", batch_size=batch_size + ) + history = multi_worker_model.fit( + tf_dataset, callbacks=[ReportCheckpointCallback()] + ) + results.append(history.history) + return results + + +def train_tensorflow_regression(num_workers: int = 2, use_gpu: bool = False) -> Result: + dataset = ray.data.read_csv("s3://anonymous@air-example-data/regression.csv") + columns_to_concatenate = [f"x{i:03}" for i in range(100)] + preprocessor = Concatenator(columns=columns_to_concatenate, output_column_name="x") + dataset = preprocessor.fit_transform(dataset) + + config = {"lr": 1e-3, "batch_size": 32, "epochs": 4} + scaling_config = ScalingConfig(num_workers=num_workers, use_gpu=use_gpu) + trainer = TensorflowTrainer( + train_loop_per_worker=train_func, + train_loop_config=config, + scaling_config=scaling_config, + datasets={"train": dataset}, + ) + results = trainer.fit() + print(results.metrics) + return results + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--address", required=False, type=str, help="the address to use for Ray" + ) + parser.add_argument( + "--num-workers", + "-n", + type=int, + default=2, + help="Sets number of workers for training.", + ) + parser.add_argument( + "--use-gpu", action="store_true", default=False, help="Enables GPU training" + ) + parser.add_argument( + "--smoke-test", + action="store_true", + default=False, + help="Finish quickly for testing.", + ) + + args, _ = parser.parse_known_args() + + if args.smoke_test: + # 2 workers, 1 for trainer, 1 for datasets + num_gpus = args.num_workers if args.use_gpu else 0 + ray.init(num_cpus=4, num_gpus=num_gpus) + result = train_tensorflow_regression(num_workers=2, use_gpu=args.use_gpu) + else: + ray.init(address=args.address) + result = train_tensorflow_regression( + num_workers=args.num_workers, use_gpu=args.use_gpu + ) + print(result) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/tune_tensorflow_autoencoder_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tune_tensorflow_autoencoder_example.py new file mode 100644 index 0000000000000000000000000000000000000000..3c2d90b1887671e8dc35820ca900af10425e64a2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tune_tensorflow_autoencoder_example.py @@ -0,0 +1,77 @@ +import argparse + +import ray +from ray import tune +from ray.train import ScalingConfig +from ray.train.examples.tf.tensorflow_mnist_example import train_func +from ray.train.tensorflow import TensorflowTrainer +from ray.tune.tune_config import TuneConfig +from ray.tune.tuner import Tuner + + +def tune_tensorflow_mnist( + num_workers: int = 2, num_samples: int = 2, use_gpu: bool = False +): + scaling_config = ScalingConfig(num_workers=num_workers, use_gpu=use_gpu) + trainer = TensorflowTrainer( + train_loop_per_worker=train_func, + scaling_config=scaling_config, + ) + tuner = Tuner( + trainer, + tune_config=TuneConfig( + num_samples=num_samples, metric="binary_crossentropy", mode="min" + ), + param_space={ + "train_loop_config": { + "lr": tune.loguniform(1e-4, 1e-1), + "batch_size": tune.choice([32, 64, 128]), + "epochs": 3, + } + }, + ) + best_accuracy = tuner.fit().get_best_result().metrics["binary_crossentropy"] + print(f"Best accuracy config: {best_accuracy}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", + action="store_true", + default=False, + help="Finish quickly for testing.", + ) + parser.add_argument( + "--address", required=False, type=str, help="the address to use for Ray" + ) + parser.add_argument( + "--num-workers", + "-n", + type=int, + default=2, + help="Sets number of workers for training.", + ) + parser.add_argument( + "--num-samples", + type=int, + default=2, + help="Sets number of samples for training.", + ) + parser.add_argument( + "--use-gpu", action="store_true", default=False, help="Enables GPU training" + ) + + args = parser.parse_args() + + if args.smoke_test: + num_gpus = args.num_workers if args.use_gpu else 0 + ray.init(num_cpus=8, num_gpus=num_gpus) + tune_tensorflow_mnist(num_workers=2, num_samples=2, use_gpu=args.use_gpu) + else: + ray.init(address=args.address) + tune_tensorflow_mnist( + num_workers=args.num_workers, + num_samples=args.num_samples, + use_gpu=args.use_gpu, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/examples/tf/tune_tensorflow_mnist_example.py b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tune_tensorflow_mnist_example.py new file mode 100644 index 0000000000000000000000000000000000000000..a1a1860516caa099ad4e1905212e8065a051a72f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/examples/tf/tune_tensorflow_mnist_example.py @@ -0,0 +1,80 @@ +import argparse +import sys + +import ray +from ray import tune +from ray.train import ScalingConfig +from ray.tune.tune_config import TuneConfig +from ray.tune.tuner import Tuner + +if sys.version_info >= (3, 12): + # Skip this test in Python 3.12+ because TensorFlow is not supported. + exit(0) +else: + from ray.train.examples.tf.tensorflow_mnist_example import train_func + from ray.train.tensorflow import TensorflowTrainer + + +def tune_tensorflow_mnist( + num_workers: int = 2, num_samples: int = 2, use_gpu: bool = False +): + trainer = TensorflowTrainer( + train_loop_per_worker=train_func, + scaling_config=ScalingConfig(num_workers=num_workers, use_gpu=use_gpu), + ) + tuner = Tuner( + trainer, + tune_config=TuneConfig(num_samples=num_samples, metric="accuracy", mode="max"), + param_space={ + "train_loop_config": { + "lr": tune.loguniform(1e-4, 1e-1), + "batch_size": tune.choice([32, 64, 128]), + "epochs": 3, + } + }, + ) + best_accuracy = tuner.fit().get_best_result().metrics["accuracy"] + print(f"Best accuracy config: {best_accuracy}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", + action="store_true", + default=False, + help="Finish quickly for testing.", + ) + parser.add_argument( + "--address", required=False, type=str, help="the address to use for Ray" + ) + parser.add_argument( + "--num-workers", + "-n", + type=int, + default=2, + help="Sets number of workers for training.", + ) + parser.add_argument( + "--num-samples", + type=int, + default=2, + help="Sets number of samples for training.", + ) + parser.add_argument( + "--use-gpu", action="store_true", default=False, help="Enables GPU training" + ) + + args = parser.parse_args() + + if args.smoke_test: + num_gpus = args.num_workers if args.use_gpu else 0 + ray.init(num_cpus=8, num_gpus=num_gpus) + tune_tensorflow_mnist(num_workers=2, num_samples=2, use_gpu=args.use_gpu) + else: + ray.init(address=args.address) + tune_tensorflow_mnist( + num_workers=args.num_workers, + num_samples=args.num_samples, + use_gpu=args.use_gpu, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/horovod/__init__.py b/venv/lib/python3.10/site-packages/ray/train/horovod/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..73f9e7ab585a1d577f589e9c795a5560d830169a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/horovod/__init__.py @@ -0,0 +1,22 @@ +# isort: off +try: + import horovod # noqa: F401 +except ModuleNotFoundError: + raise ModuleNotFoundError( + "Horovod isn't installed. To install Horovod with PyTorch support, run 'pip " + "install 'horovod[pytorch]''. To install Horovod with TensorFlow support, " + "run 'pip install 'horovod[tensorflow]''." + ) +# isort: on + +from ray.train.horovod.config import HorovodConfig +from ray.train.horovod.horovod_trainer import HorovodTrainer +from ray.train.v2._internal.constants import is_v2_enabled + +if is_v2_enabled(): + from ray.train.v2.horovod.horovod_trainer import HorovodTrainer # noqa: F811 + +__all__ = ["HorovodConfig", "HorovodTrainer"] + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/horovod/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/horovod/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..862bd71c32c25b570b75f0fb80f9d3a47ddf124e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/horovod/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/horovod/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/horovod/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..271ffaed4d1a28ece064de32e168aad9f79a3455 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/horovod/__pycache__/config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/horovod/__pycache__/horovod_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/horovod/__pycache__/horovod_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a34bd5a98b6dc6ac795def6f2ac849d0d010c23d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/horovod/__pycache__/horovod_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/horovod/config.py b/venv/lib/python3.10/site-packages/ray/train/horovod/config.py new file mode 100644 index 0000000000000000000000000000000000000000..acd56091d3a4d7bc505bad007c0d394d103269ae --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/horovod/config.py @@ -0,0 +1,159 @@ +import os +from dataclasses import dataclass +from typing import Optional, Set + +from horovod.ray.runner import Coordinator +from horovod.ray.utils import detect_nics, nics_to_env_var +from horovod.runner.common.util import secret, timeout + +import ray +from ray.train._internal.utils import update_env_vars +from ray.train._internal.worker_group import Worker, WorkerGroup +from ray.train.backend import Backend, BackendConfig +from ray.util import PublicAPI + + +@PublicAPI(stability="beta") +@dataclass +class HorovodConfig(BackendConfig): + """Configurations for Horovod setup. + + See https://github.com/horovod/horovod/blob/master/horovod/runner/common/util/settings.py # noqa: E501 + + Args: + nics (Optional[Set[str]): Network interfaces that can be used for + communication. + verbose: Horovod logging verbosity. + key (Optional[str]): Secret used for communication between workers. + ssh_port (Optional[int]): Port for SSH server running on worker nodes. + ssh_identity_file (Optional[str]): Path to the identity file to + ssh into different hosts on the cluster. + ssh_str (Optional[str]): CAUTION WHEN USING THIS. Private key + file contents. Writes the private key to ssh_identity_file. + timeout_s: Timeout parameter for Gloo rendezvous. + placement_group_timeout_s: Timeout parameter for Ray + Placement Group creation. Currently unused. + """ + + nics: Optional[Set[str]] = None + verbose: int = 1 + key: Optional[str] = None + ssh_port: Optional[int] = None + ssh_identity_file: Optional[str] = None + ssh_str: Optional[str] = None + timeout_s: int = 300 + placement_group_timeout_s: int = 100 + + @property + def start_timeout(self): + return timeout.Timeout( + self.timeout_s, + message="Timed out waiting for {activity}. Please " + "check connectivity between servers. You " + "may need to increase the --start-timeout " + "parameter if you have too many servers.", + ) + + def __post_init__(self): + if self.ssh_str and not os.path.exists(self.ssh_identity_file): + with open(self.ssh_identity_file, "w") as f: + os.chmod(self.ssh_identity_file, 0o600) + f.write(self.ssh_str) + + if self.key is None: + self.key = secret.make_secret_key() + + @property + def backend_cls(self): + return _HorovodBackend + + +class _HorovodBackend(Backend): + share_cuda_visible_devices: bool = True + + def on_start(self, worker_group: WorkerGroup, backend_config: HorovodConfig): + # TODO(matt): Implement placement group strategies in BackendExecutor. + + # Initialize workers with Horovod environment variables + setup_futures = [] + for rank in range(len(worker_group)): + worker_node_id = worker_group.workers[rank].metadata.node_id + setup_futures.append( + worker_group.execute_single_async( + rank, + _init_env_vars, + rank, + len(worker_group), + worker_node_id, + ) + ) + ray.get(setup_futures) + + # Use Horovod Ray Coordinator + # backend_config as settings + self.coordinator = Coordinator(backend_config) + + # Get all the hostnames of all workers + node_ids = [w.metadata.node_id for w in worker_group.workers] + hostnames = [w.metadata.hostname for w in worker_group.workers] + # Register each hostname to the coordinator. assumes the hostname + # ordering is the same. + for rank, (hostname, node_id) in enumerate(zip(hostnames, node_ids)): + self.coordinator.register(hostname, node_id, rank) + all_info = self.coordinator.finalize_registration() + + setup_futures = [] + for rank, local_cross_env_var in all_info.items(): + setup_futures.append( + worker_group.execute_single_async( + rank, update_env_vars, local_cross_env_var + ) + ) + ray.get(setup_futures) + + coordinator_envs = self.coordinator.establish_rendezvous() + + # Get one worker from each host/node. + node_worker_indexes = [node_ids.index(node_id) for node_id in set(node_ids)] + node_workers = [ + _HorovodWorkerWrapper(worker_group.workers[worker_index]) + for worker_index in node_worker_indexes + ] + assert len(node_workers) == len(self.coordinator.hostnames) + + nics = detect_nics( + backend_config, + all_host_names=list(self.coordinator.hostnames), + node_workers=node_workers, + ) + coordinator_envs.update(nics_to_env_var(nics)) + + worker_group.execute(update_env_vars, coordinator_envs) + + +def _init_env_vars(world_rank: int, world_size: int, node_id: str): + """Initialize Horovod environment variables.""" + os.environ["HOROVOD_HOSTNAME"] = node_id + os.environ["HOROVOD_RANK"] = str(world_rank) + os.environ["HOROVOD_SIZE"] = str(world_size) + + +# TODO(tgaddair): temporary workaround for Horovod's worker discovery logic, +# which requires passing in an extra parameter as part of the RayExecutor +# API. This will be removed in the future as we migrate more of the +# RayExecutor utils into Ray Train. +# See: https://github.com/horovod/horovod/blob/v0.23.0/horovod/ray/driver_service.py#L9 # noqa: E501 +@dataclass +class _HorovodWorkerWrapper: + w: Worker + + @property + def execute(self): + w = self.w + + class ExecuteHandle: + def remote(self, func, *args, **kwargs): + _ = None + return w.actor._RayTrainWorker__execute.remote(func, _, *args, **kwargs) + + return ExecuteHandle() diff --git a/venv/lib/python3.10/site-packages/ray/train/horovod/horovod_trainer.py b/venv/lib/python3.10/site-packages/ray/train/horovod/horovod_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..93936cac759ad897a1b1cef9c66998ae1de896ae --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/horovod/horovod_trainer.py @@ -0,0 +1,202 @@ +from typing import Any, Callable, Dict, Optional, Union + +from ray.air.config import RunConfig, ScalingConfig +from ray.train import Checkpoint, DataConfig +from ray.train.data_parallel_trainer import DataParallelTrainer +from ray.train.horovod.config import HorovodConfig +from ray.train.trainer import GenDataset +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="beta") +class HorovodTrainer(DataParallelTrainer): + """A Trainer for data parallel Horovod training. + + This Trainer runs the function ``train_loop_per_worker`` on multiple Ray + Actors. These actors already have the necessary Horovod setup already + configured for distributed Horovod training. + + The ``train_loop_per_worker`` function is expected to take in either 0 or 1 + arguments: + + .. testcode:: + + def train_loop_per_worker(): + ... + + .. testcode:: + + def train_loop_per_worker(config: Dict): + ... + + If ``train_loop_per_worker`` accepts an argument, then + ``train_loop_config`` will be passed in as the argument. This is useful if you + want to tune the values in ``train_loop_config`` as hyperparameters. + + If the ``datasets`` dict contains a training dataset (denoted by + the "train" key), then it will be split into multiple dataset + shards that can then be accessed by ``ray.train.get_dataset_shard("train")`` inside + ``train_loop_per_worker``. All the other datasets will not be split and + ``ray.train.get_dataset_shard(...)`` will return the entire Dataset. + + Inside the ``train_loop_per_worker`` function, you can use any of the + :ref:`Ray Train loop methods `. + + .. testcode:: + + from ray import train + + def train_loop_per_worker(): + # Report intermediate results for callbacks or logging and + # checkpoint data. + train.report(...) + + # Returns dict of last saved checkpoint. + train.get_checkpoint() + + # Returns the Dataset shard for the given key. + train.get_dataset_shard("my_dataset") + + # Returns the total number of workers executing training. + train.get_context().get_world_size() + + # Returns the rank of this worker. + train.get_context().get_world_rank() + + # Returns the rank of the worker on the current node. + train.get_context().get_local_rank() + + Any returns from the ``train_loop_per_worker`` will be discarded and not + used or persisted anywhere. + + You could use ``TensorflowPredictor`` or ``TorchPredictor`` in conjunction with + HorovodTrainer. You must save the model under the "model" kwarg in the + ``Checkpoint`` passed to ``train.report()``, so that it can be used by + corresponding predictors. + + Example: + + + .. testcode:: + :skipif: True + + import os + import tempfile + + import ray + import horovod.torch as hvd + import torch + import torch.nn as nn + + from ray import train + import ray.train.torch # Need this to use `train.torch.get_device()` + from ray.train import Checkpoint, ScalingConfig + from ray.train.horovod import HorovodTrainer + + # If using GPUs, set this to True. + use_gpu = False + + input_size = 1 + layer_size = 15 + output_size = 1 + num_epochs = 3 + + class NeuralNetwork(nn.Module): + def __init__(self): + super(NeuralNetwork, self).__init__() + self.layer1 = nn.Linear(input_size, layer_size) + self.relu = nn.ReLU() + self.layer2 = nn.Linear(layer_size, output_size) + def forward(self, input): + return self.layer2(self.relu(self.layer1(input))) + + def train_loop_per_worker(): + hvd.init() + dataset_shard = train.get_dataset_shard("train") + model = NeuralNetwork() + device = train.torch.get_device() + model.to(device) + loss_fn = nn.MSELoss() + lr_scaler = 1 + optimizer = torch.optim.SGD(model.parameters(), lr=0.1 * lr_scaler) + # Horovod: wrap optimizer with DistributedOptimizer. + optimizer = hvd.DistributedOptimizer( + optimizer, + named_parameters=model.named_parameters(), + op=hvd.Average, + ) + for epoch in range(num_epochs): + model.train() + for batch in dataset_shard.iter_torch_batches( + batch_size=32, dtypes=torch.float + ): + inputs, labels = torch.unsqueeze(batch["x"], 1), batch["y"] + outputs = model(inputs) + loss = loss_fn(outputs, labels) + optimizer.zero_grad() + loss.backward() + optimizer.step() + print(f"epoch: {epoch}, loss: {loss.item()}") + + # Save a model checkpoint at the end of each epoch + with tempfile.TemporaryDirectory() as temp_checkpoint_dir: + ckpt_path = os.path.join(temp_checkpoint_dir, "model.pt") + torch.save(model.state_dict(), ckpt_path) + train.report( + {"loss": loss.item(), "epoch": epoch}, + checkpoint=Checkpoint.from_directory(temp_checkpoint_dir), + ) + + train_dataset = ray.data.from_items([{"x": x, "y": x + 1} for x in range(32)]) + scaling_config = ScalingConfig(num_workers=3, use_gpu=use_gpu) + trainer = HorovodTrainer( + train_loop_per_worker=train_loop_per_worker, + scaling_config=scaling_config, + datasets={"train": train_dataset}, + ) + result = trainer.fit() + + Args: + train_loop_per_worker: The training function to execute. + This can either take in no arguments or a ``config`` dict. + train_loop_config: Configurations to pass into + ``train_loop_per_worker`` if it accepts an argument. + horovod_config: Configuration for setting up the Horovod backend. + If set to None, use the default configuration. This replaces the + ``backend_config`` arg of ``DataParallelTrainer``. + scaling_config: Configuration for how to scale data parallel training. + dataset_config: Configuration for dataset ingest. + run_config: Configuration for the execution of the training run. + datasets: Any Datasets to use for training. Use + the key "train" to denote which dataset is the training + dataset. + resume_from_checkpoint: A checkpoint to resume training from. + metadata: Dict that should be made available via + `ray.train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + """ + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + horovod_config: Optional[HorovodConfig] = None, + scaling_config: Optional[ScalingConfig] = None, + dataset_config: Optional[DataConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + super().__init__( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + backend_config=horovod_config or HorovodConfig(), + scaling_config=scaling_config, + dataset_config=dataset_config, + run_config=run_config, + datasets=datasets, + resume_from_checkpoint=resume_from_checkpoint, + metadata=metadata, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/huggingface/__init__.py b/venv/lib/python3.10/site-packages/ray/train/huggingface/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/huggingface/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/huggingface/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8510fb3740233399dff1dab9ff06f585919844a8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/huggingface/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/__init__.py b/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..870fe4ee94b873e077a7bf0d3bf48429e1bf8df0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/__init__.py @@ -0,0 +1,12 @@ +from ray.train.huggingface.transformers._transformers_utils import ( + RayTrainReportCallback, + prepare_trainer, +) + +__all__ = [ + "RayTrainReportCallback", + "prepare_trainer", +] + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecabdb943db7b88aa9fa0ce539b8436a468e11eb Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/__pycache__/_transformers_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/__pycache__/_transformers_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25d23a594254bfe2a2239f55cdcaaa2e8f5abb1d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/__pycache__/_transformers_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/_transformers_utils.py b/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/_transformers_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c522b81cfbf1c8756e26fd42c2692f3bdb421964 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/huggingface/transformers/_transformers_utils.py @@ -0,0 +1,143 @@ +import logging +import shutil +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Iterator, Optional, Type + +from torch.utils.data import DataLoader, Dataset, IterableDataset + +import ray +from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag +from ray.data.iterator import _IterableFromIterator +from ray.train import Checkpoint +from ray.util import PublicAPI + +logger = logging.getLogger(__name__) + + +TRANSFORMERS_IMPORT_ERROR: Optional[ImportError] = None + +try: + import transformers.trainer + from transformers import Trainer + from transformers.trainer_callback import TrainerCallback +except ImportError as e: + TRANSFORMERS_IMPORT_ERROR = e + TrainerCallback = object + + +@PublicAPI(stability="beta") +class RayTrainReportCallback(TrainerCallback): + """A simple callback to report checkpoints and metrics to Ray Train. + + This callback is a subclass of `transformers.TrainerCallback + `_ + and overrides the `TrainerCallback.on_save()` method. After + a new checkpoint get saved, it fetches the latest metric dictionary + from `TrainerState.log_history` and reports it with the latest checkpoint + to Ray Train. + + Checkpoints will be saved in the following structure:: + + checkpoint_00000*/ Ray Train Checkpoint + └─ checkpoint/ Hugging Face Transformers Checkpoint + + For customized reporting and checkpointing logic, implement your own + `transformers.TrainerCallback` following this user + guide: :ref:`Saving and Loading Checkpoints `. + + Note that users should ensure that the logging, evaluation, and saving frequencies + are properly configured so that the monitoring metric is always up-to-date + when `transformers.Trainer` saves a checkpoint. + + Suppose the monitoring metric is reported from evaluation stage: + + Some valid configurations: + - evaluation_strategy == save_strategy == "epoch" + - evaluation_strategy == save_strategy == "steps", save_steps % eval_steps == 0 + + Some invalid configurations: + - evaluation_strategy != save_strategy + - evaluation_strategy == save_strategy == "steps", save_steps % eval_steps != 0 + + """ + + CHECKPOINT_NAME = "checkpoint" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + record_extra_usage_tag(TagKey.TRAIN_TRANSFORMERS_RAYTRAINREPORTCALLBACK, "1") + + def on_save(self, args, state, control, **kwargs): + """Event called after a checkpoint save.""" + with TemporaryDirectory() as tmpdir: + # Aggregate all the logged metrics + metrics = {} + for log in state.log_history: + metrics.update(log) + + # Copy ckpt files and construct a Ray Train Checkpoint + source_ckpt_path = transformers.trainer.get_last_checkpoint(args.output_dir) + if source_ckpt_path is not None: + target_ckpt_path = Path(tmpdir, self.CHECKPOINT_NAME).as_posix() + shutil.copytree(source_ckpt_path, target_ckpt_path) + checkpoint = Checkpoint.from_directory(tmpdir) + else: + checkpoint = None + + # Report latest metrics and checkpoint to Ray Train + ray.train.report(metrics=metrics, checkpoint=checkpoint) + + +class RayTorchIterableDataset(IterableDataset): + """Wrapper class for ray data iterables.""" + + def __init__(self, data_iterable) -> None: + super().__init__() + self.data_iterable = data_iterable + + def __iter__(self) -> Iterator: + return iter(self.data_iterable) + + +@PublicAPI(stability="beta") +def prepare_trainer(trainer: "Trainer") -> "Trainer": + """Prepare your HuggingFace Transformer Trainer for Ray Train. + + This utility function enable the trainer integrates with Ray Data Integration. + Internally, it overrides the `get_train_dataloader` and `get_eval_dataloader` + methods and inject the data integration logics if the `train_dataset` and + `eval_dataset` are Ray Data Iterables. + """ + + if TRANSFORMERS_IMPORT_ERROR is not None: + raise TRANSFORMERS_IMPORT_ERROR + + base_trainer_class: Type[transformers.trainer.Trainer] = trainer.__class__ + + class RayTransformersTrainer(base_trainer_class): + """A Wrapper of `transformers.Trainer` for Ray Data Integration.""" + + def get_train_dataloader(self) -> DataLoader: + if isinstance(self.train_dataset, _IterableFromIterator): + dataset = RayTorchIterableDataset(self.train_dataset) + return DataLoader(dataset, batch_size=1, collate_fn=lambda x: x[0]) + else: + return super().get_train_dataloader() + + def get_eval_dataloader( + self, eval_dataset: Optional[Dataset] = None + ) -> DataLoader: + if eval_dataset is None: + eval_dataset = self.eval_dataset + + if isinstance(eval_dataset, _IterableFromIterator): + dataset = RayTorchIterableDataset(eval_dataset) + return DataLoader(dataset, batch_size=1, collate_fn=lambda x: x[0]) + else: + return super().get_eval_dataloader(eval_dataset) + + trainer.__class__ = RayTransformersTrainer + + record_extra_usage_tag(TagKey.TRAIN_TRANSFORMERS_PREPARE_TRAINER, "1") + return trainer diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/__init__.py b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92d09f80d0e08dbc4815d45a7f0c042cbe71587e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__init__.py @@ -0,0 +1,21 @@ +from ray.train.lightgbm._lightgbm_utils import RayTrainReportCallback +from ray.train.lightgbm.config import LightGBMConfig, get_network_params +from ray.train.lightgbm.lightgbm_checkpoint import LightGBMCheckpoint +from ray.train.lightgbm.lightgbm_predictor import LightGBMPredictor +from ray.train.lightgbm.lightgbm_trainer import LightGBMTrainer +from ray.train.v2._internal.constants import is_v2_enabled + +if is_v2_enabled(): + from ray.train.v2.lightgbm.lightgbm_trainer import LightGBMTrainer # noqa: F811 + +__all__ = [ + "RayTrainReportCallback", + "LightGBMCheckpoint", + "LightGBMPredictor", + "LightGBMTrainer", + "LightGBMConfig", + "get_network_params", +] + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..debd581ced4ca28d668a6a3f1a599bfefea491d8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/_lightgbm_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/_lightgbm_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b45fc721e9df7b2fcd0bbd0789c56b1637065b76 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/_lightgbm_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22eb5cab0de7036d4d680f243fb2fe00424bb644 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/lightgbm_checkpoint.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/lightgbm_checkpoint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c265a1e491a2163dff7fecb141de0135c742f2bf Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/lightgbm_checkpoint.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/lightgbm_predictor.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/lightgbm_predictor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..876fd81d58537fdcf9fbb907a09687e2fc4ed0f8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/lightgbm_predictor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/lightgbm_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/lightgbm_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80bd1945d9de56d5baccfbc7e403eaa63e8b3d46 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/lightgbm_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/v2.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/v2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebb0df6662159be7df1d0ce4b4c04bd9c978e218 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/lightgbm/__pycache__/v2.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/_lightgbm_utils.py b/venv/lib/python3.10/site-packages/ray/train/lightgbm/_lightgbm_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..15c4e344bd16dd19e84b3863eb4614bcff5fbf44 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/lightgbm/_lightgbm_utils.py @@ -0,0 +1,170 @@ +import tempfile +from contextlib import contextmanager +from pathlib import Path +from typing import Callable, Dict, List, Optional, Union + +from lightgbm.basic import Booster +from lightgbm.callback import CallbackEnv + +import ray.train +from ray.train import Checkpoint +from ray.tune.utils import flatten_dict +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="beta") +class RayTrainReportCallback: + """Creates a callback that reports metrics and checkpoints model. + + Args: + metrics: Metrics to report. If this is a list, + each item should be a metric key reported by LightGBM, + and it will be reported to Ray Train/Tune under the same name. + This can also be a dict of {: }, + which can be used to rename LightGBM default metrics. + filename: Customize the saved checkpoint file type by passing + a filename. Defaults to "model.txt". + frequency: How often to save checkpoints, in terms of iterations. + Defaults to 0 (no checkpoints are saved during training). + checkpoint_at_end: Whether or not to save a checkpoint at the end of training. + results_postprocessing_fn: An optional Callable that takes in + the metrics dict that will be reported (after it has been flattened) + and returns a modified dict. + + Examples + -------- + + Reporting checkpoints and metrics to Ray Tune when running many + independent xgboost trials (without data parallelism within a trial). + + .. testcode:: + :skipif: True + + import lightgbm + + from ray.train.lightgbm import RayTrainReportCallback + + config = { + # ... + "metric": ["binary_logloss", "binary_error"], + } + + # Report only log loss to Tune after each validation epoch. + bst = lightgbm.train( + ..., + callbacks=[ + RayTrainReportCallback( + metrics={"loss": "eval-binary_logloss"}, frequency=1 + ) + ], + ) + + Loading a model from a checkpoint reported by this callback. + + .. testcode:: + :skipif: True + + from ray.train.lightgbm import RayTrainReportCallback + + # Get a `Checkpoint` object that is saved by the callback during training. + result = trainer.fit() + booster = RayTrainReportCallback.get_model(result.checkpoint) + + """ + + CHECKPOINT_NAME = "model.txt" + + def __init__( + self, + metrics: Optional[Union[str, List[str], Dict[str, str]]] = None, + filename: str = CHECKPOINT_NAME, + frequency: int = 0, + checkpoint_at_end: bool = True, + results_postprocessing_fn: Optional[ + Callable[[Dict[str, Union[float, List[float]]]], Dict[str, float]] + ] = None, + ): + if isinstance(metrics, str): + metrics = [metrics] + self._metrics = metrics + self._filename = filename + self._frequency = frequency + self._checkpoint_at_end = checkpoint_at_end + self._results_postprocessing_fn = results_postprocessing_fn + + @classmethod + def get_model( + cls, checkpoint: Checkpoint, filename: str = CHECKPOINT_NAME + ) -> Booster: + """Retrieve the model stored in a checkpoint reported by this callback. + + Args: + checkpoint: The checkpoint object returned by a training run. + The checkpoint should be saved by an instance of this callback. + filename: The filename to load the model from, which should match + the filename used when creating the callback. + """ + with checkpoint.as_directory() as checkpoint_path: + return Booster(model_file=Path(checkpoint_path, filename).as_posix()) + + def _get_report_dict(self, evals_log: Dict[str, Dict[str, list]]) -> dict: + result_dict = flatten_dict(evals_log, delimiter="-") + if not self._metrics: + report_dict = result_dict + else: + report_dict = {} + for key in self._metrics: + if isinstance(self._metrics, dict): + metric = self._metrics[key] + else: + metric = key + report_dict[key] = result_dict[metric] + if self._results_postprocessing_fn: + report_dict = self._results_postprocessing_fn(report_dict) + return report_dict + + def _get_eval_result(self, env: CallbackEnv) -> dict: + eval_result = {} + for entry in env.evaluation_result_list: + data_name, eval_name, result = entry[0:3] + if len(entry) > 4: + stdv = entry[4] + suffix = "-mean" + else: + stdv = None + suffix = "" + if data_name not in eval_result: + eval_result[data_name] = {} + eval_result[data_name][eval_name + suffix] = result + if stdv is not None: + eval_result[data_name][eval_name + "-stdv"] = stdv + return eval_result + + @contextmanager + def _get_checkpoint(self, model: Booster) -> Optional[Checkpoint]: + if ray.train.get_context().get_world_rank() in (0, None): + with tempfile.TemporaryDirectory() as temp_checkpoint_dir: + model.save_model(Path(temp_checkpoint_dir, self._filename).as_posix()) + yield Checkpoint.from_directory(temp_checkpoint_dir) + else: + yield None + + def __call__(self, env: CallbackEnv) -> None: + eval_result = self._get_eval_result(env) + report_dict = self._get_report_dict(eval_result) + + # Ex: if frequency=2, checkpoint_at_end=True and num_boost_rounds=11, + # you will checkpoint at iterations 1, 3, 5, ..., 9, and 10 (checkpoint_at_end) + # (iterations count from 0) + on_last_iter = env.iteration == env.end_iteration - 1 + should_checkpoint_at_end = on_last_iter and self._checkpoint_at_end + should_checkpoint_with_frequency = ( + self._frequency != 0 and (env.iteration + 1) % self._frequency == 0 + ) + should_checkpoint = should_checkpoint_at_end or should_checkpoint_with_frequency + + if should_checkpoint: + with self._get_checkpoint(model=env.model) as checkpoint: + ray.train.report(report_dict, checkpoint=checkpoint) + else: + ray.train.report(report_dict) diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/config.py b/venv/lib/python3.10/site-packages/ray/train/lightgbm/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c57f4b6d17c71c563b25e59af6b4ecda1cc7cbeb --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/lightgbm/config.py @@ -0,0 +1,89 @@ +import logging +import threading +from dataclasses import dataclass +from typing import Any, Dict, Optional + +import ray +from ray.train._internal.utils import get_address_and_port +from ray.train._internal.worker_group import WorkerGroup +from ray.train.backend import Backend, BackendConfig + +logger = logging.getLogger(__name__) + + +# Global LightGBM distributed network configuration for each worker process. +_lightgbm_network_params: Optional[Dict[str, Any]] = None +_lightgbm_network_params_lock = threading.Lock() + + +def get_network_params() -> Dict[str, Any]: + """Returns the network parameters to enable LightGBM distributed training.""" + global _lightgbm_network_params + + with _lightgbm_network_params_lock: + if not _lightgbm_network_params: + logger.warning( + "`ray.train.lightgbm.get_network_params` was called outside " + "the context of a `ray.train.lightgbm.LightGBMTrainer`. " + "The current process has no knowledge of the distributed training " + "worker group, so this method will return an empty dict. " + "Please call this within the training loop of a " + "`ray.train.lightgbm.LightGBMTrainer`. " + "If you are in fact calling this within a `LightGBMTrainer`, " + "this is unexpected: please file a bug report to the Ray Team." + ) + return {} + + return _lightgbm_network_params.copy() + + +def _set_network_params( + num_machines: int, + local_listen_port: int, + machines: str, +): + global _lightgbm_network_params + + with _lightgbm_network_params_lock: + assert ( + _lightgbm_network_params is None + ), "LightGBM network params are already initialized." + _lightgbm_network_params = dict( + num_machines=num_machines, + local_listen_port=local_listen_port, + machines=machines, + ) + + +@dataclass +class LightGBMConfig(BackendConfig): + """Configuration for LightGBM distributed data-parallel training setup. + + See the LightGBM docs for more information on the "network parameters" + that Ray Train sets up for you: + https://lightgbm.readthedocs.io/en/latest/Parameters.html#network-parameters + """ + + @property + def backend_cls(self): + return _LightGBMBackend + + +class _LightGBMBackend(Backend): + def on_training_start( + self, worker_group: WorkerGroup, backend_config: LightGBMConfig + ): + node_ips_and_ports = worker_group.execute(get_address_and_port) + ports = [port for _, port in node_ips_and_ports] + machines = ",".join( + [f"{node_ip}:{port}" for node_ip, port in node_ips_and_ports] + ) + num_machines = len(worker_group) + ray.get( + [ + worker_group.execute_single_async( + rank, _set_network_params, num_machines, ports[rank], machines + ) + for rank in range(len(worker_group)) + ] + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/lightgbm_checkpoint.py b/venv/lib/python3.10/site-packages/ray/train/lightgbm/lightgbm_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..e42adf3ad84e5a14e7357fc82dbe37d1b181ed56 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/lightgbm/lightgbm_checkpoint.py @@ -0,0 +1,72 @@ +import tempfile +from pathlib import Path +from typing import TYPE_CHECKING, Optional + +import lightgbm + +from ray.train._internal.framework_checkpoint import FrameworkCheckpoint +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.data.preprocessor import Preprocessor + + +@PublicAPI(stability="beta") +class LightGBMCheckpoint(FrameworkCheckpoint): + """A :py:class:`~ray.train.Checkpoint` with LightGBM-specific functionality.""" + + MODEL_FILENAME = "model.txt" + + @classmethod + def from_model( + cls, + booster: lightgbm.Booster, + *, + preprocessor: Optional["Preprocessor"] = None, + path: Optional[str] = None, + ) -> "LightGBMCheckpoint": + """Create a :py:class:`~ray.train.Checkpoint` that stores a LightGBM model. + + Args: + booster: The LightGBM model to store in the checkpoint. + preprocessor: A fitted preprocessor to be applied before inference. + path: The path to the directory where the checkpoint file will be saved. + This should start as an empty directory, since the *entire* + directory will be treated as the checkpoint when reported. + By default, a temporary directory will be created. + + Returns: + An :py:class:`LightGBMCheckpoint` containing the specified ``Estimator``. + + Examples: + .. testcode:: + + import lightgbm + import numpy as np + from ray.train.lightgbm import LightGBMCheckpoint + + train_X = np.array([[1, 2], [3, 4]]) + train_y = np.array([0, 1]) + + model = lightgbm.LGBMClassifier().fit(train_X, train_y) + checkpoint = LightGBMCheckpoint.from_model(model.booster_) + """ + checkpoint_path = Path(path or tempfile.mkdtemp()) + + if not checkpoint_path.is_dir(): + raise ValueError(f"`path` must be a directory, but got: {checkpoint_path}") + + booster.save_model(checkpoint_path.joinpath(cls.MODEL_FILENAME).as_posix()) + + checkpoint = cls.from_directory(checkpoint_path.as_posix()) + if preprocessor: + checkpoint.set_preprocessor(preprocessor) + + return checkpoint + + def get_model(self) -> lightgbm.Booster: + """Retrieve the LightGBM model stored in this checkpoint.""" + with self.as_directory() as checkpoint_path: + return lightgbm.Booster( + model_file=Path(checkpoint_path, self.MODEL_FILENAME).as_posix() + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/lightgbm_predictor.py b/venv/lib/python3.10/site-packages/ray/train/lightgbm/lightgbm_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..57c4cbe76471f015f067929c8912d528ce6bb4c7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/lightgbm/lightgbm_predictor.py @@ -0,0 +1,153 @@ +from typing import TYPE_CHECKING, List, Optional, Union + +import lightgbm +import pandas as pd +from pandas.api.types import is_object_dtype + +from ray.air.constants import TENSOR_COLUMN_NAME +from ray.air.data_batch_type import DataBatchType +from ray.air.util.data_batch_conversion import _unwrap_ndarray_object_type_if_needed +from ray.train.lightgbm import LightGBMCheckpoint +from ray.train.predictor import Predictor +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.data.preprocessor import Preprocessor + + +@PublicAPI(stability="beta") +class LightGBMPredictor(Predictor): + """A predictor for LightGBM models. + + Args: + model: The LightGBM booster to use for predictions. + preprocessor: A preprocessor used to transform data batches prior + to prediction. + """ + + def __init__( + self, model: lightgbm.Booster, preprocessor: Optional["Preprocessor"] = None + ): + self.model = model + super().__init__(preprocessor) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(model={self.model!r}, " + f"preprocessor={self._preprocessor!r})" + ) + + @classmethod + def from_checkpoint(cls, checkpoint: LightGBMCheckpoint) -> "LightGBMPredictor": + """Instantiate the predictor from a LightGBMCheckpoint. + + Args: + checkpoint: The checkpoint to load the model and preprocessor from. + + """ + model = checkpoint.get_model() + preprocessor = checkpoint.get_preprocessor() + return cls(model=model, preprocessor=preprocessor) + + def predict( + self, + data: DataBatchType, + feature_columns: Optional[Union[List[str], List[int]]] = None, + **predict_kwargs, + ) -> DataBatchType: + """Run inference on data batch. + + Args: + data: A batch of input data. + feature_columns: The names or indices of the columns in the + data to use as features to predict on. If None, then use + all columns in ``data``. + **predict_kwargs: Keyword arguments passed to + ``lightgbm.Booster.predict``. + + Examples: + .. testcode:: + + import numpy as np + import lightgbm as lgbm + from ray.train.lightgbm import LightGBMPredictor + + train_X = np.array([[1, 2], [3, 4]]) + train_y = np.array([0, 1]) + + model = lgbm.LGBMClassifier().fit(train_X, train_y) + predictor = LightGBMPredictor(model=model.booster_) + + data = np.array([[1, 2], [3, 4]]) + predictions = predictor.predict(data) + + # Only use first and second column as the feature + data = np.array([[1, 2, 8], [3, 4, 9]]) + predictions = predictor.predict(data, feature_columns=[0, 1]) + + import pandas as pd + import lightgbm as lgbm + from ray.train.lightgbm import LightGBMPredictor + + train_X = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) + train_y = pd.Series([0, 1]) + + model = lgbm.LGBMClassifier().fit(train_X, train_y) + predictor = LightGBMPredictor(model=model.booster_) + + # Pandas dataframe. + data = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) + predictions = predictor.predict(data) + + # Only use first and second column as the feature + data = pd.DataFrame([[1, 2, 8], [3, 4, 9]], columns=["A", "B", "C"]) + predictions = predictor.predict(data, feature_columns=["A", "B"]) + + Returns: + Prediction result. + + """ + return Predictor.predict( + self, data, feature_columns=feature_columns, **predict_kwargs + ) + + def _predict_pandas( + self, + data: "pd.DataFrame", + feature_columns: Optional[Union[List[str], List[int]]] = None, + **predict_kwargs, + ) -> pd.DataFrame: + feature_names = None + if TENSOR_COLUMN_NAME in data: + data = data[TENSOR_COLUMN_NAME].to_numpy() + data = _unwrap_ndarray_object_type_if_needed(data) + if feature_columns: + # In this case feature_columns is a list of integers + data = data[:, feature_columns] + # Turn into dataframe to make dtype resolution easy + data = pd.DataFrame(data, columns=feature_names) + data = data.infer_objects() + + # Pandas does not detect categorical dtypes. Any remaining object + # dtypes are probably categories, so convert them. + # This will fail if we have a category composed entirely of + # integers, but this is the best we can do here. + update_dtypes = {} + for column in data.columns: + dtype = data.dtypes[column] + if is_object_dtype(dtype): + update_dtypes[column] = pd.CategoricalDtype() + + if update_dtypes: + data = data.astype(update_dtypes, copy=False) + elif feature_columns: + # feature_columns is a list of integers or strings + data = data[feature_columns] + + df = pd.DataFrame(self.model.predict(data, **predict_kwargs)) + df.columns = ( + ["predictions"] + if len(df.columns) == 1 + else [f"predictions_{i}" for i in range(len(df.columns))] + ) + return df diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/lightgbm_trainer.py b/venv/lib/python3.10/site-packages/ray/train/lightgbm/lightgbm_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..754cf7a961ccfff1a1e7f66cafc5bd8d3d0a8a05 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/lightgbm/lightgbm_trainer.py @@ -0,0 +1,316 @@ +import logging +from functools import partial +from typing import Any, Callable, Dict, Optional, Union + +import lightgbm + +import ray +from ray.train import Checkpoint +from ray.train.constants import TRAIN_DATASET_KEY +from ray.train.lightgbm._lightgbm_utils import RayTrainReportCallback +from ray.train.lightgbm.config import LightGBMConfig +from ray.train.lightgbm.v2 import LightGBMTrainer as SimpleLightGBMTrainer +from ray.train.trainer import GenDataset +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + + +LEGACY_LIGHTGBMGBM_TRAINER_DEPRECATION_MESSAGE = ( + "Passing in `lightgbm.train` kwargs such as `params`, `num_boost_round`, " + "`label_column`, etc. to `LightGBMTrainer` is deprecated " + "in favor of the new API which accepts a `train_loop_per_worker` argument, " + "similar to the other DataParallelTrainer APIs (ex: TorchTrainer). " + "See this issue for more context: " + "https://github.com/ray-project/ray/issues/50042" +) + + +def _lightgbm_train_fn_per_worker( + config: dict, + label_column: str, + num_boost_round: int, + dataset_keys: set, + lightgbm_train_kwargs: dict, +): + checkpoint = ray.train.get_checkpoint() + starting_model = None + remaining_iters = num_boost_round + if checkpoint: + starting_model = RayTrainReportCallback.get_model(checkpoint) + starting_iter = starting_model.current_iteration() + remaining_iters = num_boost_round - starting_iter + logger.info( + f"Model loaded from checkpoint will train for " + f"additional {remaining_iters} iterations (trees) in order " + "to achieve the target number of iterations " + f"({num_boost_round=})." + ) + + train_ds_iter = ray.train.get_dataset_shard(TRAIN_DATASET_KEY) + train_df = train_ds_iter.materialize().to_pandas() + + eval_ds_iters = { + k: ray.train.get_dataset_shard(k) + for k in dataset_keys + if k != TRAIN_DATASET_KEY + } + eval_dfs = {k: d.materialize().to_pandas() for k, d in eval_ds_iters.items()} + + train_X, train_y = train_df.drop(label_column, axis=1), train_df[label_column] + train_set = lightgbm.Dataset(train_X, label=train_y) + + # NOTE: Include the training dataset in the evaluation datasets. + # This allows `train-*` metrics to be calculated and reported. + valid_sets = [train_set] + valid_names = [TRAIN_DATASET_KEY] + + for eval_name, eval_df in eval_dfs.items(): + eval_X, eval_y = eval_df.drop(label_column, axis=1), eval_df[label_column] + valid_sets.append(lightgbm.Dataset(eval_X, label=eval_y)) + valid_names.append(eval_name) + + # Add network params of the worker group to enable distributed training. + config.update(ray.train.lightgbm.v2.get_network_params()) + + lightgbm.train( + params=config, + train_set=train_set, + num_boost_round=remaining_iters, + valid_sets=valid_sets, + valid_names=valid_names, + init_model=starting_model, + **lightgbm_train_kwargs, + ) + + +@PublicAPI(stability="beta") +class LightGBMTrainer(SimpleLightGBMTrainer): + """A Trainer for distributed data-parallel LightGBM training. + + Example + ------- + + .. testcode:: + + import lightgbm + + import ray.data + import ray.train + from ray.train.lightgbm import RayTrainReportCallback, LightGBMTrainer + + def train_fn_per_worker(config: dict): + # (Optional) Add logic to resume training state from a checkpoint. + # ray.train.get_checkpoint() + + # 1. Get the dataset shard for the worker and convert to a `lightgbm.Dataset` + train_ds_iter, eval_ds_iter = ( + ray.train.get_dataset_shard("train"), + ray.train.get_dataset_shard("validation"), + ) + train_ds, eval_ds = train_ds_iter.materialize(), eval_ds_iter.materialize() + train_df, eval_df = train_ds.to_pandas(), eval_ds.to_pandas() + train_X, train_y = train_df.drop("y", axis=1), train_df["y"] + eval_X, eval_y = eval_df.drop("y", axis=1), eval_df["y"] + dtrain = lightgbm.Dataset(train_X, label=train_y) + deval = lightgbm.Dataset(eval_X, label=eval_y) + + params = { + "objective": "regression", + "metric": "l2", + "learning_rate": 1e-4, + "subsample": 0.5, + "max_depth": 2, + } + + # 2. Do distributed data-parallel training. + # Ray Train sets up the necessary coordinator processes and + # environment variables for your workers to communicate with each other. + bst = lightgbm.train( + params, + train_set=dtrain, + valid_sets=[deval], + valid_names=["validation"], + num_boost_round=10, + callbacks=[RayTrainReportCallback()], + ) + + train_ds = ray.data.from_items([{"x": x, "y": x + 1} for x in range(32)]) + eval_ds = ray.data.from_items([{"x": x, "y": x + 1} for x in range(16)]) + trainer = LightGBMTrainer( + train_fn_per_worker, + datasets={"train": train_ds, "validation": eval_ds}, + scaling_config=ray.train.ScalingConfig(num_workers=4), + ) + result = trainer.fit() + booster = RayTrainReportCallback.get_model(result.checkpoint) + + .. testoutput:: + :hide: + + ... + + Args: + train_loop_per_worker: The training function to execute on each worker. + This function can either take in zero arguments or a single ``Dict`` + argument which is set by defining ``train_loop_config``. + Within this function you can use any of the + :ref:`Ray Train Loop utilities `. + train_loop_config: A configuration ``Dict`` to pass in as an argument to + ``train_loop_per_worker``. + This is typically used for specifying hyperparameters. + lightgbm_config: The configuration for setting up the distributed lightgbm + backend. Defaults to using the "rabit" backend. + See :class:`~ray.train.lightgbm.LightGBMConfig` for more info. + datasets: The Ray Datasets to use for training and validation. + dataset_config: The configuration for ingesting the input ``datasets``. + By default, all the Ray Datasets are split equally across workers. + See :class:`~ray.train.DataConfig` for more details. + scaling_config: The configuration for how to scale data parallel training. + ``num_workers`` determines how many Python processes are used for training, + and ``use_gpu`` determines whether or not each process should use GPUs. + See :class:`~ray.train.ScalingConfig` for more info. + run_config: The configuration for the execution of the training run. + See :class:`~ray.train.RunConfig` for more info. + resume_from_checkpoint: A checkpoint to resume training from. + This checkpoint can be accessed from within ``train_loop_per_worker`` + by calling ``ray.train.get_checkpoint()``. + metadata: Dict that should be made available via + `ray.train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + label_column: [Deprecated] Name of the label column. A column with this name + must be present in the training dataset. + params: [Deprecated] LightGBM training parameters. + Refer to `LightGBM documentation `_ + for a list of possible parameters. + num_boost_round: [Deprecated] Target number of boosting iterations (trees in the model). + Note that unlike in ``lightgbm.train``, this is the target number + of trees, meaning that if you set ``num_boost_round=10`` and pass a model + that has already been trained for 5 iterations, it will be trained for 5 + iterations more, instead of 10 more. + **train_kwargs: [Deprecated] Additional kwargs passed to ``lightgbm.train()`` function. + """ + + _handles_checkpoint_freq = True + _handles_checkpoint_at_end = True + + def __init__( + self, + train_loop_per_worker: Optional[ + Union[Callable[[], None], Callable[[Dict], None]] + ] = None, + *, + train_loop_config: Optional[Dict] = None, + lightgbm_config: Optional[LightGBMConfig] = None, + scaling_config: Optional[ray.train.ScalingConfig] = None, + run_config: Optional[ray.train.RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + dataset_config: Optional[ray.train.DataConfig] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + metadata: Optional[Dict[str, Any]] = None, + # TODO: [Deprecated] Legacy LightGBMTrainer API + label_column: Optional[str] = None, + params: Optional[Dict[str, Any]] = None, + num_boost_round: Optional[int] = None, + **train_kwargs, + ): + # TODO: [Deprecated] Legacy LightGBMTrainer API + legacy_api = train_loop_per_worker is None + if legacy_api: + train_loop_per_worker = self._get_legacy_train_fn_per_worker( + lightgbm_train_kwargs=train_kwargs, + run_config=run_config, + label_column=label_column, + num_boost_round=num_boost_round, + datasets=datasets, + ) + train_loop_config = params or {} + # TODO(justinvyu): [Deprecated] Legacy XGBoostTrainer API + # elif train_kwargs: + # _log_deprecation_warning( + # "Passing `lightgbm.train` kwargs to `LightGBMTrainer` is deprecated. " + # f"Got kwargs: {train_kwargs.keys()}\n" + # "Please pass in a `train_loop_per_worker` function instead, " + # "which has full flexibility on the call to `lightgbm.train(**kwargs)`. " + # f"{LEGACY_LIGHTGBMGBM_TRAINER_DEPRECATION_MESSAGE}" + # ) + + super(LightGBMTrainer, self).__init__( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + lightgbm_config=lightgbm_config, + scaling_config=scaling_config, + run_config=run_config, + datasets=datasets, + dataset_config=dataset_config, + resume_from_checkpoint=resume_from_checkpoint, + metadata=metadata, + ) + + def _get_legacy_train_fn_per_worker( + self, + lightgbm_train_kwargs: Dict, + run_config: Optional[ray.train.RunConfig], + datasets: Optional[Dict[str, GenDataset]], + label_column: Optional[str], + num_boost_round: Optional[int], + ) -> Callable[[Dict], None]: + """Get the training function for the legacy LightGBMTrainer API.""" + + datasets = datasets or {} + if not datasets.get(TRAIN_DATASET_KEY): + raise ValueError( + "`datasets` must be provided for the LightGBMTrainer API " + "if `train_loop_per_worker` is not provided. " + "This dict must contain the training dataset under the " + f"key: '{TRAIN_DATASET_KEY}'. " + f"Got keys: {list(datasets.keys())}" + ) + if not label_column: + raise ValueError( + "`label_column` must be provided for the LightGBMTrainer API " + "if `train_loop_per_worker` is not provided. " + "This is the column name of the label in the dataset." + ) + + num_boost_round = num_boost_round or 10 + + # TODO: [Deprecated] Legacy LightGBMTrainer API + # _log_deprecation_warning(LEGACY_LIGHTGBMGBM_TRAINER_DEPRECATION_MESSAGE) + + # Initialize a default Ray Train metrics/checkpoint reporting callback if needed + callbacks = lightgbm_train_kwargs.get("callbacks", []) + user_supplied_callback = any( + isinstance(callback, RayTrainReportCallback) for callback in callbacks + ) + callback_kwargs = {} + if run_config: + checkpoint_frequency = run_config.checkpoint_config.checkpoint_frequency + checkpoint_at_end = run_config.checkpoint_config.checkpoint_at_end + + callback_kwargs["frequency"] = checkpoint_frequency + # Default `checkpoint_at_end=True` unless the user explicitly sets it. + callback_kwargs["checkpoint_at_end"] = ( + checkpoint_at_end if checkpoint_at_end is not None else True + ) + + if not user_supplied_callback: + callbacks.append(RayTrainReportCallback(**callback_kwargs)) + lightgbm_train_kwargs["callbacks"] = callbacks + + train_fn_per_worker = partial( + _lightgbm_train_fn_per_worker, + label_column=label_column, + num_boost_round=num_boost_round, + dataset_keys=set(datasets), + lightgbm_train_kwargs=lightgbm_train_kwargs, + ) + return train_fn_per_worker + + @classmethod + def get_model( + cls, + checkpoint: Checkpoint, + ) -> lightgbm.Booster: + """Retrieve the LightGBM model stored in this checkpoint.""" + return RayTrainReportCallback.get_model(checkpoint) diff --git a/venv/lib/python3.10/site-packages/ray/train/lightgbm/v2.py b/venv/lib/python3.10/site-packages/ray/train/lightgbm/v2.py new file mode 100644 index 0000000000000000000000000000000000000000..62287e0fe4c7d8d01d0027fa868396bae0cea2f8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/lightgbm/v2.py @@ -0,0 +1,131 @@ +import logging +from typing import Any, Callable, Dict, Optional, Union + +import ray.train +from ray.train import Checkpoint +from ray.train.data_parallel_trainer import DataParallelTrainer +from ray.train.lightgbm.config import LightGBMConfig, get_network_params # noqa: F401 +from ray.train.trainer import GenDataset + +logger = logging.getLogger(__name__) + + +class LightGBMTrainer(DataParallelTrainer): + """A Trainer for distributed data-parallel LightGBM training. + + Example + ------- + + .. testcode:: + + import lightgbm as lgb + + import ray.data + import ray.train + from ray.train.lightgbm import RayTrainReportCallback, LightGBMTrainer + + + def train_fn_per_worker(config: dict): + # (Optional) Add logic to resume training state from a checkpoint. + # ray.train.get_checkpoint() + + # 1. Get the dataset shard for the worker and convert to a `lgb.Dataset` + train_ds_iter, eval_ds_iter = ( + ray.train.get_dataset_shard("train"), + ray.train.get_dataset_shard("validation"), + ) + train_ds, eval_ds = train_ds_iter.materialize(), eval_ds_iter.materialize() + train_df, eval_df = train_ds.to_pandas(), eval_ds.to_pandas() + train_X, train_y = train_df.drop("y", axis=1), train_df["y"] + eval_X, eval_y = eval_df.drop("y", axis=1), eval_df["y"] + + train_set = lgb.Dataset(train_X, label=train_y) + eval_set = lgb.Dataset(eval_X, label=eval_y) + + # 2. Run distributed data-parallel training. + # `get_network_params` sets up the necessary configurations for LightGBM + # to set up the data parallel training worker group on your Ray cluster. + params = { + "objective": "regression", + # Adding the line below is the only change needed + # for your `lgb.train` call! + **ray.train.lightgbm.v2.get_network_params(), + } + lgb.train( + params, + train_set, + valid_sets=[eval_set], + valid_names=["eval"], + callbacks=[RayTrainReportCallback()], + ) + + train_ds = ray.data.from_items([{"x": x, "y": x + 1} for x in range(32)]) + eval_ds = ray.data.from_items( + [{"x": x, "y": x + 1} for x in range(32, 32 + 16)] + ) + trainer = LightGBMTrainer( + train_fn_per_worker, + datasets={"train": train_ds, "validation": eval_ds}, + scaling_config=ray.train.ScalingConfig(num_workers=4), + ) + result = trainer.fit() + booster = RayTrainReportCallback.get_model(result.checkpoint) + + .. testoutput:: + :hide: + + ... + + Args: + train_loop_per_worker: The training function to execute on each worker. + This function can either take in zero arguments or a single ``Dict`` + argument which is set by defining ``train_loop_config``. + Within this function you can use any of the + :ref:`Ray Train Loop utilities `. + train_loop_config: A configuration ``Dict`` to pass in as an argument to + ``train_loop_per_worker``. + This is typically used for specifying hyperparameters. + lightgbm_config: The configuration for setting up the distributed lightgbm + backend. See :class:`~ray.train.lightgbm.LightGBMConfig` for more info. + datasets: The Ray Datasets to use for training and validation. + dataset_config: The configuration for ingesting the input ``datasets``. + By default, all the Ray Dataset are split equally across workers. + See :class:`~ray.train.DataConfig` for more details. + scaling_config: The configuration for how to scale data parallel training. + ``num_workers`` determines how many Python processes are used for training, + and ``use_gpu`` determines whether or not each process should use GPUs. + See :class:`~ray.train.ScalingConfig` for more info. + run_config: The configuration for the execution of the training run. + See :class:`~ray.train.RunConfig` for more info. + resume_from_checkpoint: A checkpoint to resume training from. + This checkpoint can be accessed from within ``train_loop_per_worker`` + by calling ``ray.train.get_checkpoint()``. + metadata: Dict that should be made available via + `ray.train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + """ + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + lightgbm_config: Optional[LightGBMConfig] = None, + scaling_config: Optional[ray.train.ScalingConfig] = None, + run_config: Optional[ray.train.RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + dataset_config: Optional[ray.train.DataConfig] = None, + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + super(LightGBMTrainer, self).__init__( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + backend_config=lightgbm_config or LightGBMConfig(), + scaling_config=scaling_config, + dataset_config=dataset_config, + run_config=run_config, + datasets=datasets, + resume_from_checkpoint=resume_from_checkpoint, + metadata=metadata, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/lightning/__init__.py b/venv/lib/python3.10/site-packages/ray/train/lightning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c8e413a1030837512e86386b76f1c12ce21b2a92 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/lightning/__init__.py @@ -0,0 +1,39 @@ +# isort: off +try: + import lightning # noqa: F401 +except ModuleNotFoundError: + try: + import pytorch_lightning # noqa: F401 + except ModuleNotFoundError: + raise ModuleNotFoundError( + "PyTorch Lightning isn't installed. To install PyTorch Lightning, " + "please run 'pip install lightning'" + ) +# isort: on + +from ray.train.lightning._lightning_utils import ( + RayDDPStrategy, + RayDeepSpeedStrategy, + RayFSDPStrategy, + RayLightningEnvironment, + RayTrainReportCallback, + prepare_trainer, +) +from ray.train.v2._internal.constants import is_v2_enabled + +if is_v2_enabled(): + from ray.train.v2.lightning.lightning_utils import ( # noqa: F811 + RayTrainReportCallback, + ) + +__all__ = [ + "prepare_trainer", + "RayDDPStrategy", + "RayFSDPStrategy", + "RayDeepSpeedStrategy", + "RayLightningEnvironment", + "RayTrainReportCallback", +] + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/lightning/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/lightning/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51ad19f4b93b0623036e5e81fec587daae36e012 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/lightning/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/lightning/__pycache__/_lightning_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/lightning/__pycache__/_lightning_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c658696f7304df8a7c86a2e3873e8e4cae34d2c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/lightning/__pycache__/_lightning_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/lightning/_lightning_utils.py b/venv/lib/python3.10/site-packages/ray/train/lightning/_lightning_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ba42fe12f4ba36db70620a7aeba310a6b0ccc66f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/lightning/_lightning_utils.py @@ -0,0 +1,295 @@ +import logging +import os +import shutil +import tempfile +from pathlib import Path +from typing import Any, Dict + +import torch +from packaging.version import Version + +import ray +from ray import train +from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag +from ray.train import Checkpoint +from ray.util import PublicAPI + + +def import_lightning(): # noqa: F402 + try: + import lightning.pytorch as pl + except ModuleNotFoundError: + import pytorch_lightning as pl + return pl + + +pl = import_lightning() + +_LIGHTNING_GREATER_EQUAL_2_0 = Version(pl.__version__) >= Version("2.0.0") +_LIGHTNING_LESS_THAN_2_1 = Version(pl.__version__) < Version("2.1.0") +_TORCH_GREATER_EQUAL_1_12 = Version(torch.__version__) >= Version("1.12.0") +_TORCH_FSDP_AVAILABLE = _TORCH_GREATER_EQUAL_1_12 and torch.distributed.is_available() + +try: + from lightning.pytorch.plugins.environments import LightningEnvironment +except ModuleNotFoundError: + from pytorch_lightning.plugins.environments import LightningEnvironment + +if _LIGHTNING_GREATER_EQUAL_2_0: + FSDPStrategy = pl.strategies.FSDPStrategy +else: + FSDPStrategy = pl.strategies.DDPFullyShardedStrategy + +if _TORCH_FSDP_AVAILABLE: + from torch.distributed.fsdp import ( + FullStateDictConfig, + FullyShardedDataParallel, + StateDictType, + ) + + +logger = logging.getLogger(__name__) + +LIGHTNING_REPORT_STAGE_KEY = "_report_on" + + +@PublicAPI(stability="beta") +class RayDDPStrategy(pl.strategies.DDPStrategy): + """Subclass of DDPStrategy to ensure compatibility with Ray orchestration. + + For a full list of initialization arguments, please refer to: + https://lightning.ai/docs/pytorch/stable/api/lightning.pytorch.strategies.DDPStrategy.html + + Note that `process_group_backend`, `timeout`, and `start_method` are disabled here, + please specify these arguments in :class:`~ray.train.torch.TorchConfig` instead. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + record_extra_usage_tag(TagKey.TRAIN_LIGHTNING_RAYDDPSTRATEGY, "1") + + @property + def root_device(self) -> torch.device: + return ray.train.torch.get_device() + + @property + def distributed_sampler_kwargs(self) -> Dict[str, Any]: + return dict( + num_replicas=self.world_size, + rank=self.global_rank, + ) + + +@PublicAPI(stability="beta") +class RayFSDPStrategy(FSDPStrategy): # noqa: F821 + """Subclass of FSDPStrategy to ensure compatibility with Ray orchestration. + + For a full list of initialization arguments, please refer to: + https://lightning.ai/docs/pytorch/stable/api/lightning.pytorch.strategies.FSDPStrategy.html + + .. note:: + It is recommended to upgrade `lightning>=2.1` or above when using FSDP + with Lightning, since Lightning starts to natively support `state_dict_type`, + `sharding_strategy`, `auto_wrap_policy` and other FSDP configurations from 2.1. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + record_extra_usage_tag(TagKey.TRAIN_LIGHTNING_RAYFSDPSTRATEGY, "1") + + @property + def root_device(self) -> torch.device: + return ray.train.torch.get_device() + + @property + def distributed_sampler_kwargs(self) -> Dict[str, Any]: + return dict( + num_replicas=self.world_size, + rank=self.global_rank, + ) + + def lightning_module_state_dict(self) -> Dict[str, Any]: + """Gathers the full state dict to rank 0 on CPU. + + FSDP checkpointing is broken in Lightning 2.0.x. This subclass patches the + behavior to perform a full state dict checkpointing, gathering the checkpoint + shards on rank 0 CPU. Upgrade to `lightning>=2.1` to do sharded state dict + checkpointing. + + See the note in the class docstring for more details. + """ + + assert self.model is not None, "Failed to get the state dict for a None model!" + + if ( + _TORCH_FSDP_AVAILABLE + and _LIGHTNING_GREATER_EQUAL_2_0 + and _LIGHTNING_LESS_THAN_2_1 + ): + with FullyShardedDataParallel.state_dict_type( + module=self.model, + state_dict_type=StateDictType.FULL_STATE_DICT, + state_dict_config=FullStateDictConfig( + offload_to_cpu=True, rank0_only=True + ), + ): + state_dict = self.model.state_dict() + + ckpt_state_dict = {} + prefix_len = len("_forward_module.") + for k, v in state_dict.items(): + if k.startswith("_forward_module."): + non_prefixed_key = k[prefix_len:] + ckpt_state_dict[non_prefixed_key] = v + else: + ckpt_state_dict[k] = v + return ckpt_state_dict + else: + # Otherwise Lightning uses Fairscale FSDP, no need to unshard by ourself. + return super().lightning_module_state_dict() + + +@PublicAPI(stability="beta") +class RayDeepSpeedStrategy(pl.strategies.DeepSpeedStrategy): + """Subclass of DeepSpeedStrategy to ensure compatibility with Ray orchestration. + + For a full list of initialization arguments, please refer to: + https://lightning.ai/docs/pytorch/stable/api/lightning.pytorch.strategies.DeepSpeedStrategy.html + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + record_extra_usage_tag(TagKey.TRAIN_LIGHTNING_RAYDEEPSPEEDSTRATEGY, "1") + + @property + def root_device(self) -> torch.device: + return ray.train.torch.get_device() + + @property + def distributed_sampler_kwargs(self) -> Dict[str, Any]: + return dict( + num_replicas=self.world_size, + rank=self.global_rank, + ) + + +@PublicAPI(stability="beta") +class RayLightningEnvironment(LightningEnvironment): # noqa: F821 + """Setup Lightning DDP training environment for Ray cluster.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + record_extra_usage_tag(TagKey.TRAIN_LIGHTNING_RAYLIGHTNINGENVIRONMENT, "1") + + def world_size(self) -> int: + return train.get_context().get_world_size() + + def global_rank(self) -> int: + return train.get_context().get_world_rank() + + def local_rank(self) -> int: + return train.get_context().get_local_rank() + + def node_rank(self) -> int: + return train.get_context().get_node_rank() + + def set_world_size(self, size: int) -> None: + # Disable it since `world_size()` directly returns data from Train context. + pass + + def set_global_rank(self, rank: int) -> None: + # Disable it since `global_rank()` directly returns data from Train. + pass + + def teardown(self): + pass + + +@PublicAPI(stability="beta") +def prepare_trainer(trainer: pl.Trainer) -> pl.Trainer: + """Prepare the PyTorch Lightning Trainer for distributed execution.""" + + # Check strategy class + valid_strategy_class = [RayDDPStrategy, RayFSDPStrategy, RayDeepSpeedStrategy] + + if not any(isinstance(trainer.strategy, cls) for cls in valid_strategy_class): + raise RuntimeError( + f"Invalid strategy class: {type(trainer.strategy)}. To use " + "PyTorch Lightning with Ray, the strategy object should be one of " + f"{[cls.__name__ for cls in valid_strategy_class]} class " + "or its subclass." + ) + + # Check cluster environment + cluster_environment = getattr(trainer.strategy, "cluster_environment", None) + if cluster_environment and not isinstance( + cluster_environment, RayLightningEnvironment + ): + raise RuntimeError( + "Invalid cluster environment plugin. The expected class is" + "`ray.train.lightning.RayLightningEnvironment` " + f"but got {type(cluster_environment)}!" + ) + + record_extra_usage_tag(TagKey.TRAIN_LIGHTNING_PREPARE_TRAINER, "1") + return trainer + + +@PublicAPI(stability="beta") +class RayTrainReportCallback(pl.callbacks.Callback): + """A simple callback that reports checkpoints to Ray on train epoch end. + + This callback is a subclass of `lightning.pytorch.callbacks.Callback + `_. + + It fetches the latest `trainer.callback_metrics` and reports together with + the checkpoint on each training epoch end. + + Checkpoints will be saved in the following structure:: + + checkpoint_00000*/ Ray Train Checkpoint + └─ checkpoint.ckpt PyTorch Lightning Checkpoint + + For customized reporting and checkpointing logic, implement your own + `lightning.pytorch.callbacks.Callback` following this user + guide: :ref:`Saving and Loading Checkpoints `. + """ + + CHECKPOINT_NAME = "checkpoint.ckpt" + + def __init__(self) -> None: + super().__init__() + self.trial_name = train.get_context().get_trial_name() + self.local_rank = train.get_context().get_local_rank() + self.tmpdir_prefix = Path(tempfile.gettempdir(), self.trial_name).as_posix() + if os.path.isdir(self.tmpdir_prefix) and self.local_rank == 0: + shutil.rmtree(self.tmpdir_prefix) + + record_extra_usage_tag(TagKey.TRAIN_LIGHTNING_RAYTRAINREPORTCALLBACK, "1") + + def on_train_epoch_end(self, trainer, pl_module) -> None: + # Creates a checkpoint dir with fixed name + tmpdir = Path(self.tmpdir_prefix, str(trainer.current_epoch)).as_posix() + os.makedirs(tmpdir, exist_ok=True) + + # Fetch metrics + metrics = trainer.callback_metrics + metrics = {k: v.item() for k, v in metrics.items()} + + # (Optional) Add customized metrics + metrics["epoch"] = trainer.current_epoch + metrics["step"] = trainer.global_step + + # Save checkpoint to local + ckpt_path = Path(tmpdir, self.CHECKPOINT_NAME).as_posix() + trainer.save_checkpoint(ckpt_path, weights_only=False) + + # Report to train session + checkpoint = Checkpoint.from_directory(tmpdir) + train.report(metrics=metrics, checkpoint=checkpoint) + + # Add a barrier to ensure all workers finished reporting here + trainer.strategy.barrier() + + if self.local_rank == 0: + shutil.rmtree(tmpdir) diff --git a/venv/lib/python3.10/site-packages/ray/train/predictor.py b/venv/lib/python3.10/site-packages/ray/train/predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..0d4ef100e360b14cdabc71a7fc9a3dc4e25d771b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/predictor.py @@ -0,0 +1,254 @@ +import abc +from typing import Callable, Dict, Optional, Type, Union + +import numpy as np +import pandas as pd + +from ray.air.data_batch_type import DataBatchType +from ray.air.util.data_batch_conversion import ( + BatchFormat, + _convert_batch_type_to_numpy, + _convert_batch_type_to_pandas, +) +from ray.data import Preprocessor +from ray.train import Checkpoint +from ray.util.annotations import DeveloperAPI, PublicAPI + +try: + import pyarrow + + pa_table = pyarrow.Table +except ImportError: + pa_table = None + +# Reverse mapping from data batch type to batch format. +TYPE_TO_ENUM: Dict[Type[DataBatchType], BatchFormat] = { + np.ndarray: BatchFormat.NUMPY, + dict: BatchFormat.NUMPY, + pd.DataFrame: BatchFormat.PANDAS, +} + + +@PublicAPI(stability="beta") +class PredictorNotSerializableException(RuntimeError): + """Error raised when trying to serialize a Predictor instance.""" + + pass + + +@PublicAPI(stability="beta") +class Predictor(abc.ABC): + """Predictors load models from checkpoints to perform inference. + + .. note:: + The base ``Predictor`` class cannot be instantiated directly. Only one of + its subclasses can be used. + + **How does a Predictor work?** + + Predictors expose a ``predict`` method that accepts an input batch of type + ``DataBatchType`` and outputs predictions of the same type as the input batch. + + When the ``predict`` method is called the following occurs: + + - The input batch is converted into a pandas DataFrame. Tensor input (like a + ``np.ndarray``) will be converted into a single column Pandas Dataframe. + - If there is a :ref:`Preprocessor ` saved in the provided + :class:`Checkpoint `, the preprocessor will be used to + transform the DataFrame. + - The transformed DataFrame will be passed to the model for inference (via the + ``predictor._predict_pandas`` method). + - The predictions will be outputted by ``predict`` in the same type as the + original input. + + **How do I create a new Predictor?** + + To implement a new Predictor for your particular framework, you should subclass + the base ``Predictor`` and implement the following two methods: + + 1. ``_predict_pandas``: Given a pandas.DataFrame input, return a + pandas.DataFrame containing predictions. + 2. ``from_checkpoint``: Logic for creating a Predictor from a + :class:`Checkpoint `. + 3. Optionally ``_predict_numpy`` for better performance when working with + tensor data to avoid extra copies from Pandas conversions. + """ + + def __init__(self, preprocessor: Optional[Preprocessor] = None): + """Subclasseses must call Predictor.__init__() to set a preprocessor.""" + self._preprocessor: Optional[Preprocessor] = preprocessor + # Whether tensor columns should be automatically cast from/to the tensor + # extension type at UDF boundaries. This can be overridden by subclasses. + self._cast_tensor_columns = False + + @classmethod + @abc.abstractmethod + def from_checkpoint(cls, checkpoint: Checkpoint, **kwargs) -> "Predictor": + """Create a specific predictor from a checkpoint. + + Args: + checkpoint: Checkpoint to load predictor data from. + kwargs: Arguments specific to predictor implementations. + + Returns: + Predictor: Predictor object. + """ + raise NotImplementedError + + @classmethod + def from_pandas_udf( + cls, pandas_udf: Callable[[pd.DataFrame], pd.DataFrame] + ) -> "Predictor": + """Create a Predictor from a Pandas UDF. + + Args: + pandas_udf: A function that takes a pandas.DataFrame and other + optional kwargs and returns a pandas.DataFrame. + """ + + class PandasUDFPredictor(Predictor): + @classmethod + def from_checkpoint(cls, checkpoint: Checkpoint, **kwargs) -> "Predictor": + return PandasUDFPredictor() + + def _predict_pandas(self, df, **kwargs) -> "pd.DataFrame": + return pandas_udf(df, **kwargs) + + return PandasUDFPredictor() + + def get_preprocessor(self) -> Optional[Preprocessor]: + """Get the preprocessor to use prior to executing predictions.""" + return self._preprocessor + + def set_preprocessor(self, preprocessor: Optional[Preprocessor]) -> None: + """Set the preprocessor to use prior to executing predictions.""" + self._preprocessor = preprocessor + + @classmethod + @DeveloperAPI + def preferred_batch_format(cls) -> BatchFormat: + """Batch format hint for upstream producers to try yielding best block format. + + The preferred batch format to use if both `_predict_pandas` and + `_predict_numpy` are implemented. Defaults to Pandas. + + Can be overriden by predictor classes depending on the framework type, + e.g. TorchPredictor prefers Numpy and XGBoostPredictor prefers Pandas as + native batch format. + + """ + return BatchFormat.PANDAS + + @classmethod + def _batch_format_to_use(cls) -> BatchFormat: + """Determine the batch format to use for the predictor.""" + has_pandas_implemented = cls._predict_pandas != Predictor._predict_pandas + has_numpy_implemented = cls._predict_numpy != Predictor._predict_numpy + if has_pandas_implemented and has_numpy_implemented: + return cls.preferred_batch_format() + elif has_pandas_implemented: + return BatchFormat.PANDAS + elif has_numpy_implemented: + return BatchFormat.NUMPY + else: + raise NotImplementedError( + f"Predictor {cls.__name__} must implement at least one of " + "`_predict_pandas` and `_predict_numpy`." + ) + + def _set_cast_tensor_columns(self): + """Enable automatic tensor column casting. + + If this is called on a predictor, the predictor will cast tensor columns to + NumPy ndarrays in the input to the preprocessors and cast tensor columns back to + the tensor extension type in the prediction outputs. + """ + self._cast_tensor_columns = True + + def predict(self, data: DataBatchType, **kwargs) -> DataBatchType: + """Perform inference on a batch of data. + + Args: + data: A batch of input data of type ``DataBatchType``. + kwargs: Arguments specific to predictor implementations. These are passed + directly to ``_predict_numpy`` or ``_predict_pandas``. + + Returns: + DataBatchType: + Prediction result. The return type will be the same as the input type. + """ + if not hasattr(self, "_preprocessor"): + raise NotImplementedError( + "Subclasses of Predictor must call Predictor.__init__(preprocessor)." + ) + try: + batch_format = TYPE_TO_ENUM[type(data)] + except KeyError: + raise RuntimeError( + f"Invalid input data type of {type(data)}, supported " + f"types: {list(TYPE_TO_ENUM.keys())}" + ) + + if self._preprocessor: + data = self._preprocessor.transform_batch(data) + + batch_format_to_use = self._batch_format_to_use() + + # We can finish prediction as long as one predict method is implemented. + # For prediction, we have to return back in the same format as the input. + if batch_format == BatchFormat.PANDAS: + if batch_format_to_use == BatchFormat.PANDAS: + return self._predict_pandas( + _convert_batch_type_to_pandas(data), **kwargs + ) + elif batch_format_to_use == BatchFormat.NUMPY: + return _convert_batch_type_to_pandas( + self._predict_numpy(_convert_batch_type_to_numpy(data), **kwargs) + ) + elif batch_format == BatchFormat.NUMPY: + if batch_format_to_use == BatchFormat.PANDAS: + return _convert_batch_type_to_numpy( + self._predict_pandas(_convert_batch_type_to_pandas(data), **kwargs) + ) + elif batch_format_to_use == BatchFormat.NUMPY: + return self._predict_numpy(_convert_batch_type_to_numpy(data), **kwargs) + + @DeveloperAPI + def _predict_pandas(self, data: "pd.DataFrame", **kwargs) -> "pd.DataFrame": + """Perform inference on a Pandas DataFrame. + + Args: + data: A pandas DataFrame to perform predictions on. + kwargs: Arguments specific to the predictor implementation. + + Returns: + A pandas DataFrame containing the prediction result. + + """ + raise NotImplementedError + + @DeveloperAPI + def _predict_numpy( + self, data: Union[np.ndarray, Dict[str, np.ndarray]], **kwargs + ) -> Union[np.ndarray, Dict[str, np.ndarray]]: + """Perform inference on a Numpy data. + + All Predictors working with tensor data (like deep learning predictors) + should implement this method. + + Args: + data: A Numpy ndarray or dictionary of ndarrays to perform predictions on. + kwargs: Arguments specific to the predictor implementation. + + Returns: + A Numpy ndarray or dictionary of ndarray containing the prediction result. + + """ + raise NotImplementedError + + def __reduce__(self): + raise PredictorNotSerializableException( + "Predictor instances are not serializable. Instead, you may want " + "to serialize a checkpoint and initialize the Predictor with " + "Predictor.from_checkpoint." + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/session.py b/venv/lib/python3.10/site-packages/ray/train/session.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/__init__.py b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a156e133d5facccb9b06707d4b6f15dad509ca17 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__init__.py @@ -0,0 +1,32 @@ +# isort: off +try: + import tensorflow as tf # noqa: F401 +except ModuleNotFoundError: + raise ModuleNotFoundError( + "TensorFlow isn't installed. To install TensorFlow, run 'pip install " + "tensorflow'." + ) +# isort: on + +from ray.train.tensorflow.config import TensorflowConfig +from ray.train.tensorflow.tensorflow_checkpoint import TensorflowCheckpoint +from ray.train.tensorflow.tensorflow_predictor import TensorflowPredictor +from ray.train.tensorflow.tensorflow_trainer import TensorflowTrainer +from ray.train.tensorflow.train_loop_utils import prepare_dataset_shard +from ray.train.v2._internal.constants import is_v2_enabled + +if is_v2_enabled(): + from ray.train.v2.tensorflow.tensorflow_trainer import ( # noqa: F811 + TensorflowTrainer, + ) + +__all__ = [ + "TensorflowCheckpoint", + "TensorflowConfig", + "prepare_dataset_shard", + "TensorflowPredictor", + "TensorflowTrainer", +] + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55d7ab6892da3b786e982dc3fcde80e4c8245ca6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4945d21212a0a5a24f31c1861b359dc3c67723a3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/keras.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/keras.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17cf929301414098631b715cde643de7ff24e2cc Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/keras.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/tensorflow_checkpoint.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/tensorflow_checkpoint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..876a8ce9577b03236f107d8e523523bd8b4cd3b5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/tensorflow_checkpoint.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/tensorflow_predictor.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/tensorflow_predictor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbadcf9d25d999ed34edd0d3ae4fe1fd96f7d4ac Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/tensorflow_predictor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/tensorflow_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/tensorflow_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7811b7af0207d430f5e7222ddd789bb6a8308ff2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/tensorflow_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/train_loop_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/train_loop_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f311af75afa136bf4b311d2f6a94798123730f5a Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/tensorflow/__pycache__/train_loop_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/config.py b/venv/lib/python3.10/site-packages/ray/train/tensorflow/config.py new file mode 100644 index 0000000000000000000000000000000000000000..ae3baedb2a6fef55e65fb30af17d92d7e7192a93 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/tensorflow/config.py @@ -0,0 +1,60 @@ +import json +import logging +import os +from dataclasses import dataclass +from typing import List + +import ray +from ray.train._internal.utils import get_address_and_port +from ray.train._internal.worker_group import WorkerGroup +from ray.train.backend import Backend, BackendConfig +from ray.util import PublicAPI + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="beta") +@dataclass +class TensorflowConfig(BackendConfig): + @property + def backend_cls(self): + return _TensorflowBackend + + +def _setup_tensorflow_environment(worker_addresses: List[str], index: int): + """Set up distributed Tensorflow training information. + + This function should be called on each worker. + + Args: + worker_addresses: Addresses of all the workers. + index: Index (i.e. world rank) of the current worker. + """ + tf_config = { + "cluster": {"worker": worker_addresses}, + "task": {"type": "worker", "index": index}, + } + os.environ["TF_CONFIG"] = json.dumps(tf_config) + + +class _TensorflowBackend(Backend): + def on_start(self, worker_group: WorkerGroup, backend_config: TensorflowConfig): + # Compute URL for initializing distributed setup. + def get_url(): + address, port = get_address_and_port() + return f"{address}:{port}" + + urls = worker_group.execute(get_url) + + # Get setup tasks in order to throw errors on failure. + setup_futures = [] + for i in range(len(worker_group)): + setup_futures.append( + worker_group.execute_single_async( + i, + _setup_tensorflow_environment, + worker_addresses=urls, + index=i, + ) + ) + ray.get(setup_futures) diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/keras.py b/venv/lib/python3.10/site-packages/ray/train/tensorflow/keras.py new file mode 100644 index 0000000000000000000000000000000000000000..3594779c8db1801e98aca325c7a40deff299cc56 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/tensorflow/keras.py @@ -0,0 +1,3 @@ +from ray.air.integrations.keras import ReportCheckpointCallback + +ReportCheckpointCallback.__module__ = "ray.train.tensorflow.keras" diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/tensorflow_checkpoint.py b/venv/lib/python3.10/site-packages/ray/train/tensorflow/tensorflow_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..183af6e843deea8d3322d7c9bb729961f3be3aa3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/tensorflow/tensorflow_checkpoint.py @@ -0,0 +1,155 @@ +import os +import shutil +import tempfile +from pathlib import Path +from typing import TYPE_CHECKING, Optional + +import tensorflow as tf +from tensorflow import keras + +from ray.train._internal.framework_checkpoint import FrameworkCheckpoint +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.data.preprocessor import Preprocessor + + +@PublicAPI(stability="beta") +class TensorflowCheckpoint(FrameworkCheckpoint): + """A :py:class:`~ray.train.Checkpoint` with TensorFlow-specific functionality.""" + + MODEL_FILENAME_KEY = "_model_filename" + + @classmethod + def from_model( + cls, + model: keras.Model, + *, + preprocessor: Optional["Preprocessor"] = None, + ) -> "TensorflowCheckpoint": + """Create a :py:class:`~ray.train.Checkpoint` that stores a Keras model. + + The checkpoint created with this method needs to be paired with + `model` when used. + + Args: + model: The Keras model, whose weights are stored in the checkpoint. + preprocessor: A fitted preprocessor to be applied before inference. + + Returns: + A :py:class:`TensorflowCheckpoint` containing the specified model. + + Examples: + + .. testcode:: + + from ray.train.tensorflow import TensorflowCheckpoint + import tensorflow as tf + + model = tf.keras.applications.resnet.ResNet101() + checkpoint = TensorflowCheckpoint.from_model(model) + + .. testoutput:: + :options: +MOCK + :hide: + + ... # Model may or may not be downloaded + + """ + tempdir = tempfile.mkdtemp() + filename = "model.keras" + model.save(Path(tempdir, filename).as_posix()) + + checkpoint = cls.from_directory(tempdir) + if preprocessor: + checkpoint.set_preprocessor(preprocessor) + checkpoint.update_metadata({cls.MODEL_FILENAME_KEY: filename}) + return checkpoint + + @classmethod + def from_h5( + cls, file_path: str, *, preprocessor: Optional["Preprocessor"] = None + ) -> "TensorflowCheckpoint": + """Create a :py:class:`~ray.train.Checkpoint` that stores a Keras + model from H5 format. + + The checkpoint generated by this method contains all the information needed. + Thus no `model` is needed to be supplied when using this checkpoint. + + Args: + file_path: The path to the .h5 file to load model from. This is the + same path that is used for ``model.save(path)``. + preprocessor: A fitted preprocessor to be applied before inference. + + Returns: + A :py:class:`TensorflowCheckpoint` converted from h5 format. + + """ + if not os.path.isfile(file_path) or not file_path.endswith(".h5"): + raise ValueError( + "Please supply a h5 file path to `TensorflowCheckpoint.from_h5()`." + ) + tempdir = tempfile.mkdtemp() + filename = os.path.basename(file_path) + new_checkpoint_file = Path(tempdir, filename).as_posix() + shutil.copy(file_path, new_checkpoint_file) + + checkpoint = cls.from_directory(tempdir) + if preprocessor: + checkpoint.set_preprocessor(preprocessor) + checkpoint.update_metadata({cls.MODEL_FILENAME_KEY: filename}) + return checkpoint + + @classmethod + def from_saved_model( + cls, dir_path: str, *, preprocessor: Optional["Preprocessor"] = None + ) -> "TensorflowCheckpoint": + """Create a :py:class:`~ray.train.Checkpoint` that stores a Keras + model from SavedModel format. + + The checkpoint generated by this method contains all the information needed. + Thus no `model` is needed to be supplied when using this checkpoint. + + Args: + dir_path: The directory containing the saved model. This is the same + directory as used by ``model.save(dir_path)``. + preprocessor: A fitted preprocessor to be applied before inference. + + Returns: + A :py:class:`TensorflowCheckpoint` converted from SavedModel format. + + """ + if not os.path.isdir(dir_path): + raise ValueError( + "Please supply a directory to `TensorflowCheckpoint.from_saved_model`" + ) + tempdir = tempfile.mkdtemp() + # TODO(ml-team): Replace this with copytree() + os.rmdir(tempdir) + shutil.copytree(dir_path, tempdir) + + checkpoint = cls.from_directory(tempdir) + if preprocessor: + checkpoint.set_preprocessor(preprocessor) + # NOTE: The entire directory is the checkpoint. + checkpoint.update_metadata({cls.MODEL_FILENAME_KEY: "."}) + return checkpoint + + def get_model( + self, + ) -> tf.keras.Model: + """Retrieve the model stored in this checkpoint. + + Returns: + The Tensorflow Keras model stored in the checkpoint. + """ + metadata = self.get_metadata() + if self.MODEL_FILENAME_KEY not in metadata: + raise ValueError( + "`TensorflowCheckpoint` cannot retrieve the model if you override the " + "checkpoint metadata. Please use `Checkpoint.update_metadata` instead." + ) + model_filename = metadata[self.MODEL_FILENAME_KEY] + with self.as_directory() as checkpoint_dir: + model_path = Path(checkpoint_dir, model_filename).as_posix() + return keras.models.load_model(model_path) diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/tensorflow_predictor.py b/venv/lib/python3.10/site-packages/ray/train/tensorflow/tensorflow_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..ab353c333727b8310da1d6f388eb1641d27f26e5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/tensorflow/tensorflow_predictor.py @@ -0,0 +1,247 @@ +import logging +from typing import TYPE_CHECKING, Callable, Dict, Optional, Type, Union + +import numpy as np +import tensorflow as tf + +from ray.air._internal.tensorflow_utils import convert_ndarray_batch_to_tf_tensor_batch +from ray.train._internal.dl_predictor import DLPredictor +from ray.train.predictor import DataBatchType +from ray.train.tensorflow import TensorflowCheckpoint +from ray.util import log_once +from ray.util.annotations import DeveloperAPI, PublicAPI + +if TYPE_CHECKING: + from ray.data.preprocessor import Preprocessor + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="beta") +class TensorflowPredictor(DLPredictor): + """A predictor for TensorFlow models. + + Args: + model: A Tensorflow Keras model to use for predictions. + preprocessor: A preprocessor used to transform data batches prior + to prediction. + model_weights: List of weights to use for the model. + use_gpu: If set, the model will be moved to GPU on instantiation and + prediction happens on GPU. + """ + + def __init__( + self, + *, + model: Optional[tf.keras.Model] = None, + preprocessor: Optional["Preprocessor"] = None, + use_gpu: bool = False, + ): + self.use_gpu = use_gpu + # TensorFlow model objects cannot be pickled, therefore we use + # a callable that returns the model and initialize it here, + # instead of having an initialized model object as an attribute. + # Predictors are not serializable (see the implementation of __reduce__) + # in the Predictor class, so we can safely store the initialized model + # as an attribute. + if use_gpu: + # TODO (jiaodong): #26249 Use multiple GPU devices with sharded input + with tf.device("GPU:0"): + self._model = model + else: + self._model = model + gpu_devices = tf.config.list_physical_devices("GPU") + if len(gpu_devices) > 0 and log_once("tf_predictor_not_using_gpu"): + logger.warning( + "You have `use_gpu` as False but there are " + f"{len(gpu_devices)} GPUs detected on host where " + "prediction will only use CPU. Please consider explicitly " + "setting `TensorflowPredictor(use_gpu=True)` or " + "`batch_predictor.predict(ds, num_gpus_per_worker=1)` to " + "enable GPU prediction." + ) + super().__init__(preprocessor) + + def __repr__(self): + fn_name = getattr(self._model, "__name__", self._model) + fn_name_str = "" + if fn_name: + fn_name_str = str(fn_name)[:40] + return ( + f"{self.__class__.__name__}(" + f"model={fn_name_str!r}, " + f"preprocessor={self._preprocessor!r}, " + f"use_gpu={self.use_gpu!r})" + ) + + @classmethod + def from_checkpoint( + cls, + checkpoint: TensorflowCheckpoint, + model_definition: Optional[ + Union[Callable[[], tf.keras.Model], Type[tf.keras.Model]] + ] = None, + use_gpu: Optional[bool] = False, + ) -> "TensorflowPredictor": + """Instantiate the predictor from a TensorflowCheckpoint. + + Args: + checkpoint: The checkpoint to load the model and preprocessor from. + model_definition: A callable that returns a TensorFlow Keras model + to use. Model weights will be loaded from the checkpoint. + This is only needed if the `checkpoint` was created from + `TensorflowCheckpoint.from_model`. + use_gpu: Whether GPU should be used during prediction. + """ + if model_definition: + raise DeprecationWarning( + "`model_definition` is deprecated. `TensorflowCheckpoint.from_model` " + "now saves the full model definition in .keras format." + ) + + model = checkpoint.get_model() + preprocessor = checkpoint.get_preprocessor() + return cls( + model=model, + preprocessor=preprocessor, + use_gpu=use_gpu, + ) + + @DeveloperAPI + def call_model( + self, inputs: Union[tf.Tensor, Dict[str, tf.Tensor]] + ) -> Union[tf.Tensor, Dict[str, tf.Tensor]]: + """Runs inference on a single batch of tensor data. + + This method is called by `TorchPredictor.predict` after converting the + original data batch to torch tensors. + + Override this method to add custom logic for processing the model input or + output. + + Example: + + .. testcode:: + + # List outputs are not supported by default TensorflowPredictor. + def build_model() -> tf.keras.Model: + input = tf.keras.layers.Input(shape=1) + model = tf.keras.models.Model(inputs=input, outputs=[input, input]) + return model + + # Use a custom predictor to format model output as a dict. + class CustomPredictor(TensorflowPredictor): + def call_model(self, inputs): + model_output = super().call_model(inputs) + return { + str(i): model_output[i] for i in range(len(model_output)) + } + + import numpy as np + data_batch = np.array([[0.5], [0.6], [0.7]], dtype=np.float32) + + predictor = CustomPredictor(model=build_model()) + predictions = predictor.predict(data_batch) + + Args: + inputs: A batch of data to predict on, represented as either a single + TensorFlow tensor or for multi-input models, a dictionary of tensors. + + Returns: + The model outputs, either as a single tensor or a dictionary of tensors. + + """ + if self.use_gpu: + with tf.device("GPU:0"): + return self._model(inputs) + else: + return self._model(inputs) + + def predict( + self, + data: DataBatchType, + dtype: Optional[Union[tf.dtypes.DType, Dict[str, tf.dtypes.DType]]] = None, + ) -> DataBatchType: + """Run inference on data batch. + + If the provided data is a single array or a dataframe/table with a single + column, it will be converted into a single Tensorflow tensor before being + inputted to the model. + + If the provided data is a multi-column table or a dict of numpy arrays, + it will be converted into a dict of tensors before being inputted to the + model. This is useful for multi-modal inputs (for example your model accepts + both image and text). + + Args: + data: A batch of input data. Either a pandas DataFrame or numpy + array. + dtype: The dtypes to use for the tensors. Either a single dtype for all + tensors or a mapping from column name to dtype. + + Examples: + + .. testcode:: + + import numpy as np + import tensorflow as tf + from ray.train.tensorflow import TensorflowPredictor + + def build_model(): + return tf.keras.Sequential( + [ + tf.keras.layers.InputLayer(input_shape=()), + tf.keras.layers.Flatten(), + tf.keras.layers.Dense(1), + ] + ) + + weights = [np.array([[2.0]]), np.array([0.0])] + predictor = TensorflowPredictor(model=build_model()) + + data = np.asarray([1, 2, 3]) + predictions = predictor.predict(data) + + import pandas as pd + import tensorflow as tf + from ray.train.tensorflow import TensorflowPredictor + + def build_model(): + input1 = tf.keras.layers.Input(shape=(1,), name="A") + input2 = tf.keras.layers.Input(shape=(1,), name="B") + merged = tf.keras.layers.Concatenate(axis=1)([input1, input2]) + output = tf.keras.layers.Dense(2, input_dim=2)(merged) + return tf.keras.models.Model( + inputs=[input1, input2], outputs=output) + + predictor = TensorflowPredictor(model=build_model()) + + # Pandas dataframe. + data = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) + + predictions = predictor.predict(data) + + Returns: + DataBatchType: Prediction result. The return type will be the same as the + input type. + """ + return super(TensorflowPredictor, self).predict(data=data, dtype=dtype) + + def _arrays_to_tensors( + self, + numpy_arrays: Union[np.ndarray, Dict[str, np.ndarray]], + dtype: Optional[Union[tf.dtypes.DType, Dict[str, tf.dtypes.DType]]], + ) -> Union[tf.Tensor, Dict[str, tf.Tensor]]: + return convert_ndarray_batch_to_tf_tensor_batch(numpy_arrays, dtypes=dtype) + + def _tensor_to_array(self, tensor: tf.Tensor) -> np.ndarray: + if not isinstance(tensor, tf.Tensor): + raise ValueError( + "Expected the model to return either a tf.Tensor or a " + f"dict of tf.Tensor, but got {type(tensor)} instead. " + f"To support models with different output types, subclass " + f"TensorflowPredictor and override the `call_model` method " + f"to process the output into either torch.Tensor or Dict[" + f"str, torch.Tensor]." + ) + return tensor.numpy() diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/tensorflow_trainer.py b/venv/lib/python3.10/site-packages/ray/train/tensorflow/tensorflow_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..1da58ef5b32f89b3ea785380a329b9ef279a748a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/tensorflow/tensorflow_trainer.py @@ -0,0 +1,194 @@ +from typing import Any, Callable, Dict, Optional, Union + +from ray.train import Checkpoint, DataConfig, RunConfig, ScalingConfig +from ray.train.data_parallel_trainer import DataParallelTrainer +from ray.train.tensorflow.config import TensorflowConfig +from ray.train.trainer import GenDataset +from ray.util import PublicAPI + + +@PublicAPI(stability="beta") +class TensorflowTrainer(DataParallelTrainer): + """A Trainer for data parallel Tensorflow training. + + This Trainer runs the function ``train_loop_per_worker`` on multiple Ray + Actors. These actors already have the necessary TensorFlow process group already + configured for distributed TensorFlow training. + + The ``train_loop_per_worker`` function is expected to take in either 0 or 1 + arguments: + + .. testcode:: + + def train_loop_per_worker(): + ... + + .. testcode:: + + def train_loop_per_worker(config: Dict): + ... + + If ``train_loop_per_worker`` accepts an argument, then + ``train_loop_config`` will be passed in as the argument. This is useful if you + want to tune the values in ``train_loop_config`` as hyperparameters. + + If the ``datasets`` dict contains a training dataset (denoted by + the "train" key), then it will be split into multiple dataset + shards that can then be accessed by ``ray.train.get_dataset_shard("train")`` inside + ``train_loop_per_worker``. All the other datasets will not be split and + ``ray.train.get_dataset_shard(...)`` will return the entire Dataset. + + Inside the ``train_loop_per_worker`` function, you can use any of the + :ref:`Ray Train loop methods `. + + .. warning:: + Ray will not automatically set any environment variables or configuration + related to local parallelism / threading + :ref:`aside from "OMP_NUM_THREADS" `. + If you desire greater control over TensorFlow threading, use + the ``tf.config.threading`` module (eg. + ``tf.config.threading.set_inter_op_parallelism_threads(num_cpus)``) + at the beginning of your ``train_loop_per_worker`` function. + + + .. testcode:: + + from ray import train + + def train_loop_per_worker(): + # Report intermediate results for callbacks or logging and + # checkpoint data. + train.report(...) + + # Returns dict of last saved checkpoint. + train.get_checkpoint() + + # Returns the Dataset shard for the given key. + train.get_dataset_shard("my_dataset") + + # Returns the total number of workers executing training. + train.get_context().get_world_size() + + # Returns the rank of this worker. + train.get_context().get_world_rank() + + # Returns the rank of the worker on the current node. + train.get_context().get_local_rank() + + Any returns from the ``train_loop_per_worker`` will be discarded and not + used or persisted anywhere. + + To save a model to use for the ``TensorflowPredictor``, you must save it under the + "model" kwarg in ``Checkpoint`` passed to ``train.report()``. + + Example: + + .. testcode:: + + import os + import tempfile + import tensorflow as tf + import numpy as np + + import ray + from ray import train + from ray.train import Checkpoint, ScalingConfig + from ray.train.tensorflow import TensorflowTrainer + + def build_model(): + # toy neural network : 1-layer + return tf.keras.Sequential( + [tf.keras.layers.Dense( + 1, activation="linear", input_shape=(1,))] + ) + + def train_loop_per_worker(config): + dataset_shard = train.get_dataset_shard("train") + strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy() + with strategy.scope(): + model = build_model() + model.compile( + optimizer="Adam", loss="mean_squared_error", metrics=["mse"]) + + tf_dataset = dataset_shard.to_tf( + feature_columns="x", + label_columns="y", + batch_size=1 + ) + for epoch in range(config["num_epochs"]): + model.fit(tf_dataset) + + # Create checkpoint. + checkpoint_dir = tempfile.mkdtemp() + model.save_weights( + os.path.join(checkpoint_dir, "my_checkpoint") + ) + checkpoint = Checkpoint.from_directory(checkpoint_dir) + + train.report( + {}, + checkpoint=checkpoint, + ) + + train_dataset = ray.data.from_items([{"x": np.array([x], dtype=np.float32), "y": x + 1} for x in range(32)]) + trainer = TensorflowTrainer( + train_loop_per_worker=train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=3, use_gpu=True), + datasets={"train": train_dataset}, + train_loop_config={"num_epochs": 2}, + ) + result = trainer.fit() + + .. testoutput:: + :options:+ELLIPSIS + :hide: + + ... + + Args: + train_loop_per_worker: The training function to execute. + This can either take in no arguments or a ``config`` dict. + train_loop_config: Configurations to pass into + ``train_loop_per_worker`` if it accepts an argument. + tensorflow_config: Configuration for setting up the TensorFlow backend. + If set to None, use the default configuration. This replaces the + ``backend_config`` arg of ``DataParallelTrainer``. + scaling_config: Configuration for how to scale data parallel training. + dataset_config: Configuration for dataset ingest. + run_config: Configuration for the execution of the training run. + datasets: Any Datasets to use for training. Use + the key "train" to denote which dataset is the training + dataset. + resume_from_checkpoint: A checkpoint to resume training from. + metadata: Dict that should be made available via + `ray.train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + """ + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + tensorflow_config: Optional[TensorflowConfig] = None, + scaling_config: Optional[ScalingConfig] = None, + dataset_config: Optional[DataConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + if not tensorflow_config: + tensorflow_config = TensorflowConfig() + + super(TensorflowTrainer, self).__init__( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + backend_config=tensorflow_config, + scaling_config=scaling_config, + dataset_config=dataset_config, + run_config=run_config, + datasets=datasets, + resume_from_checkpoint=resume_from_checkpoint, + metadata=metadata, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/tensorflow/train_loop_utils.py b/venv/lib/python3.10/site-packages/ray/train/tensorflow/train_loop_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b7862d6a365f14d16cf6ad85e17ce7dc92ad5c2d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/tensorflow/train_loop_utils.py @@ -0,0 +1,27 @@ +import tensorflow as tf + +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="beta") +def prepare_dataset_shard(tf_dataset_shard: tf.data.Dataset): + """A utility function that overrides default config for Tensorflow Dataset. + + This should be used on a TensorFlow ``Dataset`` created by calling + ``iter_tf_batches()`` on a ``ray.data.Dataset`` returned by + ``ray.train.get_dataset_shard()`` since the dataset has already + been sharded across the workers. + + Args: + tf_dataset_shard (tf.data.Dataset): A TensorFlow Dataset. + + Returns: + A TensorFlow Dataset with: + - autosharding turned off + - prefetching turned on with autotune enabled + """ + options = tf.data.Options() + options.experimental_distribute.auto_shard_policy = ( + tf.data.experimental.AutoShardPolicy.OFF + ) + return tf_dataset_shard.with_options(options).prefetch(tf.data.AUTOTUNE) diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/__init__.py b/venv/lib/python3.10/site-packages/ray/train/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..db989336afd15a2d2147d45f9b6685f3e823598c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/torch/__init__.py @@ -0,0 +1,56 @@ +# isort: off +try: + import torch # noqa: F401 +except ModuleNotFoundError: + raise ModuleNotFoundError( + "PyTorch isn't installed. To install PyTorch, run 'pip install torch'" + ) +# isort: on + +from ray.train.torch.config import TorchConfig +from ray.train.torch.torch_checkpoint import TorchCheckpoint +from ray.train.torch.torch_detection_predictor import TorchDetectionPredictor +from ray.train.torch.torch_predictor import TorchPredictor +from ray.train.torch.torch_trainer import TorchTrainer +from ray.train.torch.train_loop_utils import ( + accelerate, + backward, + enable_reproducibility, + get_device, + get_devices, + prepare_data_loader, + prepare_model, + prepare_optimizer, +) +from ray.train.v2._internal.constants import is_v2_enabled + +if is_v2_enabled(): + from ray.train.v2.torch.torch_trainer import TorchTrainer # noqa: F811 + from ray.train.v2.torch.train_loop_utils import ( # noqa: F811 + accelerate, + backward, + enable_reproducibility, + prepare_data_loader, + prepare_model, + prepare_optimizer, + ) + + +__all__ = [ + "TorchTrainer", + "TorchCheckpoint", + "TorchConfig", + "accelerate", + "get_device", + "get_devices", + "prepare_model", + "prepare_optimizer", + "prepare_data_loader", + "backward", + "enable_reproducibility", + "TorchPredictor", + "TorchDetectionPredictor", +] + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3d879ea472fb6c0bba8df92a862e2261f444d2a Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e881a48d6dc1c8034b2f989ad049587ae7bdb60 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_checkpoint.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_checkpoint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8c7d2c0810a820f9e286ca23e8f5ff673ec1c63 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_checkpoint.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_detection_predictor.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_detection_predictor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3270385f13c86f8b1ff2ecb526e9b4cbb498b06d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_detection_predictor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_predictor.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_predictor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a1d5fd3a84a5c56f9344043e430eb7f835db4da Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_predictor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68be667c6913c5dae387f668d8a3cabd5089d27f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/torch_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/train_loop_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/train_loop_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff6322eb07a1faa3a3435dd32382b0787ee4e2b5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/torch/__pycache__/train_loop_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/config.py b/venv/lib/python3.10/site-packages/ray/train/torch/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a0ecc61e3b874e1624b4e5ccdd3ae0e77a176d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/torch/config.py @@ -0,0 +1,213 @@ +import logging +import os +from dataclasses import dataclass +from datetime import timedelta +from typing import Optional + +import torch +import torch.distributed as dist +from packaging.version import Version + +import ray +from ray.air._internal.device_manager import register_custom_torch_dist_backend +from ray.train._internal.utils import get_address_and_port +from ray.train._internal.worker_group import WorkerGroup +from ray.train.backend import Backend, BackendConfig +from ray.util import PublicAPI + +logger = logging.getLogger(__name__) + + +class TorchConfigContextManager: + def __enter__(self): + # Set default cuda device + if torch.cuda.is_available(): + device = ray.train.torch.get_device() + if device.type == "cuda": + torch.cuda.set_device(device) + + def __exit__(self, type, value, traceback): + # Propagate exceptions if any + return False + + +@PublicAPI(stability="stable") +@dataclass +class TorchConfig(BackendConfig): + """Configuration for torch process group setup. + + See https://pytorch.org/docs/stable/distributed.html for more info. + + Args: + backend: The backend to use for training. + See ``torch.distributed.init_process_group`` for more info and + valid values. + If set to None, nccl will be used if GPUs are requested, else gloo + will be used. + init_method: The initialization method to use. Either "env" + for environment variable initialization or "tcp" for TCP + initialization. Defaults to "env". + timeout_s: Seconds for process group operations to timeout. + """ + + backend: Optional[str] = None + init_method: str = "env" + timeout_s: int = 1800 + + @property + def backend_cls(self): + return _TorchBackend + + @property + def train_func_context(self): + return TorchConfigContextManager + + +def _setup_torch_process_group( + backend: str, + world_rank: int, + world_size: int, + init_method: str, + timeout_s: int = 1800, +): + """Connects the distributed PyTorch backend. + + Args: + backend: The backend (nccl, gloo, etc.) to use for training. + world_rank: Rank of the current worker. + world_size: Number of workers participating in the job. + init_method: URL specifying how to initialize the process group. + timeout_s: Seconds for process group operations to timeout. + """ + if world_rank == 0: + logger.info( + f"Setting up process group for: {init_method} [rank={world_rank}, " + f"world_size={world_size}]" + ) + else: + logger.debug( + f"Setting up process group for: {init_method} [rank={world_rank}, " + f"world_size={world_size}]" + ) + logger.debug(f"using {backend}") + + if backend == "nccl": + # See https://github.com/pytorch/pytorch/blob/c263bd43e8e8502d4726643bc6fd046f0130ac0e/torch/distributed/distributed_c10d.py#L803-L823 # noqa: E501 + # We do not use TORCH_NCCL_BLOCKING_WAIT due to performance overhead. + if Version(torch.__version__) < Version("2.2.0"): + TORCH_NCCL_ASYNC_ERROR_HANDLING_ENV_VAR = "NCCL_ASYNC_ERROR_HANDLING" + TORCH_NCCL_BLOCKING_WAIT_ENV_VAR = "NCCL_BLOCKING_WAIT" + else: + TORCH_NCCL_ASYNC_ERROR_HANDLING_ENV_VAR = "TORCH_NCCL_ASYNC_ERROR_HANDLING" + TORCH_NCCL_BLOCKING_WAIT_ENV_VAR = "TORCH_NCCL_BLOCKING_WAIT" + if ( + TORCH_NCCL_ASYNC_ERROR_HANDLING_ENV_VAR not in os.environ + and TORCH_NCCL_BLOCKING_WAIT_ENV_VAR not in os.environ + ): + logger.debug( + f"Setting {TORCH_NCCL_ASYNC_ERROR_HANDLING_ENV_VAR}=1 to fail if NCCL collective communication operations are timing out. " # noqa: E501 + f"To override this behavior, you can set {TORCH_NCCL_ASYNC_ERROR_HANDLING_ENV_VAR}=0." # noqa: E501 + ) + os.environ[TORCH_NCCL_ASYNC_ERROR_HANDLING_ENV_VAR] = "1" + elif backend == "hccl": + register_custom_torch_dist_backend(backend) + + dist.init_process_group( + backend=backend, + init_method=init_method, + rank=world_rank, + world_size=world_size, + timeout=timedelta(seconds=timeout_s), + ) + + +def _shutdown_torch(destroy_process_group=False): + from ray.air._internal.torch_utils import get_devices + + devices = get_devices() + if destroy_process_group: + dist.destroy_process_group() + if torch.cuda.is_available(): + for device in devices: + with torch.cuda.device(device): + torch.cuda.empty_cache() + + +def _set_torch_distributed_env_vars(): + # Same env vars as in + # https://pytorch.org/docs/stable/elastic/run.html#environment-variables + from ray.train.torch import get_device + + context = ray.train.get_context() + os.environ["LOCAL_RANK"] = str(context.get_local_rank()) + os.environ["RANK"] = str(context.get_world_rank()) + os.environ["LOCAL_WORLD_SIZE"] = str(context.get_local_world_size()) + os.environ["WORLD_SIZE"] = str(context.get_world_size()) + os.environ["NODE_RANK"] = str(context.get_node_rank()) + + # Makes sure Hugging Face Accelerate uses the correct device + device = get_device() + os.environ["ACCELERATE_TORCH_DEVICE"] = str(device) + + +class _TorchBackend(Backend): + share_cuda_visible_devices: bool = True + + def on_start(self, worker_group: WorkerGroup, backend_config: TorchConfig): + if dist.is_available(): + # Set the appropriate training backend. + if backend_config.backend is None: + if worker_group.num_gpus_per_worker > 0: + backend = "nccl" + else: + backend = "gloo" + else: + backend = backend_config.backend + + master_addr, master_port = worker_group.execute_single( + 0, get_address_and_port + ) + if backend_config.init_method == "env": + + def set_env_vars(addr, port): + os.environ["MASTER_ADDR"] = addr + os.environ["MASTER_PORT"] = str(port) + + worker_group.execute(set_env_vars, addr=master_addr, port=master_port) + url = "env://" + elif backend_config.init_method == "tcp": + url = f"tcp://{master_addr}:{master_port}" + else: + raise ValueError( + f"The provided init_method (" + f"{backend_config.init_method}) is not supported. Must " + f"be either 'env' or 'tcp'." + ) + + setup_futures = [] + for i in range(len(worker_group)): + setup_futures.append( + worker_group.execute_single_async( + i, + _setup_torch_process_group, + backend=backend, + world_rank=i, + world_size=len(worker_group), + init_method=url, + timeout_s=backend_config.timeout_s, + ) + ) + ray.get(setup_futures) + else: + raise RuntimeError("Distributed torch is not available.") + + def on_shutdown(self, worker_group: WorkerGroup, backend_config: TorchConfig): + worker_group.execute( + _shutdown_torch, + destroy_process_group=len(worker_group) > 1, + ) + + def on_training_start( + self, worker_group: WorkerGroup, backend_config: BackendConfig + ): + worker_group.execute(_set_torch_distributed_env_vars) diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/torch_checkpoint.py b/venv/lib/python3.10/site-packages/ray/train/torch/torch_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..7b6eeae305185bdd638042a7c1a0386f8d26bd86 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/torch/torch_checkpoint.py @@ -0,0 +1,182 @@ +import os +import tempfile +import warnings +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, Optional + +import torch + +from ray.air._internal.torch_utils import ( + consume_prefix_in_state_dict_if_present_not_in_place, + load_torch_model, +) +from ray.train._internal.framework_checkpoint import FrameworkCheckpoint +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.data.preprocessor import Preprocessor + +ENCODED_DATA_KEY = "torch_encoded_data" + + +@PublicAPI(stability="beta") +class TorchCheckpoint(FrameworkCheckpoint): + """A :class:`~ray.train.Checkpoint` with Torch-specific functionality.""" + + MODEL_FILENAME = "model.pt" + + @classmethod + def from_state_dict( + cls, + state_dict: Dict[str, Any], + *, + preprocessor: Optional["Preprocessor"] = None, + ) -> "TorchCheckpoint": + """Create a :class:`~ray.train.Checkpoint` that stores a model state dictionary. + + .. tip:: + + This is the recommended method for creating + :class:`TorchCheckpoints`. + + Args: + state_dict: The model state dictionary to store in the checkpoint. + preprocessor: A fitted preprocessor to be applied before inference. + + Returns: + A :class:`TorchCheckpoint` containing the specified state dictionary. + + Examples: + + .. testcode:: + + import torch + import torch.nn as nn + from ray.train.torch import TorchCheckpoint + + # Set manual seed + torch.manual_seed(42) + + # Function to create a NN model + def create_model() -> nn.Module: + model = nn.Sequential(nn.Linear(1, 10), + nn.ReLU(), + nn.Linear(10,1)) + return model + + # Create a TorchCheckpoint from our model's state_dict + model = create_model() + checkpoint = TorchCheckpoint.from_state_dict(model.state_dict()) + + # Now load the model from the TorchCheckpoint by providing the + # model architecture + model_from_chkpt = checkpoint.get_model(create_model()) + + # Assert they have the same state dict + assert str(model.state_dict()) == str(model_from_chkpt.state_dict()) + print("worked") + + .. testoutput:: + :hide: + + ... + """ + tempdir = tempfile.mkdtemp() + + model_path = Path(tempdir, cls.MODEL_FILENAME).as_posix() + stripped_state_dict = consume_prefix_in_state_dict_if_present_not_in_place( + state_dict, "module." + ) + torch.save(stripped_state_dict, model_path) + + checkpoint = cls.from_directory(tempdir) + if preprocessor: + checkpoint.set_preprocessor(preprocessor) + return checkpoint + + @classmethod + def from_model( + cls, + model: torch.nn.Module, + *, + preprocessor: Optional["Preprocessor"] = None, + ) -> "TorchCheckpoint": + """Create a :class:`~ray.train.Checkpoint` that stores a Torch model. + + .. note:: + + PyTorch recommends storing state dictionaries. To create a + :class:`TorchCheckpoint` from a state dictionary, call + :meth:`~ray.train.torch.TorchCheckpoint.from_state_dict`. To learn more + about state dictionaries, read + `Saving and Loading Models `_. # noqa: E501 + + Args: + model: The Torch model to store in the checkpoint. + preprocessor: A fitted preprocessor to be applied before inference. + + Returns: + A :class:`TorchCheckpoint` containing the specified model. + + Examples: + + .. testcode:: + + from ray.train.torch import TorchCheckpoint + import torch + + # Create model identity and send a random tensor to it + model = torch.nn.Identity() + input = torch.randn(2, 2) + output = model(input) + + # Create a checkpoint + checkpoint = TorchCheckpoint.from_model(model) + print(checkpoint) + + .. testoutput:: + :hide: + + ... + """ + tempdir = tempfile.mkdtemp() + + model_path = Path(tempdir, cls.MODEL_FILENAME).as_posix() + torch.save(model, model_path) + + checkpoint = cls.from_directory(tempdir) + if preprocessor: + checkpoint.set_preprocessor(preprocessor) + return checkpoint + + def get_model(self, model: Optional[torch.nn.Module] = None) -> torch.nn.Module: + """Retrieve the model stored in this checkpoint. + + Args: + model: If the checkpoint contains a model state dict, and not + the model itself, then the state dict will be loaded to this + ``model``. Otherwise, the model will be discarded. + """ + with self.as_directory() as tempdir: + model_path = Path(tempdir, self.MODEL_FILENAME).as_posix() + if not os.path.exists(model_path): + raise RuntimeError( + "`model.pt` not found within this checkpoint. Make sure you " + "created this `TorchCheckpoint` from one of its public " + "constructors (`from_state_dict` or `from_model`)." + ) + model_or_state_dict = torch.load(model_path, map_location="cpu") + + if isinstance(model_or_state_dict, torch.nn.Module): + if model: + warnings.warn( + "TorchCheckpoint already contains all information needed. " + "Discarding provided `model` argument. If you are using " + "TorchPredictor directly, you should do " + "`TorchPredictor.from_checkpoint(checkpoint)` by removing kwargs " + "`model=`." + ) + model = load_torch_model( + saved_model=model_or_state_dict, model_definition=model + ) + return model diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/torch_detection_predictor.py b/venv/lib/python3.10/site-packages/ray/train/torch/torch_detection_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..98a708a731ca2976d57c7866dfc0707d5c255545 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/torch/torch_detection_predictor.py @@ -0,0 +1,90 @@ +import collections +from typing import Dict, List, Optional, Union + +import numpy as np +import torch + +from ray.train._internal.dl_predictor import TensorDtype +from ray.train.torch.torch_predictor import TorchPredictor +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class TorchDetectionPredictor(TorchPredictor): + """A predictor for TorchVision detection models. + + Unlike other Torch models, instance segmentation models return + `List[Dict[str, Tensor]]`. This predictor extends :class:`TorchPredictor` to support + the non-standard outputs. + + To learn more about instance segmentation models, read + `Instance segmentation models `_. + + Example: + + .. testcode:: + + import numpy as np + from torchvision import models + + from ray.train.torch import TorchDetectionPredictor + + model = models.detection.fasterrcnn_resnet50_fpn_v2(pretrained=True) + + predictor = TorchDetectionPredictor(model=model) + predictions = predictor.predict(np.zeros((4, 3, 32, 32), dtype=np.float32)) + + print(predictions.keys()) + + .. testoutput:: + + dict_keys(['pred_boxes', 'pred_labels', 'pred_scores']) + + """ # noqa: E501 + + def _predict_numpy( + self, + data: Union[np.ndarray, Dict[str, np.ndarray]], + dtype: Optional[Union[TensorDtype, Dict[str, TensorDtype]]], + ) -> Dict[str, np.ndarray]: + if isinstance(data, dict) and len(data) != 1: + raise ValueError( + f"""Expected input to contain one key, but got {len(data)} instead.""" + ) + + if dtype is not None and not isinstance(dtype, torch.dtype): + raise ValueError( + "Expected `dtype` to be a `torch.dtype`, but got a " + f"{type(dtype).__name__} instead." + ) + + if isinstance(data, dict): + images = next(iter(data.values())) + else: + images = data + + inputs = [ + torch.as_tensor(image, dtype=dtype).to(self.device) for image in images + ] + outputs = self.call_model(inputs) + outputs = _convert_outputs_to_batch(outputs) + outputs = {"pred_" + key: value for key, value in outputs.items()} + + return outputs + + +def _convert_outputs_to_batch( + outputs: List[Dict[str, torch.Tensor]], +) -> Dict[str, List[torch.Tensor]]: + """Batch detection model outputs. + + TorchVision detection models return `List[Dict[Tensor]]`. Each `Dict` contain + 'boxes', 'labels, and 'scores'. + + This function batches values and returns a `Dict[str, List[Tensor]]`. + """ # noqa: E501 + batch = collections.defaultdict(list) + for output in outputs: + for key, value in output.items(): + batch[key].append(value.cpu().detach()) + return batch diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/torch_predictor.py b/venv/lib/python3.10/site-packages/ray/train/torch/torch_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..be81d5b0f68c0a397239940bc9b310fc79a0b864 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/torch/torch_predictor.py @@ -0,0 +1,250 @@ +import logging +from typing import TYPE_CHECKING, Dict, Optional, Union + +import numpy as np +import torch + +from ray.air._internal.torch_utils import convert_ndarray_batch_to_torch_tensor_batch +from ray.train._internal.dl_predictor import DLPredictor +from ray.train.predictor import DataBatchType +from ray.train.torch import TorchCheckpoint +from ray.util import log_once +from ray.util.annotations import DeveloperAPI, PublicAPI + +if TYPE_CHECKING: + from ray.data.preprocessor import Preprocessor + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="beta") +class TorchPredictor(DLPredictor): + """A predictor for PyTorch models. + + Args: + model: The torch module to use for predictions. + preprocessor: A preprocessor used to transform data batches prior + to prediction. + use_gpu: If set, the model will be moved to GPU on instantiation and + prediction happens on GPU. + """ + + def __init__( + self, + model: torch.nn.Module, + preprocessor: Optional["Preprocessor"] = None, + use_gpu: bool = False, + ): + self.model = model + self.model.eval() + self.use_gpu = use_gpu + + if use_gpu: + # TODO (jiaodong): #26249 Use multiple GPU devices with sharded input + self.device = torch.device("cuda") + else: + self.device = torch.device("cpu") + + # Ensure input tensor and model live on the same device + self.model.to(self.device) + + if ( + not use_gpu + and torch.cuda.device_count() > 0 + and log_once("torch_predictor_not_using_gpu") + ): + logger.warning( + "You have `use_gpu` as False but there are " + f"{torch.cuda.device_count()} GPUs detected on host where " + "prediction will only use CPU. Please consider explicitly " + "setting `TorchPredictor(use_gpu=True)` or " + "`batch_predictor.predict(ds, num_gpus_per_worker=1)` to " + "enable GPU prediction." + ) + + super().__init__(preprocessor) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(model={self.model!r}, " + f"preprocessor={self._preprocessor!r}, use_gpu={self.use_gpu!r})" + ) + + @classmethod + def from_checkpoint( + cls, + checkpoint: TorchCheckpoint, + model: Optional[torch.nn.Module] = None, + use_gpu: bool = False, + ) -> "TorchPredictor": + """Instantiate the predictor from a TorchCheckpoint. + + Args: + checkpoint: The checkpoint to load the model and preprocessor from. + model: If the checkpoint contains a model state dict, and not + the model itself, then the state dict will be loaded to this + ``model``. If the checkpoint already contains the model itself, + this model argument will be discarded. + use_gpu: If set, the model will be moved to GPU on instantiation and + prediction happens on GPU. + """ + model = checkpoint.get_model(model) + preprocessor = checkpoint.get_preprocessor() + return cls(model=model, preprocessor=preprocessor, use_gpu=use_gpu) + + @DeveloperAPI + def call_model( + self, inputs: Union[torch.Tensor, Dict[str, torch.Tensor]] + ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]: + """Runs inference on a single batch of tensor data. + + This method is called by `TorchPredictor.predict` after converting the + original data batch to torch tensors. + + Override this method to add custom logic for processing the model input or + output. + + Args: + inputs: A batch of data to predict on, represented as either a single + PyTorch tensor or for multi-input models, a dictionary of tensors. + + Returns: + The model outputs, either as a single tensor or a dictionary of tensors. + + Example: + + .. testcode:: + + import numpy as np + import torch + from ray.train.torch import TorchPredictor + + # List outputs are not supported by default TorchPredictor. + # So let's define a custom TorchPredictor and override call_model + class MyModel(torch.nn.Module): + def forward(self, input_tensor): + return [input_tensor, input_tensor] + + # Use a custom predictor to format model output as a dict. + class CustomPredictor(TorchPredictor): + def call_model(self, inputs): + model_output = super().call_model(inputs) + return { + str(i): model_output[i] for i in range(len(model_output)) + } + + # create our data batch + data_batch = np.array([1, 2]) + # create custom predictor and predict + predictor = CustomPredictor(model=MyModel()) + predictions = predictor.predict(data_batch) + print(f"Predictions: {predictions.get('0')}, {predictions.get('1')}") + + .. testoutput:: + + Predictions: [1 2], [1 2] + + """ + with torch.no_grad(): + output = self.model(inputs) + return output + + def predict( + self, + data: DataBatchType, + dtype: Optional[Union[torch.dtype, Dict[str, torch.dtype]]] = None, + ) -> DataBatchType: + """Run inference on data batch. + + If the provided data is a single array or a dataframe/table with a single + column, it will be converted into a single PyTorch tensor before being + inputted to the model. + + If the provided data is a multi-column table or a dict of numpy arrays, + it will be converted into a dict of tensors before being inputted to the + model. This is useful for multi-modal inputs (for example your model accepts + both image and text). + + Args: + data: A batch of input data of ``DataBatchType``. + dtype: The dtypes to use for the tensors. Either a single dtype for all + tensors or a mapping from column name to dtype. + + Returns: + DataBatchType: Prediction result. The return type will be the same as the + input type. + + Example: + + .. testcode:: + + import numpy as np + import pandas as pd + import torch + import ray + from ray.train.torch import TorchPredictor + + # Define a custom PyTorch module + class CustomModule(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear1 = torch.nn.Linear(1, 1) + self.linear2 = torch.nn.Linear(1, 1) + + def forward(self, input_dict: dict): + out1 = self.linear1(input_dict["A"].unsqueeze(1)) + out2 = self.linear2(input_dict["B"].unsqueeze(1)) + return out1 + out2 + + # Set manul seed so we get consistent output + torch.manual_seed(42) + + # Use Standard PyTorch model + model = torch.nn.Linear(2, 1) + predictor = TorchPredictor(model=model) + # Define our data + data = np.array([[1, 2], [3, 4]]) + predictions = predictor.predict(data, dtype=torch.float) + print(f"Standard model predictions: {predictions}") + print("---") + + # Use Custom PyTorch model with TorchPredictor + predictor = TorchPredictor(model=CustomModule()) + # Define our data and predict Customer model with TorchPredictor + data = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) + predictions = predictor.predict(data, dtype=torch.float) + print(f"Custom model predictions: {predictions}") + + .. testoutput:: + + Standard model predictions: {'predictions': array([[1.5487633], + [3.8037925]], dtype=float32)} + --- + Custom model predictions: predictions + 0 [0.61623406] + 1 [2.857038] + """ + return super(TorchPredictor, self).predict(data=data, dtype=dtype) + + def _arrays_to_tensors( + self, + numpy_arrays: Union[np.ndarray, Dict[str, np.ndarray]], + dtype: Optional[Union[torch.dtype, Dict[str, torch.dtype]]], + ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]: + return convert_ndarray_batch_to_torch_tensor_batch( + numpy_arrays, + dtypes=dtype, + device=self.device, + ) + + def _tensor_to_array(self, tensor: torch.Tensor) -> np.ndarray: + if not isinstance(tensor, torch.Tensor): + raise ValueError( + "Expected the model to return either a torch.Tensor or a " + f"dict of torch.Tensor, but got {type(tensor)} instead. " + f"To support models with different output types, subclass " + f"TorchPredictor and override the `call_model` method to " + f"process the output into either torch.Tensor or Dict[" + f"str, torch.Tensor]." + ) + return tensor.cpu().detach().numpy() diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/torch_trainer.py b/venv/lib/python3.10/site-packages/ray/train/torch/torch_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..8df6a6cdbe80016c528bd5a1ac963af86eb9ff64 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/torch/torch_trainer.py @@ -0,0 +1,204 @@ +from typing import Any, Callable, Dict, Optional, Union + +from ray.train import Checkpoint, DataConfig, RunConfig, ScalingConfig +from ray.train.data_parallel_trainer import DataParallelTrainer +from ray.train.torch.config import TorchConfig +from ray.train.trainer import GenDataset +from ray.util import PublicAPI + + +@PublicAPI(stability="stable") +class TorchTrainer(DataParallelTrainer): + """A Trainer for data parallel PyTorch training. + + At a high level, this Trainer does the following: + + 1. Launches multiple workers as defined by the ``scaling_config``. + 2. Sets up a distributed PyTorch environment + on these workers as defined by the ``torch_config``. + 3. Ingests the input ``datasets`` based on the ``dataset_config``. + 4. Runs the input ``train_loop_per_worker(train_loop_config)`` + on all workers. + + For more details, see: + + * :ref:`PyTorch Guide ` + * :ref:`PyTorch Lightning Guide ` + * :ref:`Hugging Face Transformers Guide ` + + Example: + + .. testcode:: + + import os + import tempfile + + import torch + from torch import nn + from torch.nn.parallel import DistributedDataParallel + + import ray + from ray.train import Checkpoint, CheckpointConfig, RunConfig, ScalingConfig + from ray.train.torch import TorchTrainer + + # If using GPUs, set this to True. + use_gpu = False + # Number of processes to run training on. + num_workers = 4 + + # Define your network structure. + class NeuralNetwork(nn.Module): + def __init__(self): + super(NeuralNetwork, self).__init__() + self.layer1 = nn.Linear(1, 32) + self.relu = nn.ReLU() + self.layer2 = nn.Linear(32, 1) + + def forward(self, input): + return self.layer2(self.relu(self.layer1(input))) + + # Training loop. + def train_loop_per_worker(config): + + # Read configurations. + lr = config["lr"] + batch_size = config["batch_size"] + num_epochs = config["num_epochs"] + + # Fetch training dataset. + train_dataset_shard = ray.train.get_dataset_shard("train") + + # Instantiate and prepare model for training. + model = NeuralNetwork() + model = ray.train.torch.prepare_model(model) + + # Define loss and optimizer. + loss_fn = nn.MSELoss() + optimizer = torch.optim.SGD(model.parameters(), lr=lr) + + # Create data loader. + dataloader = train_dataset_shard.iter_torch_batches( + batch_size=batch_size, dtypes=torch.float + ) + + # Train multiple epochs. + for epoch in range(num_epochs): + + # Train epoch. + for batch in dataloader: + output = model(batch["input"]) + loss = loss_fn(output, batch["label"]) + optimizer.zero_grad() + loss.backward() + optimizer.step() + + # Create checkpoint. + base_model = (model.module + if isinstance(model, DistributedDataParallel) else model) + checkpoint_dir = tempfile.mkdtemp() + torch.save( + {"model_state_dict": base_model.state_dict()}, + os.path.join(checkpoint_dir, "model.pt"), + ) + checkpoint = Checkpoint.from_directory(checkpoint_dir) + + # Report metrics and checkpoint. + ray.train.report({"loss": loss.item()}, checkpoint=checkpoint) + + + # Define configurations. + train_loop_config = {"num_epochs": 20, "lr": 0.01, "batch_size": 32} + scaling_config = ScalingConfig(num_workers=num_workers, use_gpu=use_gpu) + run_config = RunConfig(checkpoint_config=CheckpointConfig(num_to_keep=1)) + + # Define datasets. + train_dataset = ray.data.from_items( + [{"input": [x], "label": [2 * x + 1]} for x in range(2000)] + ) + datasets = {"train": train_dataset} + + # Initialize the Trainer. + trainer = TorchTrainer( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + scaling_config=scaling_config, + run_config=run_config, + datasets=datasets + ) + + # Train the model. + result = trainer.fit() + + # Inspect the results. + final_loss = result.metrics["loss"] + + .. testoutput:: + :hide: + + ... + + Args: + + train_loop_per_worker: The training function to execute on each worker. + This function can either take in zero arguments or a single ``Dict`` + argument which is set by defining ``train_loop_config``. + Within this function you can use any of the + :ref:`Ray Train Loop utilities `. + train_loop_config: A configuration ``Dict`` to pass in as an argument to + ``train_loop_per_worker``. + This is typically used for specifying hyperparameters. Passing large + datasets via `train_loop_config` is not recommended and may introduce + large overhead and unknown issues with serialization and deserialization. + torch_config: The configuration for setting up the PyTorch Distributed backend. + If set to None, a default configuration will be used in which + GPU training uses NCCL and CPU training uses Gloo. + scaling_config: The configuration for how to scale data parallel training. + ``num_workers`` determines how many Python processes are used for training, + and ``use_gpu`` determines whether or not each process should use GPUs. + See :class:`~ray.train.ScalingConfig` for more info. + run_config: The configuration for the execution of the training run. + See :class:`~ray.train.RunConfig` for more info. + datasets: The Ray Datasets to ingest for training. + Datasets are keyed by name (``{name: dataset}``). + Each dataset can be accessed from within the ``train_loop_per_worker`` + by calling ``ray.train.get_dataset_shard(name)``. + Sharding and additional configuration can be done by + passing in a ``dataset_config``. + dataset_config: The configuration for ingesting the input ``datasets``. + By default, all the Ray Dataset are split equally across workers. + See :class:`~ray.train.DataConfig` for more details. + resume_from_checkpoint: A checkpoint to resume training from. + This checkpoint can be accessed from within ``train_loop_per_worker`` + by calling ``ray.train.get_checkpoint()``. + metadata: Dict that should be made available via + `ray.train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + """ + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + torch_config: Optional[TorchConfig] = None, + scaling_config: Optional[ScalingConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + dataset_config: Optional[DataConfig] = None, + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + if not torch_config: + torch_config = TorchConfig() + + super(TorchTrainer, self).__init__( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + backend_config=torch_config, + scaling_config=scaling_config, + dataset_config=dataset_config, + run_config=run_config, + datasets=datasets, + resume_from_checkpoint=resume_from_checkpoint, + metadata=metadata, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/train_loop_utils.py b/venv/lib/python3.10/site-packages/ray/train/torch/train_loop_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ea5628268875864dd5e5578d2f33902466ccdf70 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/torch/train_loop_utils.py @@ -0,0 +1,776 @@ +import collections +import logging +import os +import random +import types +from typing import Any, Callable, Dict, List, Optional, Union + +import numpy as np +import torch +from packaging.version import Version +from torch.cuda.amp import GradScaler, autocast +from torch.nn.parallel import DistributedDataParallel +from torch.optim import Optimizer +from torch.utils.data import ( + DataLoader, + DistributedSampler, + IterableDataset, + RandomSampler, + SequentialSampler, +) + +from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag +from ray.air._internal.device_manager import ( + get_torch_device_manager_by_context, + get_torch_device_manager_by_device_type, +) +from ray.train._internal import session +from ray.train._internal.accelerator import Accelerator +from ray.train._internal.session import get_accelerator, set_accelerator +from ray.train.utils import _log_deprecation_warning +from ray.util.annotations import Deprecated, PublicAPI + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="stable") +def get_device() -> torch.device: + """Gets the correct torch device configured for this process. + + Returns the torch device for the current worker. If more than 1 GPU is + requested per worker, returns the device with the minimal device index. + + .. note:: + + If you requested multiple GPUs per worker, and want to get + the full list of torch devices, please use + :meth:`~ray.train.torch.get_devices`. + + Assumes that `CUDA_VISIBLE_DEVICES` is set and is a + superset of the `ray.get_gpu_ids()`. + + Examples: + + Example: Launched 2 workers on the current node, each with 1 GPU + + .. testcode:: + :skipif: True + + os.environ["CUDA_VISIBLE_DEVICES"] = "2,3" + ray.get_gpu_ids() == [2] + torch.cuda.is_available() == True + get_device() == torch.device("cuda:0") + + Example: Launched 4 workers on the current node, each with 1 GPU + + .. testcode:: + :skipif: True + + os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3" + ray.get_gpu_ids() == [2] + torch.cuda.is_available() == True + get_device() == torch.device("cuda:2") + + Example: Launched 2 workers on the current node, each with 2 GPUs + + .. testcode:: + :skipif: True + + os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3" + ray.get_gpu_ids() == [2,3] + torch.cuda.is_available() == True + get_device() == torch.device("cuda:2") + + + You can move a model to device by: + + .. testcode:: + :skipif: True + + model.to(ray.train.torch.get_device()) + + Instead of manually checking the device type: + + .. testcode:: + :skipif: True + + model.to("cuda" if torch.cuda.is_available() else "cpu") + """ + from ray.air._internal import torch_utils + + record_extra_usage_tag(TagKey.TRAIN_TORCH_GET_DEVICE, "1") + return torch_utils.get_devices()[0] + + +@PublicAPI(stability="beta") +def get_devices() -> List[torch.device]: + """Gets the correct torch device list configured for this process. + + Assumes that `CUDA_VISIBLE_DEVICES` is set and is a + superset of the `ray.get_gpu_ids()`. + + + Examples: + + Example: Launched 2 workers on the current node, each with 1 GPU + + .. testcode:: + :skipif: True + + os.environ["CUDA_VISIBLE_DEVICES"] == "2,3" + ray.get_gpu_ids() == [2] + torch.cuda.is_available() == True + get_devices() == [torch.device("cuda:0")] + + Example: Launched 4 workers on the current node, each with 1 GPU + + .. testcode:: + :skipif: True + + os.environ["CUDA_VISIBLE_DEVICES"] == "0,1,2,3" + ray.get_gpu_ids() == [2] + torch.cuda.is_available() == True + get_devices() == [torch.device("cuda:2")] + + Example: Launched 2 workers on the current node, each with 2 GPUs + + .. testcode:: + :skipif: True + + os.environ["CUDA_VISIBLE_DEVICES"] == "0,1,2,3" + ray.get_gpu_ids() == [2,3] + torch.cuda.is_available() == True + get_devices() == [torch.device("cuda:2"), torch.device("cuda:3")] + """ + + from ray.air._internal import torch_utils + + record_extra_usage_tag(TagKey.TRAIN_TORCH_GET_DEVICES, "1") + return torch_utils.get_devices() + + +@PublicAPI(stability="stable") +def prepare_model( + model: torch.nn.Module, + move_to_device: Union[bool, torch.device] = True, + parallel_strategy: Optional[str] = "ddp", + parallel_strategy_kwargs: Optional[Dict[str, Any]] = None, +) -> torch.nn.Module: + """Prepares the model for distributed execution. + + This allows you to use the same exact code regardless of number of + workers or the device type being used (CPU, GPU). + + Args: + model (torch.nn.Module): A torch model to prepare. + move_to_device: Either a boolean indiciating whether to move + the model to the correct device or an actual device to + move the model to. If set to False, the model needs + to manually be moved to the correct device. + parallel_strategy ("ddp", "fsdp", or None): Whether to wrap models + in ``DistributedDataParallel``, ``FullyShardedDataParallel``, + or neither. + parallel_strategy_kwargs (Dict[str, Any]): Args to pass into + ``DistributedDataParallel`` or ``FullyShardedDataParallel`` + initialization if ``parallel_strategy`` is set to "ddp" + or "fsdp", respectively. + """ + if parallel_strategy == "fsdp" and Version(torch.__version__) < Version("1.11.0"): + raise ImportError( + "FullyShardedDataParallel requires torch>=1.11.0. " + "Run `pip install 'torch>=1.11.0'` to use FullyShardedDataParallel." + ) + + record_extra_usage_tag(TagKey.TRAIN_TORCH_PREPARE_MODEL, "1") + return get_accelerator(_TorchAccelerator).prepare_model( + model, + move_to_device=move_to_device, + parallel_strategy=parallel_strategy, + parallel_strategy_kwargs=parallel_strategy_kwargs, + ) + + +@PublicAPI(stability="stable") +def prepare_data_loader( + data_loader: torch.utils.data.DataLoader, + add_dist_sampler: bool = True, + move_to_device: bool = True, + auto_transfer: bool = True, +) -> torch.utils.data.DataLoader: + """Prepares :class:`~torch.utils.data.DataLoader` for distributed execution. + + This allows you to use the same exact code regardless of number of + workers or the device type being used (CPU, GPU). + + .. note:: + + This method adds a `DistributedSampler` to the `DataLoader` if the + number of training workers is greater than 1. If shuffling is + enabled on the original `DataLoader`, then `shuffle=True` will also + be passed into the `DistributedSampler` constructor. `shuffle=False` + on the original `DataLoader` also means that shuffling is disabled + on the sampler. + + With more than 1 worker, calling the `DistributedSampler.set_epoch` method + at the beginning of each epoch before creating the DataLoader iterator + is necessary to make shuffling work properly across multiple epochs. + Otherwise, the same ordering will be always used. + See: https://pytorch.org/docs/stable/data.html#torch.utils.data.distributed.DistributedSampler # noqa: E501 + + Example: + + .. testcode: + :skipif: True + + import torch + + import ray.train.torch + + train_dataloader = torch.utils.data.DataLoader( + ..., batch_size=..., shuffle=True + ) + train_dataloader = ray.train.torch.prepare_data_loader(train_loader) + + for epoch in range(10): + if ray.train.get_context().get_world_size() > 1: + # Required for the distributed sampler to shuffle properly across epochs + train_dataloader.sampler.set_epoch(epoch) + + for X, y in train_loader: + # No need to move data to GPU, this is done by `prepare_data_loader`! + # X, y = X.to("cuda"), y.to("cuda") + ... + + Args: + data_loader (torch.utils.data.DataLoader): The DataLoader to + prepare. + add_dist_sampler: Whether to add a DistributedSampler to + the provided DataLoader. + move_to_device: If set, automatically move the data + returned by the data loader to the correct device. + auto_transfer: If set and device is GPU, another CUDA stream + is created to automatically copy data from host (CPU) memory + to device (GPU) memory (the default CUDA stream still runs the + training procedure). If device is CPU, it will be disabled + regardless of the setting. This configuration will be ignored + if ``move_to_device`` is False. + """ + record_extra_usage_tag(TagKey.TRAIN_TORCH_PREPARE_DATALOADER, "1") + return get_accelerator(_TorchAccelerator).prepare_data_loader( + data_loader, + add_dist_sampler=add_dist_sampler, + move_to_device=move_to_device, + auto_transfer=auto_transfer, + ) + + +def _log_amp_deprecation_warning(): + # Keep V2 imports out of top-level V1 imports. + from ray.train.v2.torch.train_loop_utils import _TORCH_AMP_DEPRECATION_MESSAGE + + _log_deprecation_warning(_TORCH_AMP_DEPRECATION_MESSAGE) + + +@Deprecated +def accelerate(amp: bool = False) -> None: + """[Deprecated] Enables training optimizations. + + Arguments: + amp: If true, perform training with automatic mixed precision. + Otherwise, use full precision. + + .. warning:: ``train.torch.accelerate`` cannot be called more than once, and it + must be called before any other ``train.torch`` utility function. + """ + _log_amp_deprecation_warning() + try: + set_accelerator(_TorchAccelerator(amp=amp)) + except RuntimeError: + raise RuntimeError( + "An accelerator has already been set. Make sure " + "`train.torch.accelerate()` is not called multiple times, and is called " + "before any of the prepare methods." + ) + + +@Deprecated +def prepare_optimizer(optimizer: torch.optim.Optimizer) -> torch.optim.Optimizer: + """[Deprecated] Wraps optimizer to support automatic mixed precision. + + Args: + optimizer (torch.optim.Optimizer): The DataLoader to prepare. + + Returns: + A wrapped optimizer. + """ + _log_amp_deprecation_warning() + return get_accelerator(_TorchAccelerator).prepare_optimizer(optimizer) + + +@Deprecated +def backward(tensor: torch.Tensor) -> None: + """[Deprecated] Computes the gradient of the specified tensor w.r.t. graph leaves. + + Args: + tensor (torch.Tensor): Tensor of which the derivative will be computed. + """ + _log_amp_deprecation_warning() + get_accelerator(_TorchAccelerator).backward(tensor) + + +@PublicAPI(stability="stable") +def enable_reproducibility(seed: int = 0) -> None: + """Limits sources of nondeterministic behavior. + + This function: + + * Seeds PyTorch, Python, and NumPy. + * Disables CUDA convolution benchmarking. + * Configures PyTorch to use determinstic algorithms. + * Seeds workers spawned for multi-process data loading. + + Args: + seed: The number to seed libraries and data workers with. + + .. warning:: ``train.torch.enable_reproducibility()`` can't guarantee + completely reproducible results across executions. To learn more, read + the `PyTorch notes on randomness + `_. + """ + get_accelerator(_TorchAccelerator).enable_reproducibility(seed) + + +@Deprecated +class TorchWorkerProfiler: + """Utility class for running PyTorch Profiler on a Train worker. + + Args: + trace_dir (Optional[str]): The directory to store traces on the + worker node. If ``None``, this will use a default temporary dir. + """ + + WORKER_TRACE_DIR_NAME = "pytorch_profiler_worker_traces" + + def __init__(self, trace_dir: Optional[str] = None): + raise DeprecationWarning( + "The `ray.train.torch.TorchWorkerProfiler` API is deprecated in Ray 2.0.", + ) + + +class _TorchAccelerator(Accelerator): + """A utility that implements methods to accelerate PyTorch training. + + Arguments: + amp: If true, perform training with automatic mixed precision. + Otherwise, use full precision. + """ + + def __init__(self, amp: bool = False): + self.amp_is_enabled = amp + self.scaler = GradScaler() if amp else None + self._seed = None + self.device_manager = get_torch_device_manager_by_context() + + def prepare_model( + self, + model: torch.nn.Module, + move_to_device: bool = True, + parallel_strategy: Optional[str] = "ddp", + parallel_strategy_kwargs: Optional[Dict[str, Any]] = None, + ) -> torch.nn.Module: + """Prepares the model for distributed execution. + + This allows you to use the same exact code regardless of number of + workers or the device type being used (CPU, GPU). + + Args: + model (torch.nn.Module): A torch model to prepare. + move_to_device: Whether to move the model to the correct + device. If set to False, the model needs to manually be moved + to the correct device. + parallel_strategy ("ddp", "fsdp", or None): Whether to wrap models + in ``DistributedDataParallel``, ``FullyShardedDataParallel`` ( + Experimental), or neither. + parallel_strategy_kwargs (Dict[str, Any]): Args to pass into + ``DistributedDataParallel`` or ``FullyShardedDataParallel`` + initialization if ``parallel_strategy`` is set to "ddp" + or "fsdp", respectively. + """ + parallel_strategy_kwargs = parallel_strategy_kwargs or {} + + rank = session.get_local_rank() + + if isinstance(move_to_device, torch.device): + device = move_to_device + else: + device = get_device() + if isinstance(device, list): + device = device[0] + + if self.device_manager.is_available(): + self.device_manager.set_device(device) + + if move_to_device: + if rank == 0: + logger.info(f"Moving model to device: {device}") + else: + logger.debug(f"Moving model to device: {device}") + model = model.to(device) + + def model_get_state(self): + # `__getstate__` is an special method that informs pickle which attributes + # to serialize. This custom implementation ensures that the wrapped forward + # method and custom `__getstate__` method aren't serialized. + if hasattr(self, "_original_get_state"): + state = self._original_get_state() + state["__getstate__"] = state["_original_get_state"] + del state["_original_get_state"] + else: + # If model does not have a `__getstate__` already defined, use default + # implementation. + state = self.__dict__.copy() + del state["__getstate__"] + state["forward"] = state["_unwrapped_forward"] + del state["_unwrapped_forward"] + + return state + + if self.amp_is_enabled: + # Pickle cannot serialize the wrapped forward method. As a workaround, + # define a custom `__getstate__` method that unwraps the forward method. + model._unwrapped_forward = model.forward + model.forward = autocast()(model.forward) + + # TODO(amogkam): Replace below logic with a generic "unpack model" method. + # Replacing the `model.forward` method makes the model no longer + # serializable. When serializing the model, we have to override the + # `__getstate__` method to set back the original forward method. + if hasattr(model, "__getstate__"): + model._original_get_state = model.__getstate__ + # `__getstate__` must be a bound method rather than an callable attribute. + # See https://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object-instance. # noqa: E501 + model.__getstate__ = types.MethodType(model_get_state, model) + + world_size = session.get_world_size() + + if parallel_strategy and world_size > 1: + if parallel_strategy == "ddp": + DataParallel = DistributedDataParallel + if self.device_manager.is_available() and device.type != "cpu": + parallel_strategy_kwargs = { + "device_ids": [device], + "output_device": device, + **parallel_strategy_kwargs, + } + else: + if not torch.cuda.is_available(): + raise RuntimeError( + "FSDP is only available with GPU-enabled " + "training. Set " + "`use_gpu=True` in your Trainer to train with " + "GPUs." + ) + from torch.distributed.fsdp import FullyShardedDataParallel + + DataParallel = FullyShardedDataParallel + if rank == 0: + logger.info(f"Wrapping provided model in {DataParallel.__name__}.") + else: + logger.debug(f"Wrapping provided model in {DataParallel.__name__}.") + model = DataParallel(model, **parallel_strategy_kwargs) + + return model + + def prepare_data_loader( + self, + data_loader: torch.utils.data.DataLoader, + add_dist_sampler: bool = True, + move_to_device: bool = True, + auto_transfer: bool = False, + ) -> torch.utils.data.DataLoader: + """Prepares DataLoader for distributed execution. + + This allows you to use the same exact code regardless of number of + workers or the device type being used (CPU, GPU). + + Args: + data_loader (torch.utils.data.DataLoader): The DataLoader to + prepare. + add_dist_sampler: Whether to add a DistributedSampler to + the provided DataLoader. + move_to_device: If set, automatically move the data + returned by the data loader to the correct device. + auto_transfer: (Experimental) If set and device is GPU, another CUDA stream + is created to automatically copy data from host (CPU) memory + to device (GPU) memory (the default CUDA stream still runs the + training procedure). If device is CPU, it will be disabled + regardless of the setting. This configuration will be ignored + if ``move_to_device`` is False. + """ + + world_size = session.get_world_size() + world_rank = session.get_world_rank() + + # Only add Distributed Sampler if the following conditions hold: + # 1. More than one training worker is being used. + # 2. A DistributedSampler has not already been added by the user. + # 3. The dataset is not an IterableDataset. Samplers do not worker with + # IterableDatasets. + if ( + world_size > 1 + and not isinstance(data_loader.sampler, DistributedSampler) + and not ( + hasattr(data_loader, "dataset") + and isinstance(data_loader.dataset, IterableDataset) + ) + and add_dist_sampler + ): + + def with_sampler(loader): + # Automatically set the DistributedSampler + + # If you're using a sampler, the DataLoader shuffle flag must be set to + # False. Shuffling is instead determined by the shuffle argument passed + # to the DistributedSampler constructor. + + # If no sampler is passed to the DataLoader constructor, Torch + # constructs a default sampler. The default sampler is a RandomSampler + # if shuffling is enabled and a SequentialSampler otherwise. DataLoader + # does not have a shuffle attribute, so we instead identify whether + # shuffling is enabled by checking the default sampler type. + shuffle = not isinstance(loader.sampler, SequentialSampler) + + def seeded_worker_init_fn( + worker_init_fn: Optional[Callable[[int], None]], + ): + def wrapper(worker_id: int): + worker_seed = torch.initial_seed() % 2**32 + np.random.seed(worker_seed) + random.seed(worker_seed) + if worker_init_fn: + worker_init_fn(worker_id) + + return wrapper + + worker_init_fn: Optional[Callable[[int], None]] = loader.worker_init_fn + generator: Optional[torch.Generator] = loader.generator + if self._seed is not None: + worker_init_fn = seeded_worker_init_fn(worker_init_fn) + generator = torch.Generator() + generator.manual_seed(self._seed) + + using_default_sampler = isinstance( + loader.sampler, (SequentialSampler, RandomSampler) + ) + if not using_default_sampler and world_rank == 0: + logger.warning( + f"The {loader.sampler.__class__.__name__} will be overwritten " + "with a DistributedSampler. You can disable this by setting " + "`with_sampler` to False in `prepare_data_loader`." + ) + + data_loader_args = { + "dataset": loader.dataset, + "batch_size": loader.batch_size, + "shuffle": False, + "num_workers": loader.num_workers, + "collate_fn": loader.collate_fn, + "pin_memory": loader.pin_memory, + "drop_last": loader.drop_last, + "timeout": loader.timeout, + "worker_init_fn": worker_init_fn, + "generator": generator, + "sampler": DistributedSampler(loader.dataset, shuffle=shuffle), + } + return DataLoader(**data_loader_args) + + data_loader = with_sampler(data_loader) + + if move_to_device: + device = get_device() + data_loader = _WrappedDataLoader(data_loader, device, auto_transfer) + + return data_loader + + def prepare_optimizer(self, optimizer: Optimizer) -> Optimizer: + """Wraps optimizer to support automatic mixed precision. + + Args: + optimizer (torch.optim.Optimizer): The DataLoader to prepare. + + Returns: + A wrapped optimizer. + """ + return _WrappedOptimizer(optimizer, scaler=self.scaler) + + def backward(self, tensor: torch.Tensor) -> None: + """Computes the gradient of the specified tensor w.r.t. graph leaves. + + Args: + tensor (torch.Tensor): Tensor of which the derivative will be computed. + """ + if self.amp_is_enabled: + self.scaler.scale(tensor).backward() + else: + tensor.backward() + + def enable_reproducibility(self, seed: int = 0) -> None: + """Limits sources of nondeterministic behavior.""" + self._seed = seed + + torch.manual_seed(seed) + random.seed(seed) + np.random.seed(seed) + + torch.use_deterministic_algorithms(True) + torch.backends.cudnn.benchmark = False + + # If you want to use deterministic algorithms with CUDA, then you need to set + # the CUBLAS_WORKSPACE_CONFIG environment variable; otherwise, Torch errors. + # See https://docs.nvidia.com/cuda/cublas/index.html#cublasApi_reproducibility. + os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" + + +class _WrappedDataLoader(DataLoader): + def __init__( + self, base_dataloader: DataLoader, device: torch.device, auto_transfer: bool + ): + self.__dict__.update(getattr(base_dataloader, "__dict__", {})) + self._dataloader = base_dataloader + self.dataloader_iter = None + self.device = device + + self.device_manager = get_torch_device_manager_by_device_type(device.type) + + # disable auto transfer (host->device) if cpu is used + if device.type != "cpu" and self.device_manager.supports_stream(): + self._auto_transfer = auto_transfer + else: + self._auto_transfer = False + # create a new device stream to move data from host to device concurrently + self._memcpy_stream = ( + self.device_manager.create_stream(device) + if device.type != "cpu" and self._auto_transfer + else None + ) + self.next_batch = None + + def _move_to_device(self, item): + if item is None: + return None + + def try_move_device(i): + try: + i = i.to(self.device, non_blocking=self._auto_transfer) + except AttributeError: + logger.debug(f"Item {i} cannot be moved to device " f"{self.device}.") + return i + + with self.device_manager.get_stream_context(self._memcpy_stream): + if isinstance(item, collections.abc.Mapping): + item_on_device = {k: self._move_to_device(v) for k, v in item.items()} + elif isinstance(item, tuple): + item_on_device = tuple(self._move_to_device(i) for i in item) + elif isinstance(item, list): + item_on_device = [self._move_to_device(i) for i in item] + elif isinstance(item, torch.Tensor): + item_on_device = try_move_device(item) + else: + logger.debug( + f"Data type {type(item)} doesn't support being moved to device." + ) + item_on_device = item + + return item_on_device + + def _wait_for_batch(self, item): + if self._memcpy_stream is None: + return + # Reference: + # https://pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html + # The training stream (current) needs to wait until + # the memory copy stream finishes. + curr_stream = self.device_manager.get_current_stream() + curr_stream.wait_stream(self._memcpy_stream) + # When a tensor is used by CUDA streams different from + # its original allocator, we need to call ``record_stream`` + # to inform the allocator of all these streams. Otherwise, + # the tensor might be freed once it is no longer used by + # the creator stream. + for i in item: + # The Pytorch DataLoader has no restrictions on what is outputted for + # each batch. We should only ``record_stream`` if the item has the + # ability to do so. + try: + i.record_stream(curr_stream) + except AttributeError: + pass + + def __len__(self): + return len(self._dataloader) + + def _prefetch_next_batch(self): + next_batch = next(self.dataloader_iter, None) + self.next_batch = self._move_to_device(next_batch) + + def __iter__(self): + self.dataloader_iter = iter(self._dataloader) + self._prefetch_next_batch() + return self + + def __next__(self): + next_batch = self.next_batch + if next_batch is None: + raise StopIteration + self._wait_for_batch(next_batch) + self._prefetch_next_batch() + return next_batch + + +class _WrappedOptimizer(Optimizer): + def __init__(self, optimizer: Optimizer, scaler: Optional[GradScaler] = None): + self.optimizer = optimizer + self.scaler = scaler + + @property + def state(self): + return self.optimizer.state + + @state.setter + def state(self, state): + self.optimizer.state = state + + @property + def param_groups(self): + return self.optimizer.param_groups + + @param_groups.setter + def param_groups(self, param_groups): + self.optimizer.param_groups = param_groups + + @property + def defaults(self): + return self.optimizer.defaults + + @defaults.setter + def defaults(self, defaults): + self.optimizer.defaults = defaults + + def add_param_group(self, param_group): + self.optimizer.add_param_group(param_group) + + def load_state_dict(self, state_dict): + self.optimizer.load_state_dict(state_dict) + + def state_dict(self): + return self.optimizer.state_dict() + + def zero_grad(self): + self.optimizer.zero_grad() + + def step(self, closure=None): + if self.scaler is not None: + self.scaler.step(self.optimizer, closure) + self.scaler.update() + else: + self.optimizer.step(closure) diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/xla/__init__.py b/venv/lib/python3.10/site-packages/ray/train/torch/xla/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea32abc8c9d7b5514b3c5680e06ee0ab334eb4eb --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/torch/xla/__init__.py @@ -0,0 +1,5 @@ +from ray.train.torch.xla.config import TorchXLAConfig + +__all__ = [ + "TorchXLAConfig", +] diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/xla/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/torch/xla/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..061a8d46f314254ae1275e80236755fe304ef7f0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/torch/xla/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/xla/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/torch/xla/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49dd810002e2b8ae8e2448d20db085aaf4582042 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/torch/xla/__pycache__/config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/torch/xla/config.py b/venv/lib/python3.10/site-packages/ray/train/torch/xla/config.py new file mode 100644 index 0000000000000000000000000000000000000000..e965f9fc269acbc19dded2001051bf350ddf80f1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/torch/xla/config.py @@ -0,0 +1,169 @@ +import logging +import os +import re +import shutil +import uuid +from dataclasses import dataclass + +import ray +from ray.train._internal.utils import get_address_and_port +from ray.train._internal.worker_group import WorkerGroup +from ray.train.backend import Backend +from ray.train.torch import TorchConfig +from ray.util import PublicAPI + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="alpha") +@dataclass +class TorchXLAConfig(TorchConfig): + """ + Configuration for torch XLA setup. + See https://pytorch.org/xla/release/1.13/index.html for more info. + Currently, only "neuron_cores" accelerator (AwsNeuronXLABackend) + is supported with xrt runtime. + """ + + neuron_parallel_compile: bool = False + + @property + def backend_cls(self): + return _TorchAwsNeuronXLABackend + + +def _kill_xrt_server(): + import subprocess + + subprocess.call(["pkill", "-f", "xrt_run_server"]) + + +def _set_xla_env_vars(): + # https://pytorch.org/docs/1.13/elastic/run.html#environment-variables + context = ray.train.get_context() + + os.environ["LOCAL_RANK"] = str(context.get_local_rank()) + os.environ["RANK"] = str(context.get_world_rank()) + os.environ["LOCAL_WORLD_SIZE"] = str(context.get_local_world_size()) + os.environ["WORLD_SIZE"] = str(context.get_world_size()) + os.environ["GROUP_RANK"] = str(context.get_node_rank()) + os.environ["GROUP_WORLD_SIZE"] = str( + context.get_world_size() / context.get_local_world_size() + ) + os.environ["ROLE_RANK"] = str(context.get_world_rank()) + os.environ["ROLE_WORLD_RANK"] = str(context.get_world_rank()) + os.environ["ROLE_WORLD_SIZE"] = str(context.get_world_size()) + + # EFA and XLA setup + # https://github.com/aws/libfabric/blob/master/prov/efa/src/rxr/rxr_init.c + # https://github.com/aws-neuron/aws-neuron-samples/blob/master/torch-neuronx/training/dp_bert_hf_pretrain/run_dp_bert_large_hf_pretrain_bf16_s128.sh # noqa + os.environ["FI_PROVIDER"] = "efa" + os.environ["FI_EFA_USE_DEVICE_RDMA"] = "1" + os.environ["FI_EFA_FORK_SAFE"] = "1" + os.environ["XLA_TRANSFER_SEED_ASYNC"] = "1" + os.environ["NCCL_ASYNC_ERROR_HANDLING"] = "1" + + +def _setup_xla_torch_process_group(): + try: + import torch.distributed as dist + import torch_xla.core.xla_model as xm # noqa F401 + import torch_xla.distributed.xla_backend # noqa F401 + + dist.init_process_group("xla") + except ImportError: + raise ImportError("torch_xla must be installed to use torch_xla backend.") + + +# The following env vars enable Neuron graph extraction for parallel compilation +# Note: model outputs are invalid and should be ignored while these env vars are set +def _set_neuron_parallel_compile_env_vars(): + os.environ["NEURON_PARALLEL_COMPILE"] = "1" + os.environ["NEURON_EXTRACT_GRAPHS_ONLY"] = "1" + os.environ["NEURON_FALL_BACK_TO_NULL_NEFF"] = "1" + + +# Compile previously extracted Neuron graphs +def _neuron_compile_extracted_graphs(): + try: + from libneuronxla.neuron_cc_cache import CacheUrl + from libneuronxla.neuron_parallel_compile import parallel_compile + except ImportError: + raise ImportError( + "libneuronxla must be installed to use Neuron parallel compilation." + ) + + # Only 1 worker per node should run parallel_compile() + if os.environ.get("LOCAL_RANK") == "0": + logger.info("Compiling extracted graphs on local rank0 worker") + + parallel_compile_workdir = ( + f"/tmp/{os.environ.get('USER','no-user')}/parallel_compile_workdir/" + ) + if os.path.exists(parallel_compile_workdir): + shutil.rmtree(parallel_compile_workdir) + os.makedirs(parallel_compile_workdir, exist_ok=True) + + # Users can set the cache directory using --cache_dir in NEURON_CC_FLAGS or by + # using NEURON_COMPILE_CACHE_URL. --cache_dir takes precedence. + explicit_cache_dir = None + if neuron_cc_flags := os.environ.get("NEURON_CC_FLAGS"): + if s := re.search(r"--cache_dir[= ](\S+)", neuron_cc_flags): + explicit_cache_dir = s.group(1) + + parallel_compile( + parallel_compile_workdir, + CacheUrl.get_cache_url(explicit_cache_dir), + ) + + +class _TorchAwsNeuronXLABackend(Backend): + unique_run_id: str = str(uuid.uuid4()) + + def on_start(self, worker_group: WorkerGroup, backend_config: TorchXLAConfig): + """Logic ran right before training is started.""" + + # On previous worker failure, we don't run graceful shutdown on workers. + # This would leak any running xrt server. + worker_group.execute(_kill_xrt_server) + + # Get master address and port from the first worker. + master_addr, master_port = worker_group.execute_single(0, get_address_and_port) + + def set_env_vars(addr, port): + os.environ["MASTER_ADDR"] = addr + os.environ["MASTER_PORT"] = str(port) + # To trigger the xrt server + os.environ["TORCHELASTIC_RUN_ID"] = self.unique_run_id + + # Set the env vars on all workers. + worker_group.execute(set_env_vars, addr=master_addr, port=master_port) + + # Set up env vars for neuron parallel compilation graph extraction + if backend_config.neuron_parallel_compile: + logger.info("Extracting graphs for Neuron parallel compilation") + worker_group.execute(_set_neuron_parallel_compile_env_vars) + + def on_training_start( + self, worker_group: WorkerGroup, backend_config: TorchXLAConfig + ): + """ + Configure the environment variables for the worker group. + And initialize the xla distributed process group. + TODO: Current setup only supports homogenous cluster with + neuron_cores accelerator and xrt runtime. + """ + worker_group.execute(_set_xla_env_vars) + worker_group.execute(_setup_xla_torch_process_group) + + def on_shutdown(self, worker_group: WorkerGroup, backend_config: TorchXLAConfig): + """ + Logic ran right after training is finished. + This is a sanity cleanup to kill xrt server, and to optionally + run neuron parallel graph compilation + """ + worker_group.execute(_kill_xrt_server) + + # Compile the extracted graphs. This must run at end of training. + if backend_config.neuron_parallel_compile: + worker_group.execute(_neuron_compile_extracted_graphs) diff --git a/venv/lib/python3.10/site-packages/ray/train/trainer.py b/venv/lib/python3.10/site-packages/ray/train/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..725ba029d766c37d838e456f58abd2182e836a8d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/trainer.py @@ -0,0 +1,194 @@ +import logging +import traceback +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, TypeVar, Union + +from ray.air._internal.util import ( + StartTraceback, + StartTracebackWithWorkerRank, + skip_exceptions, +) +from ray.data import Dataset +from ray.train import Checkpoint, DataConfig +from ray.train._internal.backend_executor import ( + BackendExecutor, + InactiveWorkerGroupError, + TrainBackendError, + TrainingWorkerError, +) +from ray.train._internal.session import _TrainingResult, _TrainSession, get_session +from ray.train._internal.utils import ActorWrapper +from ray.train.backend import BackendConfig +from ray.train.base_trainer import ( # noqa: F401 + BaseTrainer, + GenDataset, + TrainingFailedError, +) +from ray.util.annotations import DeveloperAPI + +T = TypeVar("T") +S = TypeVar("S") + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class TrainingIterator: + """An iterator over Train results. Returned by ``trainer.run_iterator``.""" + + def __init__( + self, + backend_executor: Union[BackendExecutor, ActorWrapper], + backend_config: BackendConfig, + train_func: Union[Callable[[], T], Callable[[Dict[str, Any]], T]], + datasets: Dict[str, Dataset], + metadata: Dict[str, Any], + data_config: DataConfig, + checkpoint: Optional[Union[Dict, str, Path, Checkpoint]], + ): + self._backend_executor = backend_executor + self._backend = backend_config.backend_cls() + self._train_func = train_func + self._datasets = datasets + self._metadata = metadata + self._data_config = data_config + + self._start_training( + train_func=train_func, + datasets=self._datasets, + metadata=self._metadata, + data_config=self._data_config, + checkpoint=checkpoint, + ) + + self._finished_training = False + + def __iter__(self): + return self + + def _start_training( + self, + train_func, + datasets, + metadata, + data_config, + checkpoint: Optional[Checkpoint] = None, + ): + tune_session: _TrainSession = get_session() + assert tune_session, "`_start_training` should only be called from within Tune" + storage = tune_session.storage + + self._run_with_error_handling( + lambda: self._backend_executor.start_training( + train_func=train_func, + datasets=datasets, + metadata=metadata, + data_config=data_config, + storage=storage, + checkpoint=checkpoint, + ) + ) + + def _run_with_error_handling(self, func: Callable): + try: + return func() + except TrainingWorkerError: + # TODO(ml-team): This Train fault-tolerance code doesn't get used + # since max_retries=0 + # Workers have already been restarted. + logger.info( + "Workers have been successfully restarted. Resuming " + "training from latest checkpoint." + ) + self._start_training( + self._train_func, + self._datasets, + self._metadata, + self._data_config, + ) + return self._run_with_error_handling(func) + except InactiveWorkerGroupError: + raise RuntimeError( + "This Trainer is not active. It is either shutdown " + "already or never started in the first place. " + "Either create a new Trainer or start this one." + ) from None + except TrainBackendError: + raise RuntimeError( + "Training failed. You should not be seeing " + "this error and this is a bug. Please create " + "a new issue at " + "https://github.com/ray-project/ray." + ) from None + + def __next__(self): + if self.is_finished(): + self._backend_executor.report_final_run_status(errored=False) + raise StopIteration + try: + next_results = self._run_with_error_handling(self._fetch_next_result) + if next_results is None: + self._backend_executor.report_final_run_status(errored=False) + self._run_with_error_handling(self._finish_training) + self._finished_training = True + raise StopIteration + else: + return next_results + except StartTraceback as e: + # If this is a StartTraceback, then this is a user error. + # We raise it directly + if isinstance(e, StartTracebackWithWorkerRank): + failed_rank = e.worker_rank + else: + failed_rank = None + + # Extract the stack trace from the exception + e = skip_exceptions(e) + stack_trace = "".join( + traceback.format_exception(type(e), e, e.__traceback__) + ) + + self._backend_executor.report_final_run_status( + errored=True, stack_trace=stack_trace, failed_rank=failed_rank + ) + try: + # Exception raised in at least one training worker. Immediately raise + # this error to the user and do not attempt to terminate gracefully. + self._backend_executor.shutdown(graceful_termination=False) + self._finished_training = True + except Exception: + pass + raise + + def _fetch_next_result(self) -> Optional[List[Dict]]: + """Fetch next results produced by ``session.report()`` from each worker. + + Assumes ``start_training`` has already been called. + + Returns: + A list of dictionaries of values passed to ``session.report()`` from + each worker. Each item corresponds to an intermediate result + a single worker. If there are no more items to fetch, + returns None. + """ + results = self._backend_executor.get_next_results() + if results is None: + return None + assert all(isinstance(result, _TrainingResult) for result in results) + return results + + def _finish_training(self): + """Finish training and return final results. Propagate any exceptions. + + Blocks until training is finished on all workers. + + Assumes `start_training` has already been called. + + Returns: + A list of return values from calling ``train_func`` on each worker. + Each item corresponds to the return value from a single worker. + """ + return self._backend_executor.finish_training() + + def is_finished(self) -> bool: + return self._finished_training diff --git a/venv/lib/python3.10/site-packages/ray/train/util/__init__.py b/venv/lib/python3.10/site-packages/ray/train/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f373b95bbd270009d820abab7f1e3c8324c6fa9f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/util/__init__.py @@ -0,0 +1,7 @@ +from ray.air.util.check_ingest import DummyTrainer + +__all__ = [ + "DummyTrainer", +] + +DummyTrainer.__module__ = "ray.train.util" diff --git a/venv/lib/python3.10/site-packages/ray/train/util/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/util/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e3e88ae71a7a81523479cea793e0a80dd988489 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/util/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/utils.py b/venv/lib/python3.10/site-packages/ray/train/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..395cd01ab968237b5f727a93b4d8e6b3e7861edc --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/utils.py @@ -0,0 +1,19 @@ +import warnings + +from ray.util.annotations import RayDeprecationWarning + + +def _copy_doc(copy_func): + def wrapped(func): + func.__doc__ = copy_func.__doc__ + return func + + return wrapped + + +def _log_deprecation_warning(message: str): + warnings.warn( + message, + RayDeprecationWarning, + stacklevel=2, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c94b1091351294493a9886bc4840ee483df0a097 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8be26f207d5cc459b5bf0d287ee850910c4bffa0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/constants.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3515cbf8b50dbba8230289511b9f776084e9092e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/constants.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..181d5d1944b6e91e8dbb57675198b38ef014803e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/exceptions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/migration_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/migration_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cc600f5eff6f6c486244bf3cb0cc47bcddd1162 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/migration_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/util.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1be26be2b63f55a2e2c1316578f624e2150da613 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/__pycache__/util.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c5b204acdcff27635778f57718f46bacf655a4a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__init__.py @@ -0,0 +1,16 @@ +from .accelerators import AcceleratorSetupCallback +from .backend_setup import BackendSetupCallback +from .datasets import DatasetsSetupCallback +from .state_manager import StateManagerCallback +from .working_dir_setup import WorkingDirectorySetupCallback + +__all__ = [ + "AcceleratorSetupCallback", + "BackendSetupCallback", + "DatasetsSetupCallback", + "StateManagerCallback", + "WorkingDirectorySetupCallback", +] + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d9eded64a3813afe14b1c44b0a87218c087efc3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/accelerators.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/accelerators.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e7b5f33a686c0441569022b80c2d3035439c8e0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/accelerators.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/backend_setup.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/backend_setup.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dba6b963def173520441ed8af746a650d0390a77 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/backend_setup.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/datasets.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/datasets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..546f1eb2f8994295a00e61f4e62de42165b63a78 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/datasets.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/env_callback.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/env_callback.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbbca758c13c18ddbd563fdb8e6d1b81f62286e5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/env_callback.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/metrics.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/metrics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36fe0b34d711916e1fd53c3469bfce7e455ab592 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/metrics.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/state_manager.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/state_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1b86ab9ca839248534594a8bd387a0245110b30 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/state_manager.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/user_callback.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/user_callback.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34fe151d946c597baedb4568725e6894829d5f00 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/user_callback.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/working_dir_setup.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/working_dir_setup.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9eb526873d31891197c701e06fd43bc1f8f1ad4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/__pycache__/working_dir_setup.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/accelerators.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/accelerators.py new file mode 100644 index 0000000000000000000000000000000000000000..81858f2b8a89e7824090749c18d11196067f909a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/accelerators.py @@ -0,0 +1,152 @@ +import logging +import os +from collections import defaultdict +from typing import List + +import ray._private.ray_constants as ray_constants +from ray._private.accelerators.nvidia_gpu import CUDA_VISIBLE_DEVICES_ENV_VAR +from ray._private.ray_constants import env_bool +from ray.train import BackendConfig +from ray.train.constants import ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV +from ray.train.v2._internal.execution.callback import WorkerGroupCallback +from ray.train.v2._internal.execution.worker_group import ActorMetadata, WorkerGroup +from ray.train.v2._internal.util import ray_get_safe +from ray.train.v2.api.config import ScalingConfig + +logger = logging.getLogger(__name__) + + +class AcceleratorSetupCallback(WorkerGroupCallback): + """Perform accelerator setup for workers. + + For example, this callback can be used to share CUDA_VISIBLE_DEVICES + among workers on the same node. + """ + + def __init__(self, backend_config: BackendConfig, scaling_config: ScalingConfig): + self._backend = backend_config.backend_cls() + self._scaling_config = scaling_config + + def after_worker_group_start(self, worker_group: WorkerGroup): + self._maybe_share_cuda_visible_devices(worker_group) + # TODO: Add support for sharing other accelerator resources. + + def _maybe_share_cuda_visible_devices(self, worker_group: WorkerGroup): + share_cuda_visible_devices_enabled = env_bool( + ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV, + self._backend.share_cuda_visible_devices, + ) + + if ( + self._scaling_config._resources_per_worker_not_none.get("GPU", 0) > 0 + and share_cuda_visible_devices_enabled + ): + _share_cuda_visible_devices(worker_group) + + +def _share_cuda_visible_devices(worker_group: WorkerGroup): + """Sets CUDA_VISIBLE_DEVICES on all workers. + For each worker, CUDA_VISIBLE_DEVICES will be set to the GPU IDs + visible to all workers on that worker's node. + This allows GPU workers on the same node to communicate with one + another. + + Example: + Setup: + - Node1: + - Worker1: {0, 1} + - Worker2: {2, 3} + - Node2: + - Worker3: {0, 1} + CUDA_VISIBLE_DEVICES: + - Worker1: "0,1,2,3" + - Worker2: "0,1,2,3" + - Worker2: "0,1" + """ + _share_accelerator_ids( + worker_group, ray_constants.GPU, CUDA_VISIBLE_DEVICES_ENV_VAR + ) + + +def _share_accelerator_ids( + worker_group: WorkerGroup, accelerator_name: str, env_var: str +): + """Sets the given env_var on all workers. + For each worker, the cores/devices are visible to all the + workers on that worker's node. This allows workers on the + same node to communicate with one another. + + Example: + Setup: + - Node1: + - Worker1: {0, 1} + - Worker2: {2, 3} + - Node2: + - Worker3: {0, 1} + NEURON_RT_VISIBLE_CORES/TPU_VISIBLE_CHIPS/...: + - Worker1: "0,1,2,3" + - Worker2: "0,1,2,3" + - Worker2: "0,1" + + Args: + accelerator_name: The name of the accelerator. + env_var: The name of the environment variable to set. + """ + if not worker_group.has_started(): + raise RuntimeError( + "WorkerGroup must be started before sharing accelerator IDs." + ) + + worker_metadatas = [worker.metadata for worker in worker_group.get_workers()] + visible_accelerator_ids_per_worker = _get_visible_accelerator_ids_per_worker( + worker_metadatas=worker_metadatas, accelerator_name=accelerator_name + ) + + def set_accelerator_ids(accelerator_ids): + os.environ[env_var] = accelerator_ids + + futures = [] + for rank, visible_accelerator_ids in enumerate(visible_accelerator_ids_per_worker): + futures.append( + worker_group.execute_single_async( + rank, set_accelerator_ids, accelerator_ids=visible_accelerator_ids + ) + ) + ray_get_safe(futures) + + +def _get_visible_accelerator_ids_per_worker( + worker_metadatas: List[ActorMetadata], accelerator_name: str +) -> List[str]: + """Returns a list of comma-separated accelerator IDs visible to each worker. + + All workers on a node should have the same set of visible accelerators, + which is the union of accelerator ids of the workers. + + Returns: + visible_accelerator_ids_per_worker: A list of comma-separated accelerator ID + strings. This list is the same length as the number of workers. + + """ + for metadata in worker_metadatas: + if accelerator_name not in metadata.accelerator_ids: + raise ValueError( + f"Accelerator '{accelerator_name}' is not available on all workers. " + f"Got these available accelerators instead: {metadata.accelerator_ids}" + ) + + node_id_to_accelerator_ids = defaultdict(set) + + for metadata in worker_metadatas: + node_id_to_accelerator_ids[metadata.node_id].update( + metadata.accelerator_ids[accelerator_name] + ) + + visible_accelerator_ids_per_worker = [] + for worker_id in range(len(worker_metadatas)): + node_id = worker_metadatas[worker_id].node_id + accelerator_ids = sorted(node_id_to_accelerator_ids[node_id]) + all_resource_ids = ",".join([str(id) for id in accelerator_ids]) + visible_accelerator_ids_per_worker.append(all_resource_ids) + + return visible_accelerator_ids_per_worker diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/backend_setup.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/backend_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8b592980f7e5c201f7ff541a0f592b7f1f54428f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/backend_setup.py @@ -0,0 +1,27 @@ +import logging + +from ray.exceptions import RayActorError +from ray.train.backend import BackendConfig +from ray.train.v2._internal.execution.callback import WorkerGroupCallback +from ray.train.v2._internal.execution.worker_group import WorkerGroup + +logger = logging.getLogger(__name__) + + +class BackendSetupCallback(WorkerGroupCallback): + def __init__(self, backend_config: BackendConfig): + self._backend_config = backend_config + self._backend = backend_config.backend_cls() + + def after_worker_group_start(self, worker_group: WorkerGroup): + self._backend.on_start(worker_group, self._backend_config) + self._backend.on_training_start(worker_group, self._backend_config) + + def before_worker_group_shutdown(self, worker_group: WorkerGroup): + try: + self._backend.on_shutdown(worker_group, self._backend_config) + except RayActorError: + logger.warning( + "Graceful shutdown of backend failed. This is " + "expected if one of the workers has crashed." + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/datasets.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..a51b633d457a5e20217ed5b5a25092be118d7456 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/datasets.py @@ -0,0 +1,77 @@ +import copy +from typing import Any, Callable, Dict, List, Union + +import ray.train +from ray.data import Dataset +from ray.data.context import DataContext +from ray.train.v2._internal.execution.callback import WorkerGroupCallback +from ray.train.v2._internal.execution.worker_group.worker_group import ( + Worker, + WorkerGroup, +) + +# A type representing either a ray.data.Dataset or a function that returns a +# ray.data.Dataset and accepts no arguments. +GenDataset = Union[Dataset, Callable[[], Dataset]] + + +class DatasetsSetupCallback(WorkerGroupCallback): + """The callback to setup Ray Datasets for the worker group.""" + + def __init__( + self, + datasets: Dict[str, GenDataset], + data_config: ray.train.DataConfig, + scaling_config: ray.train.ScalingConfig, + ): + self._datasets = datasets + self._data_config = data_config + self._scaling_config = scaling_config + + # Capture the current DataContext to propagate it to + # the Train workers later. + # The propagation works in the following way: + # 1. This callback is created when user create the Trainer. + # 2. Then this callback will be passed to the Controller actor. + # 3. Lastly, when the worker group is initialized, the Controller + # will call the `after_worker_group_start` callback to propagate + # the DataContext to Train workers. + self._data_context = copy.deepcopy(DataContext.get_current()) + + def get_train_total_resources( + self, scaling_config: ray.train.ScalingConfig + ) -> Dict[str, float]: + """Return the resources reserved for training, so that Data can exclude + these resources logically from its available pool.""" + return scaling_config.total_resources + + def before_init_train_context(self, workers: List[Worker]) -> Dict[str, List[Any]]: + # Configure dataset shards + datasets = {k: v() if callable(v) else v for k, v in self._datasets.items()} + node_ids = [worker.metadata.node_id for worker in workers] + + # Notify the DataConfig about the total resources reserved for training. + total_train_resources = self.get_train_total_resources(self._scaling_config) + self._data_config.set_train_total_resources( + total_train_resources.get("CPU", 0), total_train_resources.get("GPU", 0) + ) + + dataset_shards = self._data_config.configure( + datasets, + world_size=len(workers), + worker_handles=None, + worker_node_ids=node_ids, + ) + assert len(dataset_shards) == len(workers) + + return {"dataset_shards": dataset_shards} + + def after_worker_group_start(self, worker_group: WorkerGroup): + # Propagate DataContext + def _propagate_data_context(ctx: DataContext): + DataContext._set_current(ctx) + + worker_group.execute( + _propagate_data_context, + self._data_context, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/env_callback.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/env_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..3a7489b2a2f9544b59c5728573fde4eee4e6d5a2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/env_callback.py @@ -0,0 +1,39 @@ +import importlib +import os +from typing import List + +from ray.train.v2._internal.constants import RAY_TRAIN_CALLBACKS_ENV_VAR +from ray.train.v2._internal.execution.callback import RayTrainCallback + + +def _initialize_env_callbacks() -> List[RayTrainCallback]: + """Initialize callbacks from environment variable. + + Returns: + List of callbacks initialized from environment variable. + """ + callbacks = [] + callbacks_str = os.environ.get(RAY_TRAIN_CALLBACKS_ENV_VAR, "") + if not callbacks_str: + return callbacks + + for callback_path in callbacks_str.split(","): + callback_path = callback_path.strip() + if not callback_path: + continue + + try: + module_path, class_name = callback_path.rsplit(".", 1) + module = importlib.import_module(module_path) + callback_cls = getattr(module, class_name) + if not issubclass(callback_cls, RayTrainCallback): + raise TypeError( + f"Callback class '{callback_path}' must be a subclass of " + f"RayTrainCallback, got {type(callback_cls).__name__}" + ) + callback = callback_cls() + callbacks.append(callback) + except (ImportError, AttributeError, ValueError, TypeError) as e: + raise ValueError(f"Failed to import callback from '{callback_path}'") from e + + return callbacks diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/metrics.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..7b510ecd0daf7e02a0ade976ccf24eeea61daba3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/metrics.py @@ -0,0 +1,104 @@ +from contextlib import contextmanager +from typing import Dict, Optional + +import ray +from ray.train.v2._internal.execution.callback import ( + ControllerCallback, + TrainContextCallback, + WorkerCallback, + WorkerGroupCallback, +) +from ray.train.v2._internal.execution.context import TrainRunContext, get_train_context +from ray.train.v2._internal.execution.controller.state import ( + TrainControllerState, + TrainControllerStateType, +) +from ray.train.v2._internal.metrics.base import Metric +from ray.train.v2._internal.metrics.controller import ControllerMetrics +from ray.train.v2._internal.metrics.worker import WorkerMetrics +from ray.train.v2._internal.util import time_monotonic + + +class ControllerMetricsCallback(ControllerCallback, WorkerGroupCallback): + """Callback that records controller-specific metrics.""" + + def after_controller_start(self, train_run_context: TrainRunContext): + """Initialize metrics after controller starts.""" + self._run_name = train_run_context.get_run_config().name + self._run_id = train_run_context.run_id + self._metrics: Dict[str, Metric] = ControllerMetrics.get_controller_metrics( + self._run_name, self._run_id + ) + # Record initial state + self._metrics[ControllerMetrics.CONTROLLER_STATE].record( + TrainControllerStateType.INITIALIZING + ) + + def before_controller_shutdown(self): + """Shutdown metrics before controller shuts down.""" + for metric in self._metrics.values(): + metric.reset() + + def after_controller_state_update( + self, + previous_state: TrainControllerState, + current_state: TrainControllerState, + ): + """Record state transitions after controller state updates.""" + self._metrics[ControllerMetrics.CONTROLLER_STATE].record( + current_state._state_type + ) + + @contextmanager + def on_worker_group_start(self): + """Measure time taken to start worker group.""" + start_time_s = time_monotonic() + yield + elapsed_time_s = time_monotonic() - start_time_s + self._metrics[ControllerMetrics.WORKER_GROUP_START_TOTAL_TIME_S].record( + elapsed_time_s + ) + + @contextmanager + def on_worker_group_shutdown(self): + """Measure time taken to shutdown worker group.""" + start_time_s = time_monotonic() + yield + elapsed_time_s = time_monotonic() - start_time_s + self._metrics[ControllerMetrics.WORKER_GROUP_SHUTDOWN_TOTAL_TIME_S].record( + elapsed_time_s + ) + + +class WorkerMetricsCallback(WorkerCallback, TrainContextCallback): + """Callback that records worker-specific metrics.""" + + def __init__(self, train_run_context: TrainRunContext): + self._run_name = train_run_context.get_run_config().name + self._run_id = train_run_context.run_id + self._metrics: Optional[Dict[str, Metric]] = None + + def after_init_train_context(self): + """Initialize metrics after train context is initialized.""" + train_context = get_train_context() + core_context = ray.runtime_context.get_runtime_context() + world_rank = train_context.get_world_rank() + worker_actor_id = core_context.get_actor_id() + self._metrics = WorkerMetrics.get_worker_metrics( + self._run_name, self._run_id, world_rank, worker_actor_id + ) + + def before_shutdown(self): + """Shutdown metrics before shutdown.""" + for metric in self._metrics.values(): + metric.reset() + + @contextmanager + def on_report(self): + """ + Context manager to measure the time taken to report a checkpoint to the storage. + """ + start_time_s = time_monotonic() + yield + elapsed_time_s = time_monotonic() - start_time_s + self._metrics[WorkerMetrics.REPORT_TOTAL_BLOCKED_TIME_S].record(elapsed_time_s) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/state_manager.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/state_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..ff4aeea3e7693745d3eebf21789a827ef1a08538 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/state_manager.py @@ -0,0 +1,160 @@ +import logging +from typing import Optional + +import ray +from ray.train.v2._internal.execution.callback import ( + ControllerCallback, + WorkerGroupCallback, +) +from ray.train.v2._internal.execution.context import TrainRunContext +from ray.train.v2._internal.execution.controller.state import ( + AbortedState, + ErroredState, + FinishedState, + ResizingState, + RestartingState, + RunningState, + SchedulingState, + TrainControllerState, +) +from ray.train.v2._internal.execution.scaling_policy.scaling_policy import ( + ResizeDecision, +) +from ray.train.v2._internal.execution.worker_group import ( + WorkerGroup, + WorkerGroupContext, + WorkerGroupState, +) +from ray.train.v2._internal.execution.worker_group.poll import WorkerGroupPollStatus +from ray.train.v2._internal.logging.logging import ( + get_train_application_controller_log_path, +) +from ray.train.v2._internal.state.state_manager import TrainStateManager + +logger = logging.getLogger(__name__) + + +class StateManagerCallback(ControllerCallback, WorkerGroupCallback): + def after_controller_start(self, train_run_context: TrainRunContext): + self._state_manager = TrainStateManager() + self._run_name = train_run_context.get_run_config().name + self._run_id = train_run_context.run_id + + # TODO: Should this be generated by the caller? + # NOTE: These must be called on the Controller. + # The Callback is first initialized on the Driver. + core_context = ray.runtime_context.get_runtime_context() + self._job_id = core_context.get_job_id() + self._controller_actor_id = core_context.get_actor_id() + controller_log_file_path = get_train_application_controller_log_path() + self._state_manager.create_train_run( + id=self._run_id, + name=self._run_name, + job_id=self._job_id, + controller_actor_id=self._controller_actor_id, + controller_log_file_path=controller_log_file_path, + ) + + def after_controller_state_update( + self, + previous_state: TrainControllerState, + current_state: TrainControllerState, + ): + if previous_state._state_type == current_state._state_type: + return + + logger.info( + f"[State Transition] {previous_state._state_type.state_name} -> " + f"{current_state._state_type.state_name}." + ) + + if isinstance(current_state, SchedulingState): + # TODO: This should probably always be ResizeDecision. + if isinstance(current_state.scaling_decision, ResizeDecision): + resize_decision = current_state.scaling_decision + else: + resize_decision = None + + self._state_manager.update_train_run_scheduling( + run_id=self._run_id, + resize_decision=resize_decision, + ) + + elif isinstance(current_state, RunningState): + self._state_manager.update_train_run_running( + run_id=self._run_id, + ) + + elif isinstance(current_state, RestartingState): + self._state_manager.update_train_run_restarting( + run_id=self._run_id, + ) + + elif isinstance(current_state, ResizingState): + self._state_manager.update_train_run_resizing( + run_id=self._run_id, + ) + + elif isinstance(current_state, ErroredState): + self._state_manager.update_train_run_errored( + run_id=self._run_id, + status_detail=str(current_state.training_failed_error), + ) + + elif isinstance(current_state, FinishedState): + self._state_manager.update_train_run_finished( + run_id=self._run_id, + ) + + elif isinstance(current_state, AbortedState): + self._state_manager.update_train_run_aborted( + run_id=self._run_id, + ) + + def before_worker_group_start(self, worker_group_context: WorkerGroupContext): + self._state_manager.create_train_run_attempt( + run_id=self._run_id, + attempt_id=worker_group_context.run_attempt_id, + num_workers=worker_group_context.num_workers, + resources_per_worker=worker_group_context.resources_per_worker, + ) + + def after_worker_group_start(self, worker_group: WorkerGroup): + worker_group_context: WorkerGroupContext = ( + worker_group.get_worker_group_context() + ) + worker_group_state: WorkerGroupState = worker_group.get_worker_group_state() + self._state_manager.update_train_run_attempt_running( + run_id=self._run_id, + attempt_id=worker_group_context.run_attempt_id, + workers=worker_group_state.workers, + ) + + def before_worker_group_shutdown(self, worker_group: WorkerGroup): + worker_group_context: WorkerGroupContext = ( + worker_group.get_worker_group_context() + ) + # TODO: Consider passing error reason directly to the callback. + # Something along the lines of: + # WorkerGroup.shutdown(reason) + # -> WorkerGroupCallback.before_worker_group_shutdown(reason) + worker_group_poll_status: Optional[ + WorkerGroupPollStatus + ] = worker_group.get_latest_poll_status() + if worker_group_poll_status and worker_group_poll_status.errors: + self._state_manager.update_train_run_attempt_errored( + run_id=self._run_id, + attempt_id=worker_group_context.run_attempt_id, + status_detail=worker_group_poll_status.get_error_string(), + ) + else: + self._state_manager.update_train_run_attempt_finished( + run_id=self._run_id, + attempt_id=worker_group_context.run_attempt_id, + ) + + def before_worker_group_abort(self, worker_group_context: WorkerGroupContext): + self._state_manager.update_train_run_attempt_aborted( + self._run_id, + worker_group_context.run_attempt_id, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/user_callback.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/user_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..baa4cca39f79cd2ef01f8a2e0ee75d7181678e60 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/user_callback.py @@ -0,0 +1,52 @@ +from typing import Any, Dict, List, Optional + +from ray.train import Checkpoint +from ray.train.v2._internal.execution.callback import ( + ReportCallback, + WorkerGroupCallback, +) +from ray.train.v2._internal.execution.context import TrainRunContext +from ray.train.v2._internal.execution.worker_group import WorkerGroupPollStatus +from ray.train.v2.api.callback import UserCallback + + +class UserCallbackHandler(WorkerGroupCallback, ReportCallback): + """Responsible for calling methods of subscribers implementing + the `UserCallback` interface. + """ + + def __init__( + self, user_callbacks: List[UserCallback], train_run_context: TrainRunContext + ): + self._user_callbacks = user_callbacks + self._train_run_context = train_run_context + + # -------------------------- + # ReportCallback + # -------------------------- + + def after_report( + self, metrics: List[Dict[str, Any]], checkpoint: Optional[Checkpoint] + ): + for user_callback in self._user_callbacks: + user_callback.after_report( + run_context=self._train_run_context, + metrics=metrics, + checkpoint=checkpoint, + ) + + # -------------------------- + # WorkerGroupCallback + # -------------------------- + + def after_worker_group_poll_status( + self, worker_group_status: WorkerGroupPollStatus + ): + if not worker_group_status.errors: + return + + for user_callback in self._user_callbacks: + user_callback.after_exception( + run_context=self._train_run_context, + worker_exceptions=worker_group_status.errors, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/working_dir_setup.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/working_dir_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f43ab2e3094dd54a890aa60b00a7d490ffb7d1ad --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/callbacks/working_dir_setup.py @@ -0,0 +1,24 @@ +import logging +import os + +from ray.train.v2._internal.execution.callback import WorkerGroupCallback +from ray.train.v2._internal.execution.context import get_train_context +from ray.train.v2._internal.execution.worker_group import WorkerGroup + +logger = logging.getLogger(__name__) + + +class WorkingDirectorySetupCallback(WorkerGroupCallback): + def after_worker_group_start(self, worker_group: WorkerGroup): + def chdir_to_working_dir() -> None: + """Create the local working directory for the experiment.""" + local_working_directory = ( + get_train_context().get_storage().local_working_directory + ) + os.makedirs(local_working_directory, exist_ok=True) + logger.debug( + f"Changing the working directory to: {local_working_directory}" + ) + os.chdir(local_working_directory) + + worker_group.execute(chdir_to_working_dir) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/constants.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..9a3dd0cd025cea0335d68214321455a647451701 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/constants.py @@ -0,0 +1,108 @@ +import os +from typing import Dict + +from ray._private.ray_constants import env_bool, env_set_by_user + +# Unsupported configs can use this value to detect if the user has set it. +_UNSUPPORTED = "UNSUPPORTED" +_DEPRECATED = "DEPRECATED" + +# The name of the file that is used to validate the storage. +VALIDATE_STORAGE_MARKER_FILENAME = ".validate_storage_marker" +# The name of the file that is used to store the checkpoint manager snapshot. +CHECKPOINT_MANAGER_SNAPSHOT_FILENAME = "checkpoint_manager_snapshot.json" + + +# ------------------------------------------------------------ +# Environment variables used in the controller and workers. +# +# Be sure to update ENV_VARS_TO_PROPAGATE when adding new +# environment variables in this section. +# ------------------------------------------------------------ + +# Polling interval for the Train controller. +# This determines how many seconds the controller will wait between +# polling the worker group for its status. +HEALTH_CHECK_INTERVAL_S_ENV_VAR = "RAY_TRAIN_HEALTH_CHECK_INTERVAL_S" +DEFAULT_HEALTH_CHECK_INTERVAL_S: float = 2.0 + +# The time in seconds a worker health check must be hanging for +# before the controller marks the worker as dead and handles the failure. +WORKER_HEALTH_CHECK_TIMEOUT_S_ENV_VAR = "RAY_TRAIN_WORKER_HEALTH_CHECK_TIMEOUT_S" +DEFAULT_WORKER_HEALTH_CHECK_TIMEOUT_S: float = 10 * 60 + +# Timeout in seconds for the worker group to start. +WORKER_GROUP_START_TIMEOUT_S_ENV_VAR = "RAY_TRAIN_WORKER_GROUP_START_TIMEOUT_S" +DEFAULT_WORKER_GROUP_START_TIMEOUT_S: float = 30.0 + +# Timeout in seconds for `ray.train.report` to block on synchronization barriers, +# after which a timeout error will be raised. +REPORT_BARRIER_TIMEOUT_S_ENV_VAR = "RAY_TRAIN_REPORT_BARRIER_TIMEOUT_S" +DEFAULT_REPORT_BARRIER_TIMEOUT_S: float = 60 * 30 +# Time in seconds for `ray.train.report` to log a warning if it is waiting for sync +# actor notification of releasing. +REPORT_BARRIER_WARN_INTERVAL_S_ENV_VAR = "RAY_TRAIN_REPORT_BARRIER_WARN_INTERVAL_S" +DEFAULT_REPORT_BARRIER_WARN_INTERVAL_S: float = 60 + +# Environment variable to enable the print function patching. +ENABLE_PRINT_PATCH_ENV_VAR = "RAY_TRAIN_ENABLE_PRINT_PATCH" +DEFAULT_ENABLE_PRINT_PATCH = "1" + +# V2 feature flag. +V2_ENABLED_ENV_VAR = "RAY_TRAIN_V2_ENABLED" + +# Environment variables to enable/disable controller/worker structured logging. +ENABLE_CONTROLLER_STRUCTURED_LOGGING_ENV_VAR = ( + "RAY_TRAIN_ENABLE_CONTROLLER_STRUCTURED_LOGGING" +) +ENABLE_WORKER_STRUCTURED_LOGGING_ENV_VAR = "RAY_TRAIN_ENABLE_WORKER_STRUCTURED_LOGGING" +DEFAULT_ENABLE_CONTROLLER_LOGGING = "1" +DEFAULT_ENABLE_WORKER_LOGGING = "1" + +# Environment variable for Train execution callbacks +RAY_TRAIN_CALLBACKS_ENV_VAR = "RAY_TRAIN_CALLBACKS" + +# Environment variables to propagate from the driver to the controller, +# and then from the controller to the workers. +ENV_VARS_TO_PROPAGATE = { + V2_ENABLED_ENV_VAR, + HEALTH_CHECK_INTERVAL_S_ENV_VAR, + WORKER_HEALTH_CHECK_TIMEOUT_S_ENV_VAR, + WORKER_GROUP_START_TIMEOUT_S_ENV_VAR, + REPORT_BARRIER_TIMEOUT_S_ENV_VAR, + REPORT_BARRIER_WARN_INTERVAL_S_ENV_VAR, + ENABLE_PRINT_PATCH_ENV_VAR, + ENABLE_CONTROLLER_STRUCTURED_LOGGING_ENV_VAR, + ENABLE_WORKER_STRUCTURED_LOGGING_ENV_VAR, +} + + +# ------------------------------------------------------------ +# Environment variables used in the driver script only. +# ------------------------------------------------------------ + +# The environment variable to enable the Ray Train Metrics. +METRICS_ENABLED_ENV_VAR = "RAY_TRAIN_METRICS_ENABLED" + +# Whether or not to run the controller as an actor. +RUN_CONTROLLER_AS_ACTOR_ENV_VAR = "RAY_TRAIN_RUN_CONTROLLER_AS_ACTOR" +DEFAULT_RUN_CONTROLLER_AS_ACTOR = "1" + + +def is_v2_enabled() -> bool: + return env_bool(V2_ENABLED_ENV_VAR, False) + + +def get_env_vars_to_propagate() -> Dict[str, str]: + """Returns a dictionary of environment variables that should be propagated + from the driver to the controller, and then from the controller + to each training worker. + + This way, users only need to set environment variables in one place + when launching the script instead of needing to manually set a runtime environment. + """ + env_vars = {} + for env_var in ENV_VARS_TO_PROPAGATE: + if env_set_by_user(env_var): + env_vars[env_var] = os.environ[env_var] + return env_vars diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/exceptions.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..a3bb2c4ae48ea6f78674e56e05899f2603482c6e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/exceptions.py @@ -0,0 +1,157 @@ +import os +from typing import List, Optional + +from ray.train.v2._internal.constants import ( + DEFAULT_WORKER_GROUP_START_TIMEOUT_S, + DEFAULT_WORKER_HEALTH_CHECK_TIMEOUT_S, + REPORT_BARRIER_TIMEOUT_S_ENV_VAR, + WORKER_GROUP_START_TIMEOUT_S_ENV_VAR, + WORKER_HEALTH_CHECK_TIMEOUT_S_ENV_VAR, +) + + +# TODO: Distinguish between user and system exceptions. +class RayTrainError(Exception): + """Base class for all Ray Train exceptions.""" + + +class WorkerHealthCheckTimeoutError(RayTrainError): + """Exception raised when a worker health check hangs for long enough.""" + + def __init__(self, message): + timeout = os.getenv( + WORKER_HEALTH_CHECK_TIMEOUT_S_ENV_VAR, DEFAULT_WORKER_HEALTH_CHECK_TIMEOUT_S + ) + message += ( + f"\nSet the {WORKER_HEALTH_CHECK_TIMEOUT_S_ENV_VAR} " + "environment variable to increase the timeout " + f"(current value: {timeout} seconds)." + ) + super().__init__(message) + + +class WorkerHealthCheckFailedError(RayTrainError): + """Exception raised when a worker health check fails.""" + + def __init__(self, message, failure: Exception): + super().__init__(message) + self._message = message + self.health_check_failure = failure + + def __reduce__(self): + return (self.__class__, (self._message, self.health_check_failure)) + + def __str__(self): + return self._message + "\n" + str(self.health_check_failure) + + +class WorkerGroupStartupTimeoutError(RayTrainError): + """Exception raised when the worker group startup times out. + + Example scenario: 4 GPUs are detected in the cluster, but when the worker + are actually scheduled, one of the nodes goes down and only 3 GPUs are + available. One of the worker tasks may be stuck pending, until a timeout is reached. + """ + + def __init__(self, num_workers: int): + timeout = float( + os.environ.get( + WORKER_GROUP_START_TIMEOUT_S_ENV_VAR, + DEFAULT_WORKER_GROUP_START_TIMEOUT_S, + ) + ) + self.num_workers = num_workers + super().__init__( + f"The worker group startup timed out after {timeout} seconds waiting " + f"for {num_workers} workers. " + "Potential causes include: " + "(1) temporary insufficient cluster resources while waiting for " + "autoscaling (ignore this warning in this case), " + "(2) infeasible resource request where the provided `ScalingConfig` " + "cannot be satisfied), " + "and (3) transient network issues. " + f"Set the {WORKER_GROUP_START_TIMEOUT_S_ENV_VAR} " + "environment variable to increase the timeout." + ) + + def __reduce__(self): + return (self.__class__, (self.num_workers,)) + + +class WorkerGroupStartupFailedError(RayTrainError): + """Exception raised when the worker group fails to start. + + Example scenario: A worker is scheduled onto a node that dies while + the worker actor is initializing. + """ + + +class CheckpointManagerInitializationError(RayTrainError): + """Exception raised when the checkpoint manager fails to initialize from a snapshot. + + Example scenarios: + 1. The checkpoint manager snapshot version is old and + incompatible with the current version of Ray Train. + 2. The checkpoint manager snapshot JSON file is corrupted. + 3. The checkpoint manager snapshot references checkpoints that cannot be found + in the run storage path. + """ + + +class CollectiveTimeoutError(RayTrainError): + """Exception raised when an internal Ray Train collective operation of + the worker group times out. + """ + + +class BroadcastCollectiveTimeoutError(CollectiveTimeoutError): + """Exception raised when the broadcast operation times out. + + There are two main timeout examples: + 1. If not all workers call `ray.train.report`, the entire worker group will + hang until the timeout before raising. This prevents indefinite worker + group hangs. + 2. If a worker is slow in the training loop and fails to reach the broadcast + time, the collective will time out. + """ + + def __init__( + self, time_elapsed: Optional[float], missing_ranks: List[int], timeout_s: float + ): + self._time_elapsed = time_elapsed + self._missing_ranks = missing_ranks + self._timeout_s = timeout_s + + message = ( + f"The broadcast operation timed out after {time_elapsed:.2f} seconds. " + "Please make sure all worker ranks call `ray.train.report`. \n" + f"The following ranks have not called it: {missing_ranks}\n" + f"You can set this timeout with the {REPORT_BARRIER_TIMEOUT_S_ENV_VAR} " + f"environment variable (current value: {timeout_s:.2f} s)." + ) + super().__init__(message) + + def __reduce__(self): + return ( + self.__class__, + (self._time_elapsed, self._missing_ranks, self._timeout_s), + ) + + +class UserExceptionWithTraceback(RayTrainError): + """This class wraps a user code exception raised on the worker + with its original traceback string, for logging and debugging purposes. + + This is needed because the original exception traceback is not serialized + with the exception when it is *returned* back to the main process. + """ + + def __init__(self, exc: BaseException, traceback_str: str): + self._base_exc = exc + self._traceback_str = traceback_str + + def __reduce__(self): + return (self.__class__, (self._base_exc, self._traceback_str)) + + def __str__(self): + return self._traceback_str diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e567062e98507dac9fb34c28537ec4383f412986 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/callback.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/callback.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4018ccceda67edca0ae455e5dcb058f7bb6a470 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/callback.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/context.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0600db7375b067c4aa27caf98bb3f342a44ccac3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/context.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/storage.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/storage.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4021662800973e7c6f6e1821d373d1f7beb6631b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/__pycache__/storage.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/callback.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..50796a0700c84f4f89bc27c1979a810c542a3b6d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/callback.py @@ -0,0 +1,162 @@ +from contextlib import contextmanager +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +from ray.train.v2.api.callback import RayTrainCallback +from ray.train.v2.api.result import Result +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + from ray.train import Checkpoint + from ray.train.v2._internal.execution.context import TrainRunContext + from ray.train.v2._internal.execution.controller import ( + TrainControllerState, + ) + from ray.train.v2._internal.execution.failure_handling import FailureDecision + from ray.train.v2._internal.execution.scaling_policy import ResizeDecision + from ray.train.v2._internal.execution.worker_group import ( + Worker, + WorkerGroup, + WorkerGroupContext, + WorkerGroupPollStatus, + ) + + +@DeveloperAPI +class WorkerGroupCallback(RayTrainCallback): + def before_init_train_context( + self, workers: List["Worker"] + ) -> Dict[str, List[Any]]: + """Called before initializing the TrainContext for the worker_group. + + Return: + A dictionary of additional arguments for TrainContext. + The key is the argument name and the value is a list of argument values + to pass to the TrainContext constructor of each worker in the worker group. + """ + return {} + + @contextmanager + def on_worker_group_start(self): + yield + + def before_worker_group_start(self, worker_group_context: "WorkerGroupContext"): + """Called before the worker group actors are initialized.""" + pass + + def after_worker_group_start(self, worker_group: "WorkerGroup"): + """Called after the worker group actors are initialized. + All workers should be ready to execute tasks.""" + pass + + def after_worker_group_training_start(self, worker_group: "WorkerGroup"): + pass + + @contextmanager + def on_worker_group_shutdown(self): + yield + + def before_worker_group_shutdown(self, worker_group: "WorkerGroup"): + """Called before the worker group is shut down. + Workers may be dead at this point due to actor failures, so this method + should catch and handle exceptions if attempting to execute tasks.""" + pass + + def after_worker_group_poll_status( + self, worker_group_status: "WorkerGroupPollStatus" + ): + pass + + def before_worker_group_abort(self, worker_group_context: "WorkerGroupContext"): + """Called before the worker group is aborted.""" + pass + + +@DeveloperAPI +class ControllerCallback(RayTrainCallback): + def after_controller_start(self, train_run_context: "TrainRunContext"): + """Called immediately after `TrainController.run` is called, + before the control loop starts executing.""" + pass + + def before_controller_shutdown(self): + """Called before `TrainController.run` exits, + after the control loop has exited.""" + pass + + def after_controller_state_update( + self, + previous_state: "TrainControllerState", + current_state: "TrainControllerState", + ): + """Called whenever the controller state is updated.""" + pass + + def before_controller_execute_failure_decision( + self, + failure_decision: "FailureDecision", + ): + """Called before the controller executes a failure decision.""" + pass + + def before_controller_execute_resize_decision( + self, + resize_decision: "ResizeDecision", + ): + """Called before the controller executes a resize decision.""" + pass + + def after_controller_finish(self, result: Result): + """Called after the training run completes, providing access to the final result. + + Args: + result: The final training result containing metrics and checkpoint. + """ + pass + + +@DeveloperAPI +class ReportCallback(RayTrainCallback): + def after_report( + self, metrics: List[Dict[str, Any]], checkpoint: Optional["Checkpoint"] + ): + """Called after all workers have reported a training result. + + Note that this differs from `after_worker_group_poll_status`, + which may only contain a subset of workers that have reported. + For example, if only rank 0 is performing checkpointing, then + rank 0 would report a training result the slowest. + """ + pass + + +@DeveloperAPI +class WorkerCallback(RayTrainCallback): + """ + Callbacks that are hooked to the worker event. + + These callbacks are created on the train driver process and then + copied and passed to all the workers. + The execution of these callbacks happens on each of the workers, + not on the train driver process. + """ + + def after_init_train_context(self): + pass + + def before_worker_shutdown(self): + pass + + +@DeveloperAPI +class TrainContextCallback(RayTrainCallback): + """ + Callbacks that are hooked to the train context event. + + These callbacks are created on the train driver process and then + copied and passed to all the workers. + The execution of these callbacks happens on the train context of the workers. + """ + + @contextmanager + def on_report(self): + yield diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb9ceb99da9b7c6cb1e73f8c6568b42a6a12e520 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/checkpoint_manager.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/checkpoint_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70d4f861dffcb373c4f490cc7d5c56eebffad2db Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/checkpoint_manager.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/report_handler.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/report_handler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18d556c0e5df56e7e856fc0bb162f71affb417ba Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/report_handler.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/sync_actor.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/sync_actor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a6cd4b7e2943b1551f8dd1e596886e239d9a6e1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/__pycache__/sync_actor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/checkpoint_manager.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/checkpoint_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..a241ce43619db60e8fab3fab8d59954bd89b9f9b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/checkpoint_manager.py @@ -0,0 +1,287 @@ +import logging +from typing import Any, Dict, List, Optional + +from ray.air.config import CheckpointConfig +from ray.train._checkpoint import Checkpoint +from ray.train._internal.checkpoint_manager import ( + _CheckpointManager, + _insert_into_sorted_list, +) +from ray.train._internal.session import _TrainingResult +from ray.train.v2._internal.exceptions import CheckpointManagerInitializationError +from ray.train.v2._internal.execution.callback import ( + ReportCallback, + WorkerGroupCallback, +) +from ray.train.v2._internal.execution.context import StorageContext +from ray.train.v2._internal.execution.storage import _delete_fs_path, _exists_at_fs_path +from ray.train.v2._internal.execution.worker_group import Worker + +try: + from pydantic import BaseModel + from pydantic_core import from_json +except (ImportError, ModuleNotFoundError) as exc: + raise ImportError( + "`ray.train.v2` requires the pydantic package, which is missing. " + "Run the following command to fix this: `pip install pydantic`" + ) from exc + + +logger = logging.getLogger(__name__) + + +class _TrainingResultState(BaseModel): + # Increment version if the schema changes + version: int = 0 + checkpoint_dir_name: str + metrics: dict + + +class _CheckpointManagerState(BaseModel): + # Increment version if the schema changes + version: int = 0 + checkpoint_results: List[_TrainingResultState] + latest_checkpoint_result: Optional[_TrainingResultState] + + +def _get_training_result_from_state( + state: _TrainingResultState, + storage_context: StorageContext, +) -> _TrainingResult: + """Get a TrainingResult object from a Pydantic state object.""" + return _TrainingResult( + checkpoint=Checkpoint( + path=storage_context.build_checkpoint_path_from_name( + state.checkpoint_dir_name + ), + filesystem=storage_context.storage_filesystem, + ), + metrics=state.metrics, + ) + + +def _get_state_from_training_result( + training_result: _TrainingResult, + storage_context: StorageContext, +) -> _TrainingResultState: + """Get a Pydantic state object from a TrainingResult object.""" + return _TrainingResultState( + checkpoint_dir_name=storage_context.extract_checkpoint_dir_name_from_path( + training_result.checkpoint.path + ), + metrics=training_result.metrics, + ) + + +class CheckpointManager(_CheckpointManager, ReportCallback, WorkerGroupCallback): + def __init__( + self, + checkpoint_config: CheckpointConfig, + storage_context: StorageContext, + ): + self._storage_context = storage_context + self._checkpoint_config = checkpoint_config + super().__init__(checkpoint_config) + # If the snapshot is found, the checkpoint manager will restore its state. + self._maybe_load_state_from_storage() + + def register_checkpoint(self, checkpoint_result: _TrainingResult): + """Register new checkpoint and add to bookkeeping. + + This method will register a new checkpoint and add it to the internal + bookkeeping logic. This means the checkpoint manager will decide if + this checkpoint should be kept, and if older or worse performing + checkpoints should be deleted. + + Args: + checkpoint: Tracked checkpoint object to add to bookkeeping. + """ + self._latest_checkpoint_result = checkpoint_result + + if self._checkpoint_config.checkpoint_score_attribute is not None: + # If we're ordering by a score, insert the checkpoint + # so that the list remains sorted. + _insert_into_sorted_list( + self._checkpoint_results, + checkpoint_result, + key=self._get_checkpoint_score, + ) + else: + # If no metric is provided, just append (ordering by time of registration). + self._checkpoint_results.append(checkpoint_result) + + results_to_delete = {} + if self._checkpoint_config.num_to_keep is not None: + # Delete the bottom (N - K) checkpoints + worst_results = set( + self._checkpoint_results[: -self._checkpoint_config.num_to_keep] + ) + # Except for the latest checkpoint. + results_to_delete = worst_results - {self._latest_checkpoint_result} + + # Update internal state before actually deleting them. + self._checkpoint_results = [ + checkpoint_result + for checkpoint_result in self._checkpoint_results + if checkpoint_result not in results_to_delete + ] + + # Save the checkpoint manager state to storage. + # Note: We save the state before deleting the old checkpoints. + # If deletion happens first and the process crashes, our snapshot + # may point to some stale checkpoints that are already deleted. + # TODO: Make this writing operation non-blocking. + self._write_state_to_storage() + + # Delete the old checkpoints. + for checkpoint_result in results_to_delete: + checkpoint = checkpoint_result.checkpoint + logger.debug("Deleting checkpoint: ", checkpoint) + _delete_fs_path(fs=checkpoint.filesystem, fs_path=checkpoint.path) + + # -------------------------- + # CheckpointManager state + # -------------------------- + + def _save_state(self) -> str: + """Save the checkpoint manager state to a JSON str.""" + + checkpoint_results = [ + _get_state_from_training_result(checkpoint_result, self._storage_context) + for checkpoint_result in self._checkpoint_results + ] + + latest_checkpoint_result = ( + _get_state_from_training_result( + self._latest_checkpoint_result, self._storage_context + ) + if self._latest_checkpoint_result is not None + else None + ) + + manager_snapshot = _CheckpointManagerState( + checkpoint_results=checkpoint_results, + latest_checkpoint_result=latest_checkpoint_result, + ) + return manager_snapshot.model_dump_json() + + def _load_state(self, json_state: str): + """Load the checkpoint manager state from a JSON str.""" + try: + manager_snapshot = _CheckpointManagerState.model_validate( + from_json(json_state) + ) + except Exception as e: + raise CheckpointManagerInitializationError(repr(e)) from e + self._assert_checkpoints_exist() + + self._checkpoint_results = [ + _get_training_result_from_state( + training_result_state, self._storage_context + ) + for training_result_state in manager_snapshot.checkpoint_results + ] + + self._latest_checkpoint_result = ( + _get_training_result_from_state( + manager_snapshot.latest_checkpoint_result, self._storage_context + ) + if manager_snapshot.latest_checkpoint_result is not None + else None + ) + + def _maybe_load_state_from_storage(self): + """Load the checkpoint manager state from storage. + If no snapshot is found, start with a clean state. + """ + if not _exists_at_fs_path( + fs=self._storage_context.storage_filesystem, + fs_path=self._storage_context.checkpoint_manager_snapshot_path, + ): + logger.debug( + "No checkpoint manager snapshot found. " + "No checkpoint will be available via `ray.train.get_checkpoint`, " + "so training will start from scratch." + ) + return + with self._storage_context.storage_filesystem.open_input_stream( + self._storage_context.checkpoint_manager_snapshot_path + ) as f: + logger.info( + "A run snapshot was found in storage folder at: " + f"'{self._storage_context.experiment_fs_path}'\n" + "This snapshot contains a list of checkpoints reported via " + "`ray.train.report` and will be loaded. " + "This allows the latest checkpoint found in the snapshot to be " + "accessible within your training function via " + "`ray.train.get_checkpoint`.\n" + "If you meant to start a brand new training job without any " + "information about previous checkpoints found in this directory, " + "please configure a new, unique `RunConfig(name)` or delete the " + f"existing folder at '{self._storage_context.experiment_fs_path}'." + ) + json_state = f.read().decode("utf-8") + self._load_state(json_state) + + def _write_state_to_storage(self): + """Write the checkpoint manager state to storage.""" + checkpoint_manager_snapshot = self._save_state() + with self._storage_context.storage_filesystem.open_output_stream( + self._storage_context.checkpoint_manager_snapshot_path + ) as f: + f.write(checkpoint_manager_snapshot.encode("utf-8")) + + def _assert_checkpoints_exist(self): + """Validate the checkpoint manager state. + + This method will validate the checkpoint manager state by checking if + the checkpoints specified in manager snapshot is compatible with the + checkpoint folders of the experiment storage filesystem. + + Raises: + CheckpointManagerInitializationError: If the checkpoint manager snapshot + is not consistent with the stored checkpoints. + """ + for checkpoint_result in self._checkpoint_results: + checkpoint = checkpoint_result.checkpoint + assert checkpoint is not None + if not _exists_at_fs_path( + fs=checkpoint.filesystem, fs_path=checkpoint.path + ): + raise CheckpointManagerInitializationError( + message=( + "The run snapshot contains a reference to a checkpoint " + f"that does not exist anymore ({checkpoint}). You are " + "running in a corrupted run directory `experiment_fs_path`." + "Please configure a new, unique `RunConfig(name)` " + "or delete the existing folder at " + f"`{self._storage_context.experiment_fs_path}`." + ) + ) + + # -------------------------- + # ReportCallback + # -------------------------- + + def after_report( + self, metrics: List[Dict[str, Any]], checkpoint: Optional[Checkpoint] + ): + if not checkpoint: + return + + rank_0_metrics = metrics[0] + self.register_checkpoint( + _TrainingResult(checkpoint=checkpoint, metrics=rank_0_metrics) + ) + + # -------------------------- + # WorkerGroupCallback + # -------------------------- + + def before_init_train_context(self, workers: List[Worker]) -> Dict[str, List[Any]]: + latest_checkpoint = ( + self.latest_checkpoint_result.checkpoint + if self.latest_checkpoint_result + else None + ) + return {"checkpoint": [latest_checkpoint] * len(workers)} diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/report_handler.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/report_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..47ac5dd9c2eafc13d2d537da284ca558b8c2092d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/report_handler.py @@ -0,0 +1,114 @@ +from collections import deque +from typing import TYPE_CHECKING, Deque, List, Optional + +from ray.train.v2._internal.execution.callback import ( + ReportCallback, + WorkerGroupCallback, +) +from ray.train.v2._internal.execution.worker_group import ( + WorkerGroup, + WorkerGroupPollStatus, +) + +if TYPE_CHECKING: + from ray.train._internal.session import _TrainingResult + + +class ReportCallbackHandler(WorkerGroupCallback): + """Consolidate training results from multiple workers and call + subscribers implementing the `ReportCallback` interface sequentially. + """ + + def __init__(self, report_callbacks: List[ReportCallback]): + # Number of workers in the current worker group. It is initialized + # to be None. It is set to the number of workers when it receives the + # worker group status for the first time. + # When a worker group shutdown, self._num_workers is set to None, + # waiting to be updated when a new worker group status is received again. + self._num_workers: Optional[int] = None + # A list of queues holding training results from workers. + self._training_result_queues: Optional[List[Deque[_TrainingResult]]] = None + + self._report_callbacks = report_callbacks + + # -------------------------- + # WorkerGroupCallback + # -------------------------- + + def after_worker_group_poll_status( + self, worker_group_status: WorkerGroupPollStatus + ) -> None: + """Handle training results as they roll in from worker status polls. + + Wait for all workers to report training results to collect + a consolidated training result. + """ + # Step 1: If self._num_workers is None, we need to initialize the number + # of workers and training_results_queues from the worker group status. This + # happens when the handler receives the worker group status for the first time. + assert ( + self._num_workers and self._training_result_queues + ), "Need to call initialize state with `after_worker_group_start` first." + + assert self._num_workers == len(worker_group_status.worker_statuses), ( + f"The number of workers in the worker group has changed unexpectedly. " + f"Expected: {self._num_workers}, got: {len(worker_group_status.worker_statuses)}" + ) + + # Step 2: Update training_results_queues with poll_results. + for i in range(self._num_workers): + training_result = worker_group_status.worker_statuses[i].training_result + if training_result: + self._training_result_queues[i].append(training_result) + + # Directly return if any of the worker result queues are empty. + if not all(self._training_result_queues): + return + + training_results = [q.popleft() for q in self._training_result_queues] + + # Step 3: Consolidate a list of checkpoints to single checkpoint. + # Use the first checkpoint as the consolidated checkpoint. + checkpoint_results = [ + tr for tr in training_results if tr.checkpoint is not None + ] + + consolidated_checkpoint = None + if checkpoint_results: + # Double check the storage path of the checkpoints in the training results. + unique_checkpoint_paths = {tr.checkpoint.path for tr in checkpoint_results} + if len(unique_checkpoint_paths) > 1: + # TODO: Support for inconsistent checkpoints path from workers + # instead of hard raising error. Maybe drop this iteration of + # training results and continue with the next iteration. + raise RuntimeError( + "The storage path of the checkpoints in the training results " + "is not the same. This means the checkpoints are not consistent." + "Got a mix of the following checkpoint paths: " + f"{unique_checkpoint_paths}\n" + "This is unexpected -- please file a Github issue." + ) + consolidated_checkpoint = checkpoint_results[0].checkpoint + + # Step 4: Invoke all dependent `ReportCallback`s. + metrics_per_worker = [ + training_result.metrics for training_result in training_results + ] + for callback in self._report_callbacks: + callback.after_report( + metrics=metrics_per_worker, + checkpoint=consolidated_checkpoint, + ) + + def after_worker_group_start(self, worker_group: WorkerGroup) -> None: + """Handle worker group start. Initialize internal states.""" + self._num_workers = len(worker_group) + self._training_result_queues = [deque() for _ in range(self._num_workers)] + + def before_worker_group_shutdown(self, worker_group: WorkerGroup) -> None: + """Handle worker group shutdown. Clear internal states. + + None of the partial reported results are valid at this point. + """ + self._num_workers = None + self._training_result_queues = None diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/sync_actor.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/sync_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..ee26ad967da7a356078766544eb18f2234af77d0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/checkpoint/sync_actor.py @@ -0,0 +1,203 @@ +import asyncio +import logging +from contextlib import contextmanager +from typing import List, Optional, TypeVar + +import ray +from ray.train.v2._internal.constants import ( + DEFAULT_REPORT_BARRIER_TIMEOUT_S, + DEFAULT_REPORT_BARRIER_WARN_INTERVAL_S, + REPORT_BARRIER_WARN_INTERVAL_S_ENV_VAR, +) +from ray.train.v2._internal.exceptions import BroadcastCollectiveTimeoutError + +T = TypeVar("T", bound=Optional[object]) +logger = logging.getLogger(__name__) + + +BROADCAST_PERIODIC_WARNING = """ +`{caller_method_name}` has not been called by all {world_size} workers in the group. +The workers have been waiting for {max_time_elapsed_s:.2f} s for the following ranks to join the `{caller_method_name}` call: {missing_ranks}. +Also ensure that workers are not hanging on other operations, causing them to miss this synchronization barrier. +You can set the {warn_interval_env_var} environment variable to change the frequency of this warning (current value: {warn_interval_s} s). +""" + + +@ray.remote(num_cpus=0) # type: ignore +class SynchronizationActor: + """A Ray actor that synchronizes the workers in a distributed training job. + + This actor forms a synchronization barrier on a group of processes. + Every time a worker calls the broadcast_from_rank_zero method, + the counter is incremented. When the counter equals to the world size, + the actor notifies all the workers to continue. + """ + + def __init__( + self, + timeout_s: float = DEFAULT_REPORT_BARRIER_TIMEOUT_S, + warn_interval_s: float = DEFAULT_REPORT_BARRIER_WARN_INTERVAL_S, + ): + self._counter: int = 0 + self._world_size: int = 0 + self._condition = asyncio.Condition() + self._reduced_data = None + # The time when workers from different ranks + # enters the synchronization barrier. + self._sync_start_times: List[Optional[float]] = [] + # The timeout in seconds for the synchronization barrier. + self._timeout_s: float = timeout_s + # The interval in seconds to log a warning when waiting for the barrier. + self._warn_interval_s: float = warn_interval_s + + def get_counter(self): + """Returns the current value of the counter.""" + return self._counter + + def get_world_size(self): + """Returns the current value of the world_size.""" + return self._world_size + + def get_reduced_data(self): + """Returns the current value of the reduced_data.""" + return self._reduced_data + + def _clear_states(self): + """Clears the states of the actor. When the last worker has + called the _clear_states method, the actor clears its states + """ + self._counter -= 1 + if self._counter == 0: + self._reduced_data = None + self._world_size = 0 + + def _setup_or_validate_collective_op(self, world_size: int): + """The setup method for the synchronization actor if it is not setup yet. + It initializes the world size and the start times for the + synchronization barrier. + """ + if self._world_size == 0: + self._world_size = world_size + self._sync_start_times = [None] * world_size + elif world_size != self._world_size: + raise ValueError( + f"Expected all callers to provide the same world size. \ + Got {world_size} and expected {self._world_size}." + ) + + @contextmanager + def _broadcast_collective_context_manager( + self, world_rank: int, world_size: int, data: T + ): + """A context manager that ensures the synchronization barrier is lifted + after the block of code is executed. + """ + try: + self._setup_or_validate_collective_op(world_size) + if world_rank == 0: + self._reduced_data = data + if self._counter < self._world_size: + self._counter += 1 + yield + finally: + self._clear_states() + + def _get_time_elapsed(self) -> Optional[float]: + """Return the time elapsed since the first worker entered the barrier. + If no workers have entered the barrier, returns None. + """ + start_times = [t for t in self._sync_start_times if t is not None] + if not start_times: + return None + + return asyncio.get_event_loop().time() - min(start_times) + + def _get_missing_ranks(self) -> List[int]: + """Returns the ranks that have not entered the synchronization barrier.""" + return [i for i, t in enumerate(self._sync_start_times) if t is None] + + async def _wait_with_logging( + self, condition, world_rank: int, caller_method_name: str + ): + """Waits for the condition to be notified, logging an warning every + `log_interval` seconds, and raises a timeout error if `timeout` is reached. + """ + current_time = asyncio.get_event_loop().time() + self._sync_start_times[world_rank] = current_time + while True: + try: + await asyncio.wait_for(condition.wait(), timeout=self._warn_interval_s) + return + # asyncio.wait_for() raises `asyncio.TimeoutError` for asyncio<=3.10 + # and raises `TimeoutError` for asyncio>=3.11 + # https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for + # TODO: (hpguo) Make only one worker log the warning message. + except (asyncio.TimeoutError, TimeoutError): + logger.warning( + BROADCAST_PERIODIC_WARNING.format( + caller_method_name=caller_method_name, + world_size=self._world_size, + max_time_elapsed_s=self._get_time_elapsed(), + missing_ranks=self._get_missing_ranks(), + warn_interval_env_var=REPORT_BARRIER_WARN_INTERVAL_S_ENV_VAR, + warn_interval_s=self._warn_interval_s, + ), + ) + + async def broadcast_from_rank_zero( + self, + world_rank: int, + world_size: int, + data: T, + caller_method_name: str, + ) -> T: + """Broadcasts a data from the worker with rank 0 to all other workers. + + This method is a coroutine that blocks until all workers have called this + method with the their data. The data from the worker with rank 0 will + be returned. + + Args: + world_rank: The rank of the worker that calls this method. + world_size: The total number of workers in the group. + data: The data to broadcast. + caller_method_name: The name of the method that calls this method. + + Returns: + The data broadcasted from the worker with rank 0. + """ + # TODO: resolve https://github.com/ray-project/ray/pull/54066#discussion_r2180657435 + # We couldn't reproduce the issue but the asyncio docs don't say it can't happen. + + # Ensures that all global states manipulation is done within the async context + # manager which makes the condition variable awaiting and the counter + # incrementing an atomic operation. + async with self._condition: + with self._broadcast_collective_context_manager( + world_rank, world_size, data + ): + # If the counter is equal to the world size, it means the last worker + # has called the broadcast_from_rank_zero method. The actor notifies + # all the workers to continue. + if self._counter == self._world_size: + self._condition.notify_all() + return self._reduced_data + # If the counter is less than the world size, the actor waits for the + # other workers to call the broadcast_from_rank_zero method. + try: + await asyncio.wait_for( + self._wait_with_logging( + self._condition, world_rank, caller_method_name + ), + timeout=self._timeout_s, + ) + return self._reduced_data + except (asyncio.TimeoutError, TimeoutError) as e: + raise BroadcastCollectiveTimeoutError( + time_elapsed=self._get_time_elapsed(), + missing_ranks=self._get_missing_ranks(), + timeout_s=self._timeout_s, + ) from e + + # TODO: Implement a general consensus_from_votes method that takes a callable + # reduce_fn and a list of votes from each worker. The method returns the consensus diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/context.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/context.py new file mode 100644 index 0000000000000000000000000000000000000000..cf76ec4f84844eadf5b364a0d5478c11684e6ece --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/context.py @@ -0,0 +1,289 @@ +import logging +import sys +import threading +import uuid +from dataclasses import dataclass, field +from queue import Queue +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +import ray +from ray.data import DataIterator, Dataset +from ray.train import BackendConfig, Checkpoint, DataConfig +from ray.train._internal import session +from ray.train._internal.session import _TrainingResult +from ray.train.v2._internal.execution.checkpoint.sync_actor import SynchronizationActor +from ray.train.v2._internal.execution.storage import StorageContext +from ray.train.v2._internal.util import _copy_doc, invoke_context_managers +from ray.train.v2.api.config import RunConfig, ScalingConfig + +if TYPE_CHECKING: + from ray.train.v2._internal.execution.callback import TrainContextCallback + from ray.train.v2._internal.execution.worker_group.thread_runner import ThreadRunner + + +logger = logging.getLogger(__file__) + + +@dataclass(frozen=True) +class TrainRunContext: + """Holds the metadata and context for the current training run.""" + + # The unique ID of the training run. + run_id: str = field(init=False, default_factory=lambda: uuid.uuid4().hex) + + # The run configuration for the current training run. + run_config: RunConfig + + # The configuration passed to the training function. + train_loop_config: Optional[Dict[str, Any]] + + # The scaling configuration for the current training run. + scaling_config: ScalingConfig + + # The configuration for the training backend (e.g., PyTorch, XGBoost). + backend_config: BackendConfig + + # The datasets used in the current training run. + datasets: Dict[str, Dataset] + + # The configuration for dataset ingestion and sharding. + dataset_config: DataConfig + + def get_run_config(self) -> RunConfig: + """Returns the run config of the current training run.""" + return self.run_config + + +@dataclass(frozen=True) +class DistributedContext: + world_rank: int + world_size: int + local_rank: int + local_world_size: int + node_rank: int + + +@dataclass(frozen=True) +class ExecutionContext: + """Holds the execution context for the current worker process. + + Every worker process has a single execution context accessed via the + `TrainContext`, which includes the training thread that is actually + running the user code. + """ + + # A shared synchronization actor that helps broadcast data across ranks. + synchronization_actor: SynchronizationActor + + # A queue that receives training results from the user training code. + # `ray.train.report` in user code populates this queue. + result_queue: Queue + + # The thread launcher that runs the user training loop. + training_thread_runner: "ThreadRunner" + + # The callbacks that are run in the worker train context. + train_context_callbacks: List["TrainContextCallback"] + + +@dataclass +class TrainContext: + train_run_context: TrainRunContext + distributed_context: DistributedContext + execution_context: ExecutionContext + storage_context: StorageContext + dataset_shards: Dict[str, DataIterator] + checkpoint: Optional[Checkpoint] = None + + @_copy_doc(session.get_experiment_name) + def get_experiment_name(self) -> str: + return self.train_run_context.run_config.name + + @_copy_doc(session.get_world_size) + def get_world_size(self) -> int: + return self.distributed_context.world_size + + @_copy_doc(session.get_world_rank) + def get_world_rank(self) -> int: + return self.distributed_context.world_rank + + @_copy_doc(session.get_local_rank) + def get_local_rank(self) -> int: + return self.distributed_context.local_rank + + @_copy_doc(session.get_local_world_size) + def get_local_world_size(self) -> int: + return self.distributed_context.local_world_size + + @_copy_doc(session.get_node_rank) + def get_node_rank(self) -> int: + return self.distributed_context.node_rank + + @_copy_doc(session.get_storage) + def get_storage(self): + return self.storage_context + + # TODO: Don't allow these private methods to be called from user code. + def get_result_queue(self): + return self.execution_context.result_queue + + def get_synchronization_actor(self): + return self.execution_context.synchronization_actor + + def get_checkpoint(self): + return self.checkpoint + + def get_dataset_shard(self, dataset_name: str) -> DataIterator: + """Returns the :class:`ray.data.DataIterator` shard for this worker. + + Call :meth:`~ray.data.DataIterator.iter_torch_batches` or + :meth:`~ray.data.DataIterator.to_tf` on this shard to convert it to the + appropriate framework-specific data type. + + Args: + dataset_name: Name of the dataset shard. + Returns: + The ``DataIterator`` shard with the given name for this worker. + Raises: + KeyError: If the dataset shard with the given name is not found. + """ + try: + return self.dataset_shards[dataset_name] + except KeyError: + raise KeyError( + f"Dataset {dataset_name} not found. Available datasets: " + f"{list(self.dataset_shards.keys())}." + ) + + def get_context_callbacks(self) -> List["TrainContextCallback"]: + return self.execution_context.train_context_callbacks + + def _sync_checkpoint_dir_name_across_ranks( + self, checkpoint_dir_name: Optional[str] = None + ) -> str: + """Sync the checkpoint dir name across ranks. + + Args: + checkpoint_dir_name: The checkpoint dir name to sync. + + Returns: + The synced checkpoint dir name. + """ + # If checkpoint_dir_name is not set, use default checkpoint_dir_name + # created by the storage context. + checkpoint_dir_name = ( + checkpoint_dir_name + or self.storage_context.make_default_checkpoint_dir_name() + ) + # Get a consensus across ranks on the remote storage path, so distributed + # checkpoints will be stored to the same place. + sync_actor = self.get_synchronization_actor() + return ray.get( + sync_actor.broadcast_from_rank_zero.remote( + world_rank=self.distributed_context.world_rank, + world_size=self.distributed_context.world_size, + data=checkpoint_dir_name, + caller_method_name="ray.train.report", + ) + ) + + def _save_checkpoint( + self, + checkpoint_dir_name: str, + metrics: Dict[str, Any], + checkpoint: Optional[Checkpoint] = None, + ) -> _TrainingResult: + """Save the checkpoint to remote storage. + + Returns: + The training result object containing the persisted checkpoint. + """ + + if not checkpoint: + return _TrainingResult(checkpoint=None, metrics=metrics) + + # Persist the checkpoint to the remote storage path. + persisted_checkpoint = self.storage_context.persist_current_checkpoint( + checkpoint, checkpoint_dir_name + ) + # Update latest checkpoint as the persisted checkpoint. + self.checkpoint = persisted_checkpoint + + return _TrainingResult(checkpoint=persisted_checkpoint, metrics=metrics) + + def report( + self, + metrics: Dict[str, Any], + checkpoint: Optional[Checkpoint] = None, + checkpoint_dir_name: Optional[str] = None, + ): + """ + Upload checkpoint to remote storage and put a training + result on the result queue of this worker process. + + Args: + metrics: The metrics to report. + checkpoint: The checkpoint to report. + checkpoint_dir_name: The name of the checkpoint dir + in this iteration. Note: If not set, the checkpoint will + be stored in the default storage path. If set, make sure + this value is unique for each iteration. + + TODO: the report function should be implemented in the worker instead + of in the train context. The train context should only keep the train + related information and not the worker related actions. This refactor + would also require the `TrainContextCallback` to be updated as well. + """ + if "torch" in sys.modules: + from ray.air._internal.torch_utils import contains_tensor + + if contains_tensor(metrics): + raise ValueError( + "Passing objects containg Torch tensors as metrics " + "is not supported as it will throw an exception on " + "deserialization. You can either convert the tensors " + "to Python objects (ex: `.numpy()`, `.item()`, etc.) " + "or save tensors as part of the checkpoint files instead." + ) + + with invoke_context_managers( + [ + callback.on_report + for callback in self.execution_context.train_context_callbacks + ] + ): + # Step 1: sync the checkpoint dir name across ranks. + checkpoint_dir_name = self._sync_checkpoint_dir_name_across_ranks( + checkpoint_dir_name + ) + # Step 2: save the checkpoint to remote storage. + training_result = self._save_checkpoint( + checkpoint_dir_name, metrics, checkpoint + ) + # Step 3: Report the training result to the result queue. + # The queue size is set to 1 to avoid accumulating unprocessed results. + # If the queue is full, the put operation blocks until a result is consumed. + + # TODO (hpguo): Add a metrics to track the blocking time waiting for the + # training result to be consumed by the controller. + self.get_result_queue().put(training_result) + + +# The global variable holding the current TrainContext +_train_context: Optional[TrainContext] = None + +# Thread lock to protect the global TrainContext +_context_lock = threading.Lock() + + +def get_train_context() -> TrainContext: + with _context_lock: + if _train_context is None: + raise RuntimeError("TrainContext has not been initialized.") + return _train_context + + +def set_train_context(context) -> None: + global _train_context + with _context_lock: + _train_context = context diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f28117ecf45e4c49f8cae9bb646e064dfc5aacc7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__init__.py @@ -0,0 +1,3 @@ +from .controller import TrainController + +__all__ = ["TrainController"] diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2408f9853469f416373f05a423d18f76640f3659 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__pycache__/controller.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__pycache__/controller.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a9941944d5757faaac672f934af850946412c32 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__pycache__/controller.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__pycache__/state.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__pycache__/state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d4c2d51ecea0780a7742481407926eda5e9e067 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/__pycache__/state.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/controller.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..f26f65c755fc5984046654bcbe3bd4468d6c9b9a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/controller.py @@ -0,0 +1,540 @@ +import asyncio +import logging +import os +import uuid +from dataclasses import dataclass +from typing import Callable, List, Optional + +import pandas as pd + +import ray +import ray._private.ray_constants as ray_constants +from ray.train.v2._internal.constants import ( + DEFAULT_ENABLE_CONTROLLER_LOGGING, + DEFAULT_HEALTH_CHECK_INTERVAL_S, + ENABLE_CONTROLLER_STRUCTURED_LOGGING_ENV_VAR, + HEALTH_CHECK_INTERVAL_S_ENV_VAR, +) +from ray.train.v2._internal.exceptions import ( + WorkerGroupStartupFailedError, + WorkerGroupStartupTimeoutError, +) +from ray.train.v2._internal.execution.callback import ( + ControllerCallback, + ReportCallback, + TrainContextCallback, + WorkerCallback, + WorkerGroupCallback, +) +from ray.train.v2._internal.execution.checkpoint.checkpoint_manager import ( + CheckpointManager, +) +from ray.train.v2._internal.execution.checkpoint.report_handler import ( + ReportCallbackHandler, +) +from ray.train.v2._internal.execution.context import TrainRunContext +from ray.train.v2._internal.execution.controller.state import ( + AbortedState, + ErroredState, + FinishedState, + InitializingState, + ReschedulingState, + ResizingState, + RestartingState, + RunningState, + SchedulingState, + TrainControllerState, +) +from ray.train.v2._internal.execution.failure_handling import ( + FailureDecision, + FailurePolicy, +) +from ray.train.v2._internal.execution.scaling_policy import ( + NoopDecision, + ResizeDecision, + ScalingPolicy, +) +from ray.train.v2._internal.execution.storage import StorageContext +from ray.train.v2._internal.execution.worker_group import ( + WorkerGroup, + WorkerGroupPollStatus, +) +from ray.train.v2._internal.execution.worker_group.worker_group import ( + WorkerGroupContext, +) +from ray.train.v2._internal.logging.logging import configure_controller_logger +from ray.train.v2._internal.util import ObjectRefWrapper, time_monotonic +from ray.train.v2.api.callback import RayTrainCallback +from ray.train.v2.api.exceptions import TrainingFailedError +from ray.train.v2.api.result import Result + +logger = logging.getLogger(__name__) + + +@dataclass +class TrainControllerLoopIterationResult: + """The result of a single iteration of the control loop.""" + + run_attempt_id: str + previous_state: TrainControllerState + next_state: TrainControllerState + training_failed_error: Optional[TrainingFailedError] = None + + def __repr__(self) -> str: + return ( + f"TrainControllerLoopIterationResult(\n" + f" run_attempt_id={self.run_attempt_id},\n" + f" previous_state={self.previous_state._state_type.state_name},\n" + f" next_state={self.next_state._state_type.state_name}\n" + f" training_failed_error={self.training_failed_error}\n" + f")" + ) + + +class TrainController: + """Manages the execution of a distributed training job. + + Responsibilities include: + * Triggering the training function to run on the worker group. + * Monitoring the status of the worker group. + * Handling scaling decisions by restarting the worker group. + * Handling failure decisions by restarting the worker group or terminating training. + * Running callback logic on different hooks in the control loop. + """ + + worker_group_cls = WorkerGroup + + def __init__( + self, + train_fn_ref: ObjectRefWrapper[Callable[[], None]], + train_run_context: TrainRunContext, + scaling_policy: ScalingPolicy, + failure_policy: FailurePolicy, + callbacks: Optional[List[RayTrainCallback]] = None, + ): + self._train_run_context = train_run_context + if ray_constants.env_bool( + ENABLE_CONTROLLER_STRUCTURED_LOGGING_ENV_VAR, + DEFAULT_ENABLE_CONTROLLER_LOGGING, + ): + configure_controller_logger(self._train_run_context) + self._train_fn_ref = train_fn_ref + self._scaling_policy = scaling_policy + self._failure_policy = failure_policy + self._run_config = self._train_run_context.run_config + self._callbacks = callbacks or [] + self._storage_context = StorageContext( + storage_path=self._run_config.storage_path, + experiment_dir_name=self._run_config.name, + storage_filesystem=self._run_config.storage_filesystem, + ) + + self._checkpoint_manager = CheckpointManager( + checkpoint_config=self._run_config.checkpoint_config, + storage_context=self._storage_context, + ) + report_handler = ReportCallbackHandler( + report_callbacks=( + [self._checkpoint_manager] + + [c for c in self._callbacks if isinstance(c, ReportCallback)] + ) + ) + + # Group callbacks by the hooks they're subscribed to. + self._controller_callbacks = [self._scaling_policy] + [ + c for c in self._callbacks if isinstance(c, ControllerCallback) + ] + # Group callbacks that will be propagated to the worker group, + # train worker and the train context. + self._worker_group_callbacks_to_propagate = ( + [report_handler] + + [ + c + for c in self._callbacks + if isinstance( + c, (WorkerGroupCallback, WorkerCallback, TrainContextCallback) + ) + ] + + [self._checkpoint_manager] + ) + + self._health_check_interval_s = float( + os.getenv(HEALTH_CHECK_INTERVAL_S_ENV_VAR, DEFAULT_HEALTH_CHECK_INTERVAL_S) + ) + + self._worker_group: Optional[WorkerGroup] = None + self._state = InitializingState() + + # TODO: These can be attributes of a RunAttempt? + self._latest_poll_time = float("-inf") + + self._start() + + def _execute_resize_decision( + self, decision: ResizeDecision + ) -> TrainControllerLoopIterationResult: + """Executes resize decisions.""" + + for callback in self._controller_callbacks: + callback.before_controller_execute_resize_decision(decision) + + if self._worker_group: + self._shutdown_worker_group() + + worker_group_started = self._start_worker_group( + num_workers=decision.num_workers, + resources_per_worker=decision.resources_per_worker, + ) + + if worker_group_started: + next_state = RunningState() + else: + next_state = ReschedulingState() + + return TrainControllerLoopIterationResult( + run_attempt_id=self._get_run_attempt_id(), + previous_state=self._state, + next_state=next_state, + ) + + def _execute_failure_decision( + self, + failure_decision: FailureDecision, + worker_group_status: WorkerGroupPollStatus, + ) -> TrainControllerLoopIterationResult: + """Executes failure handling decisions (ex: restart, terminate).""" + assert worker_group_status.errors + + controller_state = self.get_state() + + for callback in self._controller_callbacks: + callback.before_controller_execute_failure_decision(failure_decision) + + # TODO: What should we do here? + # This currently never happens because there must be errors. + if failure_decision == FailureDecision.NOOP: + return TrainControllerLoopIterationResult( + run_attempt_id=self._get_run_attempt_id(), + previous_state=controller_state, + next_state=RunningState(), + ) + + errors_str = worker_group_status.get_error_string() + training_failed_error = TrainingFailedError( + error_message=errors_str, worker_failures=worker_group_status.errors + ) + + if failure_decision == FailureDecision.RESTART: + logger.error( + "Restarting training worker group after encountering " + f"failures on {len(worker_group_status.errors)} worker(s):\n" + f"{errors_str}" + ) + next_state = RestartingState(training_failed_error=training_failed_error) + return TrainControllerLoopIterationResult( + run_attempt_id=self._get_run_attempt_id(), + previous_state=controller_state, + next_state=next_state, + training_failed_error=training_failed_error, + ) + elif failure_decision == FailureDecision.RAISE: + logger.error( + "Terminating training worker group after encountering " + f"failure(s) on {len(worker_group_status.errors)} worker(s):\n" + f"{errors_str}" + ) + next_state = ErroredState(training_failed_error=training_failed_error) + return TrainControllerLoopIterationResult( + run_attempt_id=self._get_run_attempt_id(), + previous_state=controller_state, + next_state=next_state, + training_failed_error=training_failed_error, + ) + else: + raise ValueError(f"Unexpected failure decision: {failure_decision}") + + async def _poll_workers(self) -> WorkerGroupPollStatus: + # Ensure that the time between polls is at least HEALTH_CHECK_INTERVAL_S. + time_since_last_poll = time_monotonic() - self._latest_poll_time + if time_since_last_poll < self._health_check_interval_s: + remaining_time = max( + self._health_check_interval_s - time_since_last_poll, 0 + ) + await asyncio.sleep(remaining_time) + + status = self._worker_group.poll_status(timeout=self._health_check_interval_s) + self._latest_poll_time = time_monotonic() + return status + + def _start_worker_group(self, num_workers: int, resources_per_worker: dict) -> bool: + """Start the worker group and launch the train function. + + Returns: + True if the worker group was successfully started, False otherwise. + """ + placement_strategy = self._scaling_policy.scaling_config.placement_strategy + worker_group_context = WorkerGroupContext( + run_attempt_id=self._get_run_attempt_id(), + train_fn_ref=self._train_fn_ref, + num_workers=num_workers, + resources_per_worker=resources_per_worker, + placement_strategy=placement_strategy, + ) + try: + self._worker_group = self.worker_group_cls.create( + train_run_context=self._train_run_context, + worker_group_context=worker_group_context, + callbacks=self._worker_group_callbacks_to_propagate, + ) + except (WorkerGroupStartupTimeoutError, WorkerGroupStartupFailedError) as e: + logger.error( + "Retrying the launch of the training worker group. " + f"The previous launch attempt encountered the following failure:\n{e}" + ) + + # TODO: Should this logic go through the failure policy? + # The current logic will always try recovering unconditionally + # on startup errors without a retry limit. + return False + + # TODO: Consider starting the worker group asynchronously. + return True + + def _start(self): + for callback in self._controller_callbacks: + callback.after_controller_start(self._train_run_context) + + def _shutdown(self): + if self._worker_group: + self._shutdown_worker_group() + + for callback in self._controller_callbacks: + callback.before_controller_shutdown() + + def _shutdown_worker_group(self): + """Shutdown the worker group and set the worker group to None.""" + self._worker_group.shutdown() + self._worker_group = None + + def get_worker_group(self) -> Optional[WorkerGroup]: + return self._worker_group + + def get_state(self) -> TrainControllerState: + return self._state + + def _set_state(self, state: TrainControllerState): + previous_state = self._state + self._state = state + + for callback in self._controller_callbacks: + callback.after_controller_state_update(previous_state, state) + + def _make_and_handle_scaling_decision_for_non_running_worker_group( + self, + controller_state: TrainControllerState, + ) -> TrainControllerLoopIterationResult: + """Make a scaling decision for a non-running worker group and return the appropriate next state. + + This method should be called when entering a state that requires a scaling decision + for a non-running worker group. + + This method handles the complete flow of: + 1. Getting a scaling decision for a non-running worker group + 2. Determining the next state based on the decision type + 3. Creating and returning the iteration result + + Args: + controller_state: The current controller state + + Returns: + TrainControllerLoopIterationResult with the appropriate next state + """ + scaling_decision = ( + self._scaling_policy.make_decision_for_non_running_worker_group() + ) + + if isinstance(scaling_decision, NoopDecision): + next_state = controller_state + elif isinstance(scaling_decision, ResizeDecision): + next_state = SchedulingState(scaling_decision) + else: + raise ValueError(f"Unexpected scaling decision: {scaling_decision}") + + return TrainControllerLoopIterationResult( + run_attempt_id=self._get_run_attempt_id(), + previous_state=controller_state, + next_state=next_state, + ) + + async def _step(self) -> TrainControllerLoopIterationResult: + """Run a single iteration of the control loop. + + Returns: + The result of the iteration. + """ + controller_state = self.get_state() + + if isinstance( + controller_state, (InitializingState, ReschedulingState, RestartingState) + ): + return self._make_and_handle_scaling_decision_for_non_running_worker_group( + controller_state + ) + elif isinstance(controller_state, SchedulingState): + assert isinstance(controller_state.scaling_decision, ResizeDecision) + return self._execute_resize_decision(controller_state.scaling_decision) + elif isinstance(controller_state, RunningState): + worker_group_status = await self._poll_workers() + + if worker_group_status.finished and not worker_group_status.errors: + return TrainControllerLoopIterationResult( + run_attempt_id=self._get_run_attempt_id(), + previous_state=controller_state, + next_state=FinishedState(), + ) + if worker_group_status.errors: + failure_decision = self._failure_policy.make_decision( + worker_group_status + ) + return self._execute_failure_decision( + failure_decision, worker_group_status + ) + else: + scaling_decision = self._scaling_policy.make_decision_for_running_worker_group( + worker_group_state=self.get_worker_group().get_worker_group_state(), + worker_group_status=worker_group_status, + ) + + if isinstance(scaling_decision, NoopDecision): + next_state = RunningState() + elif isinstance(scaling_decision, ResizeDecision): + next_state = ResizingState( + scaling_decision=scaling_decision, + ) + else: + raise ValueError(f"Unexpected scaling decision: {scaling_decision}") + + return TrainControllerLoopIterationResult( + run_attempt_id=self._get_run_attempt_id(), + previous_state=controller_state, + next_state=next_state, + ) + elif isinstance(controller_state, ResizingState): + return TrainControllerLoopIterationResult( + run_attempt_id=self._get_run_attempt_id(), + previous_state=controller_state, + next_state=SchedulingState( + scaling_decision=controller_state.scaling_decision + ), + ) + else: + raise ValueError(f"Unexpected controller state: {controller_state}") + + def _generate_run_attempt_id(self): + self._run_attempt_id = uuid.uuid4().hex + return self._run_attempt_id + + def _get_run_attempt_id(self): + return self._run_attempt_id + + async def _run_control_loop_iteration(self): + """Run a single iteration of the control loop. + + Steps: + 1. Poll the worker group for status. + 2. If the worker group is initializing or recovering from an error, + make a scaling decision and execute it. + 3. If the worker group has finished, set the controller state to FINISHED. + 4. If the worker group has errors, make a failure decision and execute it. + 5. Otherwise, the worker group is running healthily. + Query the scaling policy for a scaling decision and execute it. + """ + controller_state = self.get_state() + assert not controller_state.is_terminal() + + if controller_state.needs_new_run_attempt(): + self._generate_run_attempt_id() + + result = await self._step() + + self._set_state(result.next_state) + + async def run(self): + """Run the main control loop. Exits when training is finished or errored.""" + while not self.get_state().is_terminal(): + await self._run_control_loop_iteration() + + # TODO: move to __del__ after https://github.com/ray-project/ray/issues/53169 + self._shutdown() + + # Call after_controller_finish with the final result + result = self._build_result() + for callback in self._controller_callbacks: + callback.after_controller_finish(result) + + async def abort(self): + """Trigger callback abort hooks and terminate the controller process.""" + # Do not abort run if it's already finished. + if self.get_state().is_terminal(): + return + # Intentionally abort worker group before setting train run state because + # we only reconcile the states of live train runs. + if self._worker_group: + self._worker_group.abort() + self._set_state(AbortedState()) + ray.actor.exit_actor() + + def _build_result(self) -> Result: + storage = self._checkpoint_manager._storage_context + + latest_checkpoint_result = self._checkpoint_manager.latest_checkpoint_result + latest_metrics = ( + latest_checkpoint_result.metrics if latest_checkpoint_result else None + ) + latest_checkpoint = ( + latest_checkpoint_result.checkpoint if latest_checkpoint_result else None + ) + best_checkpoints = [ + (r.checkpoint, r.metrics) + for r in self._checkpoint_manager.best_checkpoint_results + ] + + # Provide the history of metrics attached to checkpoints as a dataframe. + metrics_dataframe = None + if best_checkpoints: + metrics_dataframe = pd.DataFrame([m for _, m in best_checkpoints]) + + return Result( + metrics=latest_metrics, + checkpoint=latest_checkpoint, + error=self.get_training_failed_error(), + path=storage.experiment_fs_path, + best_checkpoints=best_checkpoints, + metrics_dataframe=metrics_dataframe, + _storage_filesystem=storage.storage_filesystem, + ) + + def get_result(self) -> Result: + """Get the final training result from the TrainController.""" + + controller_state = self.get_state() + if not controller_state.is_terminal(): + raise ValueError( + f"Cannot get result when controller is in state {controller_state}" + ) + + return self._build_result() + + def get_training_failed_error(self) -> Optional[TrainingFailedError]: + """Get the training failed error from the controller state. + + Returns: + The training failed error if the controller is in an errored state, + None otherwise. + """ + controller_state = self.get_state() + + if isinstance(controller_state, ErroredState): + return controller_state.training_failed_error + + return None diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/state.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/state.py new file mode 100644 index 0000000000000000000000000000000000000000..575650bfe21d06b29bf251acc5fb5283111cf086 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/controller/state.py @@ -0,0 +1,138 @@ +from enum import Enum + +from ray.train.v2._internal.execution.scaling_policy.scaling_policy import ( + ScalingDecision, +) +from ray.train.v2.api.exceptions import TrainingFailedError + + +class TrainControllerStateType(Enum): + """Enum representing different states of the train controller. + + States: + INITIALIZING: The train controller is starting up. This is always the initial + state of the controller. + SCHEDULING: The training controller is in the process of scheduling a new worker + group. + RESCHEDULING: The train controller is in the process of rescheduling the worker + group. + RUNNING: The train controller is actively running training tasks. + RESTARTING: The train controller is in the process of recovering from an error. + RESIZING: The train controller is in the process of resizing a running worker + group. + ERRORED: A terminal state indicating that training has encountered an error and + cannot continue. + FINISHED: A terminal state indicating that training has completed. + ABORTED: A terminal state indicating that training has been aborted. + + Args: + state_name: The name of the state. + is_terminal: Whether this is a terminal state that should not be further processed. + needs_new_run_attempt: Whether this state requires starting a new run attempt, where + a run attempt is a logical unit that encompasses both scheduling workers and + executing training on those workers. + """ + + INITIALIZING = ("INITIALIZING", False, True) + SCHEDULING = ("SCHEDULING", False, False) + RESCHEDULING = ("RESCHEDULING", False, False) + RUNNING = ("RUNNING", False, False) + RESTARTING = ("RESTARTING", False, True) + RESIZING = ("RESIZING", False, True) + ERRORED = ("ERRORED", True, False) + FINISHED = ("FINISHED", True, False) + ABORTED = ("ABORTED", True, False) + + def __init__(self, state_name: str, is_terminal: bool, needs_new_run_attempt: bool): + self.state_name = state_name + self.is_terminal = is_terminal + self.needs_new_run_attempt = needs_new_run_attempt + + +class TrainControllerState: + """Base class for all train controller states. + + Methods: + get_type() -> TrainControllerStateType: Returns the type of the state. + is_terminal() -> bool: Returns whether the state is terminal. + needs_new_run_attempt() -> bool: Returns whether a new run attempt is needed. + """ + + def __init__(self, state_type: TrainControllerStateType): + self._state_type = state_type + + def __repr__(self) -> str: + attrs = { + "type": self._state_type.name, + "is_terminal": self._state_type.is_terminal, + "needs_new_run_attempt": self._state_type.needs_new_run_attempt, + **{k: v for k, v in vars(self).items() if not k.startswith("_")}, + } + attrs_str = "\n ".join(f"{k}={v}" for k, v in attrs.items()) + return f"{self.__class__.__name__}(\n {attrs_str}\n)" + + def is_terminal(self) -> bool: + return self._state_type.is_terminal + + def needs_new_run_attempt(self) -> bool: + return self._state_type.needs_new_run_attempt + + +class InitializingState(TrainControllerState): + def __init__(self): + super().__init__(state_type=TrainControllerStateType.INITIALIZING) + + +class SchedulingState(TrainControllerState): + def __init__(self, scaling_decision: ScalingDecision): + super().__init__(state_type=TrainControllerStateType.SCHEDULING) + self.scaling_decision = scaling_decision + + +class ReschedulingState(TrainControllerState): + def __init__(self): + super().__init__(state_type=TrainControllerStateType.RESCHEDULING) + + +class RunningState(TrainControllerState): + # TODO: Split into multiple more granular states, or add more fields. + # For example, we may want to indicate if any health checks failed. + def __init__(self): + super().__init__(state_type=TrainControllerStateType.RUNNING) + + +class RestartingState(TrainControllerState): + def __init__( + self, + training_failed_error: TrainingFailedError, + ): + super().__init__(state_type=TrainControllerStateType.RESTARTING) + self.training_failed_error = training_failed_error + + +class ResizingState(TrainControllerState): + def __init__( + self, + scaling_decision: ScalingDecision, + ): + super().__init__(state_type=TrainControllerStateType.RESIZING) + self.scaling_decision = scaling_decision + + +class ErroredState(TrainControllerState): + def __init__( + self, + training_failed_error: TrainingFailedError, + ): + super().__init__(state_type=TrainControllerStateType.ERRORED) + self.training_failed_error = training_failed_error + + +class FinishedState(TrainControllerState): + def __init__(self): + super().__init__(state_type=TrainControllerStateType.FINISHED) + + +class AbortedState(TrainControllerState): + def __init__(self): + super().__init__(state_type=TrainControllerStateType.ABORTED) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a2f13ae8ec17a39c124939d33c67014abc64bc1c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__init__.py @@ -0,0 +1,16 @@ +# isort: off +from .failure_policy import FailureDecision, FailurePolicy +from .default import DefaultFailurePolicy +from .factory import create_failure_policy + +# isort: on + +__all__ = [ + "DefaultFailurePolicy", + "FailureDecision", + "FailurePolicy", + "create_failure_policy", +] + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8257da9d2235f9530bedb546dd169dfb1b55f3a2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/default.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/default.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79058a76d93644877517d589f0001489058c83aa Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/default.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/factory.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/factory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d050005244fd1887942707964ed86dd138e17bc8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/factory.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/failure_policy.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/failure_policy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23cd8fd2674e8ef66aa6d1a85ee55693f052063b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/__pycache__/failure_policy.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/default.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/default.py new file mode 100644 index 0000000000000000000000000000000000000000..dc521c8c82e93c56e9e099fcfe9f8537a3fdbaad --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/default.py @@ -0,0 +1,46 @@ +import logging + +from ray.train import FailureConfig +from ray.train.v2._internal.execution.failure_handling import ( + FailureDecision, + FailurePolicy, +) +from ray.train.v2._internal.execution.worker_group import WorkerGroupPollStatus + +logger = logging.getLogger(__name__) + + +class DefaultFailurePolicy(FailurePolicy): + def __init__(self, failure_config: FailureConfig): + super().__init__(failure_config) + self._total_failures = 0 + + def make_decision( + self, worker_group_status: WorkerGroupPollStatus + ) -> FailureDecision: + if not worker_group_status.errors: + return FailureDecision.NOOP + + self._total_failures += 1 + + if self.failure_config.max_failures == -1: + logger.info( + "Deciding to RESTART, since infinite retry is enabled. " + f"Encountered {self._total_failures} failures so far." + ) + return FailureDecision.RESTART + + if self._total_failures > self.failure_config.max_failures: + logger.info( + "Deciding to TERMINATE, since the total failure count " + f"({self._total_failures}) exceeded the maximum allowed failures: " + f"FailureConfig(max_failures={self.failure_config.max_failures})." + ) + return FailureDecision.RAISE + + logger.info( + "Deciding to RESTART, since the total " + f"failure count ({self._total_failures}) <= " + f"FailureConfig(max_failures={self.failure_config.max_failures})." + ) + return FailureDecision.RESTART diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/factory.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..48a902c0300e7931b4c1808ba90766fdaf1bff98 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/factory.py @@ -0,0 +1,13 @@ +from ray.train import FailureConfig +from ray.train.v2._internal.execution.failure_handling import ( + DefaultFailurePolicy, + FailurePolicy, +) + + +def create_failure_policy(failure_config: FailureConfig) -> FailurePolicy: + """Create a failure policy from the given failure config. + + Defaults to the `DefaultFailurePolicy` implementation. + """ + return DefaultFailurePolicy(failure_config=failure_config) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/failure_policy.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/failure_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..e6ce8369971c4b7a438fc117777090c92d4c9700 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/failure_handling/failure_policy.py @@ -0,0 +1,27 @@ +import abc +from enum import Enum + +from ray.train.v2._internal.execution.worker_group import WorkerGroupPollStatus +from ray.train.v2.api.config import FailureConfig + + +class FailureDecision(Enum): + RESTART = "RESTART" + RAISE = "RAISE" + NOOP = "NOOP" + + +class FailurePolicy(abc.ABC): + """A policy that determines how to handle user and system failures. + + This can be used to implement fault tolerance and error recovery. + """ + + def __init__(self, failure_config: FailureConfig): + self.failure_config = failure_config + + @abc.abstractmethod + def make_decision( + self, worker_group_status: WorkerGroupPollStatus + ) -> FailureDecision: + raise NotImplementedError diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f51407285701dbce7bc8ba3d4d93c6b0afb8bd5c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__init__.py @@ -0,0 +1,19 @@ +# isort: off +from .scaling_policy import ScalingDecision, ScalingPolicy, NoopDecision, ResizeDecision +from .fixed import FixedScalingPolicy +from .factory import create_scaling_policy + +# isort: on + + +__all__ = [ + "ScalingPolicy", + "FixedScalingPolicy", + "ScalingDecision", + "NoopDecision", + "ResizeDecision", + "create_scaling_policy", +] + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29b0b7e61fcbac88d695cc94bb3759f5fdb4ccd1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/factory.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/factory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df59b53f912c8948f0b0b8f8c9b0c9e9669f5170 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/factory.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/fixed.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/fixed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc5d55584fe7fd543e27a7b9d451e2ab01808871 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/fixed.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/scaling_policy.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/scaling_policy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfa1cc71647ff672320150da34734e6e9027fc7e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/__pycache__/scaling_policy.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/factory.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..506a1df09e94e35f093eb9e5802f714ec7ed1543 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/factory.py @@ -0,0 +1,13 @@ +from ray.train.v2._internal.execution.scaling_policy import ( + FixedScalingPolicy, + ScalingPolicy, +) +from ray.train.v2.api.config import ScalingConfig + + +def create_scaling_policy(scaling_config: ScalingConfig) -> ScalingPolicy: + """Create a scaling policy from the given scaling config. + + Defaults to the `FixedScalingPolicy` implementation. + """ + return FixedScalingPolicy(scaling_config=scaling_config) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/fixed.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/fixed.py new file mode 100644 index 0000000000000000000000000000000000000000..154b45b7fe5611285de955e016ec4fe95e59166e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/fixed.py @@ -0,0 +1,25 @@ +from ray.train.v2._internal.execution.scaling_policy import ( + NoopDecision, + ResizeDecision, + ScalingDecision, + ScalingPolicy, +) +from ray.train.v2._internal.execution.worker_group import ( + WorkerGroupPollStatus, + WorkerGroupState, +) + + +class FixedScalingPolicy(ScalingPolicy): + def make_decision_for_non_running_worker_group(self) -> ScalingDecision: + return ResizeDecision( + num_workers=self.scaling_config.num_workers, + resources_per_worker=self.scaling_config._resources_per_worker_not_none, + ) + + def make_decision_for_running_worker_group( + self, + worker_group_state: WorkerGroupState, + worker_group_status: WorkerGroupPollStatus, + ) -> ScalingDecision: + return NoopDecision() diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/scaling_policy.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/scaling_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..50cf88f84d9c6ba8bc4aac2a0656e1ace43f472f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/scaling_policy/scaling_policy.py @@ -0,0 +1,57 @@ +import abc +from dataclasses import dataclass +from typing import Dict + +from ray.train.v2._internal.execution.callback import ControllerCallback +from ray.train.v2._internal.execution.worker_group import ( + WorkerGroupPollStatus, + WorkerGroupState, +) +from ray.train.v2.api.config import ScalingConfig + + +@dataclass +class ScalingDecision: + pass + + +@dataclass +class NoopDecision(ScalingDecision): + pass + + +@dataclass +class ResizeDecision(ScalingDecision): + num_workers: int + resources_per_worker: Dict[str, float] + + +class ScalingPolicy(abc.ABC, ControllerCallback): + """A policy that determines when and how to scale a worker group. + + This can be used to implement elasticity and fault tolerance. + + Recovery decisions are made when workers are in an inactive or unhealthy state. + Upscale decisions are optional and are made when workers are healthy. + """ + + # TODO: Restructure these APIs to consider different TrainControllerStates + # instead of just running and non-running worker groups. + + def __init__(self, scaling_config: ScalingConfig): + self.scaling_config = scaling_config + + @abc.abstractmethod + def make_decision_for_non_running_worker_group(self) -> ScalingDecision: + """Makes a scaling decision when the worker group is initializing + or recovering from an error.""" + raise NotImplementedError + + @abc.abstractmethod + def make_decision_for_running_worker_group( + self, + worker_group_state: WorkerGroupState, + worker_group_status: WorkerGroupPollStatus, + ) -> ScalingDecision: + """Makes a scaling decision when monitoring healthy, running workers.""" + raise NotImplementedError diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/storage.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..4ffc740c50af874a7d57134773acbad2d32f9d5a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/storage.py @@ -0,0 +1,551 @@ +# Try import ray[train] core requirements (defined in setup.py) +# isort: off +try: + import fsspec # noqa + from fsspec.implementations.local import LocalFileSystem + +except (ImportError, ModuleNotFoundError) as e: + raise RuntimeError( + "fsspec is a required dependency of Ray Train and Ray Tune. " + "Please install with: `pip install fsspec`" + ) from e + +try: + import pyarrow + import pyarrow.fs + +except (ImportError, ModuleNotFoundError) as e: + raise RuntimeError( + "pyarrow is a required dependency of Ray Train and Ray Tune. " + "Please install with: `pip install pyarrow`" + ) from e +# isort: on + +import fnmatch +import logging +import os +import shutil +from pathlib import Path +from typing import TYPE_CHECKING, Callable, List, Optional, Tuple, Type, Union + +from ray.air._internal.filelock import TempFileLock +from ray.train.constants import _get_ray_train_session_dir +from ray.train.v2._internal.constants import ( + CHECKPOINT_MANAGER_SNAPSHOT_FILENAME, + VALIDATE_STORAGE_MARKER_FILENAME, +) +from ray.train.v2._internal.util import date_str +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + from ray.train import Checkpoint + + +logger = logging.getLogger(__name__) + + +class _ExcludingLocalFilesystem(LocalFileSystem): + """LocalFileSystem wrapper to exclude files according to patterns. + + Args: + root_path: Root path to strip when matching with the exclude pattern. + Ex: root_path="/tmp/a/b/c", exclude=["*a*"], will exclude + /tmp/a/b/c/_a_.txt but not ALL of /tmp/a/*. + exclude: List of patterns that are applied to files returned by + ``self.find()``. If a file path matches this pattern, it will + be excluded. + + """ + + def __init__(self, root_path: Path, exclude: List[str], **kwargs): + super().__init__(**kwargs) + self._exclude = exclude + self._root_path = root_path + + @property + def fsid(self): + return "_excluding_local" + + def _should_exclude(self, path: str) -> bool: + """Return True if `path` (relative to `root_path`) matches any of the + `self._exclude` patterns.""" + path = Path(path) + relative_path = path.relative_to(self._root_path).as_posix() + match_candidates = [relative_path] + if path.is_dir(): + # Everything is in posix path format ('/') + match_candidates.append(relative_path + "/") + + for excl in self._exclude: + if any(fnmatch.fnmatch(candidate, excl) for candidate in match_candidates): + return True + return False + + def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + """Call parent find() and exclude from result.""" + paths = super().find( + path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs + ) + if detail: + return { + path: out + for path, out in paths.items() + if not self._should_exclude(path) + } + else: + return [path for path in paths if not self._should_exclude(path)] + + +def _pyarrow_fs_copy_files( + source, destination, source_filesystem=None, destination_filesystem=None, **kwargs +): + if isinstance(destination_filesystem, pyarrow.fs.S3FileSystem): + # Workaround multi-threading issue with pyarrow. Note that use_threads=True + # is safe for download, just not for uploads, see: + # https://github.com/apache/arrow/issues/32372 + kwargs.setdefault("use_threads", False) + + # Use a large chunk size to speed up large checkpoint transfers. + kwargs.setdefault("chunk_size", 64 * 1024 * 1024) + + return pyarrow.fs.copy_files( + source, + destination, + source_filesystem=source_filesystem, + destination_filesystem=destination_filesystem, + **kwargs, + ) + + +# TODO(justinvyu): Add unit tests for all these utils. + + +def _delete_fs_path(fs: pyarrow.fs.FileSystem, fs_path: str): + is_dir = _is_directory(fs, fs_path) + + try: + if is_dir: + fs.delete_dir(fs_path) + else: + fs.delete_file(fs_path) + except Exception: + logger.exception(f"Caught exception when deleting path at ({fs}, {fs_path}):") + + +def _download_from_fs_path( + fs: pyarrow.fs.FileSystem, + fs_path: str, + local_path: str, + filelock: bool = True, +): + """Downloads a directory or file from (fs, fs_path) to a local path. + + If fs_path points to a directory: + - The full directory contents are downloaded directly into `local_path`, + rather than to a subdirectory of `local_path`. + + If fs_path points to a file: + - The file is downloaded to `local_path`, which is expected to be a file path. + + If the download fails, the `local_path` contents are + cleaned up before raising, if the directory did not previously exist. + + NOTE: This method creates `local_path`'s parent directories if they do not + already exist. If the download fails, this does NOT clean up all the parent + directories that were created. + + Args: + fs: The filesystem to download from. + fs_path: The filesystem path (either a directory or a file) to download. + local_path: The local path to download to. + filelock: Whether to require a file lock before downloading, useful for + multiple downloads to the same directory that may be happening in parallel. + + Raises: + FileNotFoundError: if (fs, fs_path) doesn't exist. + """ + + _local_path = Path(local_path).resolve() + exists_before = _local_path.exists() + if _is_directory(fs=fs, fs_path=fs_path): + _local_path.mkdir(parents=True, exist_ok=True) + else: + _local_path.parent.mkdir(parents=True, exist_ok=True) + + try: + if filelock: + with TempFileLock(f"{os.path.normpath(local_path)}.lock"): + _pyarrow_fs_copy_files(fs_path, local_path, source_filesystem=fs) + else: + _pyarrow_fs_copy_files(fs_path, local_path, source_filesystem=fs) + except Exception as e: + # Clean up the directory if downloading was unsuccessful + if not exists_before: + shutil.rmtree(local_path, ignore_errors=True) + raise e + + +def _upload_to_fs_path( + local_path: str, + fs: pyarrow.fs.FileSystem, + fs_path: str, + exclude: Optional[List[str]] = None, +) -> None: + """Uploads a local directory or file to (fs, fs_path). + + NOTE: This will create all necessary parent directories at the destination. + + Args: + local_path: The local path to upload. + fs: The filesystem to upload to. + fs_path: The filesystem path where the dir/file will be uploaded to. + exclude: A list of filename matches to exclude from upload. This includes + all files under subdirectories as well. + This pattern will match with the relative paths of all files under + `local_path`. + Ex: ["*.png"] to exclude all .png images. + """ + + if not exclude: + # TODO(justinvyu): uploading a single file doesn't work + # (since we always create a directory at fs_path) + _create_directory(fs=fs, fs_path=fs_path) + _pyarrow_fs_copy_files(local_path, fs_path, destination_filesystem=fs) + return + + _upload_to_uri_with_exclude_fsspec( + local_path=local_path, fs=fs, fs_path=fs_path, exclude=exclude + ) + + +def _upload_to_uri_with_exclude_fsspec( + local_path: str, fs: "pyarrow.fs", fs_path: str, exclude: Optional[List[str]] +) -> None: + local_fs = _ExcludingLocalFilesystem(root_path=local_path, exclude=exclude) + handler = pyarrow.fs.FSSpecHandler(local_fs) + source_fs = pyarrow.fs.PyFileSystem(handler) + + _create_directory(fs=fs, fs_path=fs_path) + _pyarrow_fs_copy_files( + local_path, fs_path, source_filesystem=source_fs, destination_filesystem=fs + ) + + +def _list_at_fs_path( + fs: pyarrow.fs.FileSystem, + fs_path: str, + file_filter: Callable[[pyarrow.fs.FileInfo], bool] = lambda x: True, +) -> List[str]: + """Returns the list of filenames at (fs, fs_path), similar to os.listdir. + + If the path doesn't exist, returns an empty list. + """ + selector = pyarrow.fs.FileSelector(fs_path, allow_not_found=True, recursive=False) + return [ + os.path.relpath(file_info.path.lstrip("/"), start=fs_path.lstrip("/")) + for file_info in fs.get_file_info(selector) + if file_filter(file_info) + ] + + +def _exists_at_fs_path(fs: pyarrow.fs.FileSystem, fs_path: str) -> bool: + """Returns True if (fs, fs_path) exists.""" + + valid = fs.get_file_info(fs_path) + return valid.type != pyarrow.fs.FileType.NotFound + + +def _is_directory(fs: pyarrow.fs.FileSystem, fs_path: str) -> bool: + """Checks if (fs, fs_path) is a directory or a file. + + Raises: + FileNotFoundError: if (fs, fs_path) doesn't exist. + """ + + file_info = fs.get_file_info(fs_path) + if file_info.type == pyarrow.fs.FileType.NotFound: + raise FileNotFoundError(f"Path not found: ({fs}, {fs_path})") + + return not file_info.is_file + + +def _create_directory(fs: pyarrow.fs.FileSystem, fs_path: str) -> None: + """Create directory at (fs, fs_path). + + Some external filesystems require directories to already exist, or at least + the `netloc` to be created (e.g. PyArrows ``mock://`` filesystem). + + Generally this should be done before and outside of Ray applications. This + utility is thus primarily used in testing, e.g. of ``mock://` URIs. + """ + try: + fs.create_dir(fs_path) + except Exception: + logger.exception( + f"Caught exception when creating directory at ({fs}, {fs_path}):" + ) + + +def get_fs_and_path( + storage_path: Union[str, os.PathLike], + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, +) -> Tuple[pyarrow.fs.FileSystem, str]: + """Returns the fs and path from a storage path and an optional custom fs. + + Args: + storage_path: A storage path or URI. (ex: s3://bucket/path or /tmp/ray_results) + storage_filesystem: A custom filesystem to use. If not provided, + this will be auto-resolved by pyarrow. If provided, the storage_path + is assumed to be prefix-stripped already, and must be a valid path + on the filesystem. + """ + storage_path = str(storage_path) + + if storage_filesystem: + return storage_filesystem, storage_path + + return pyarrow.fs.FileSystem.from_uri(storage_path) + + +@DeveloperAPI +class StorageContext: + """Shared context that holds the source of truth for all paths and + storage utilities, passed along from the driver to workers. + + This object defines a few types of paths: + 1. *_fs_path: A path on the `storage_filesystem`. This is a regular path + which has been prefix-stripped by pyarrow.fs.FileSystem.from_uri and + can be joined with `Path(...).as_posix()`. + 2. *_driver_staging_path: The temporary staging directory on the local filesystem + where driver artifacts are saved to before persisting them to storage. + 3. trial_working_directory: The local filesystem path that the remote + actors' working directories are moved to by default. + This is separated from the driver staging path so that driver syncing + does not implicitly upload the trial working directory, for trials on the + driver node. + + Example with storage_path="mock:///bucket/path?param=1": + + >>> import ray + >>> from ray.train._internal.storage import StorageContext + >>> import os + >>> _ = ray.init() + >>> storage = StorageContext( + ... storage_path="mock://netloc/bucket/path?param=1", + ... experiment_dir_name="exp_name", + ... ) + >>> storage.storage_filesystem # Auto-resolved # doctest: +ELLIPSIS + >> storage.experiment_fs_path + 'bucket/path/exp_name' + >>> storage.experiment_driver_staging_path # doctest: +ELLIPSIS + '/tmp/ray/session_.../artifacts/.../exp_name/driver_artifacts' + >>> storage.trial_dir_name = "trial_dir" + >>> storage.trial_fs_path + 'bucket/path/exp_name/trial_dir' + >>> storage.trial_driver_staging_path # doctest: +ELLIPSIS + '/tmp/ray/session_.../artifacts/.../exp_name/driver_artifacts/trial_dir' + >>> storage.trial_working_directory # doctest: +ELLIPSIS + '/tmp/ray/session_.../artifacts/.../exp_name/working_dirs/trial_dir' + >>> ray.shutdown() + + Example with storage_path="/tmp/ray_results": + + >>> from ray.train._internal.storage import StorageContext + >>> storage = StorageContext( + ... storage_path="/tmp/ray_results", + ... experiment_dir_name="exp_name", + ... ) + >>> storage.storage_fs_path + '/tmp/ray_results' + >>> storage.experiment_fs_path + '/tmp/ray_results/exp_name' + >>> storage.storage_filesystem # Auto-resolved # doctest: +ELLIPSIS + " + ) + + def _create_validation_file(self): + """On the creation of a storage context, create a validation file at the + storage path to verify that the storage path can be written to. + This validation file is also used to check whether the storage path is + accessible by all nodes in the cluster.""" + valid_file = Path( + self.experiment_fs_path, VALIDATE_STORAGE_MARKER_FILENAME + ).as_posix() + self.storage_filesystem.create_dir(self.experiment_fs_path) + with self.storage_filesystem.open_output_stream(valid_file): + pass + + def _check_validation_file(self): + """Checks that the validation file exists at the storage path.""" + valid_file = Path( + self.experiment_fs_path, VALIDATE_STORAGE_MARKER_FILENAME + ).as_posix() + if not _exists_at_fs_path(fs=self.storage_filesystem, fs_path=valid_file): + raise RuntimeError( + f"Unable to set up cluster storage with the following settings:\n{self}" + "\nCheck that all nodes in the cluster have read/write access " + "to the configured storage path. `RunConfig(storage_path)` should be " + "set to a cloud storage URI or a shared filesystem path accessible " + "by all nodes in your cluster ('s3://bucket' or '/mnt/nfs'). " + "A local path on the head node is not accessible by worker nodes. " + "See: https://docs.ray.io/en/latest/train/user-guides/persistent-storage.html" # noqa: E501 + ) + + def persist_current_checkpoint( + self, checkpoint: "Checkpoint", checkpoint_dir_name: str + ) -> "Checkpoint": + """Persists a given checkpoint to the current checkpoint path on the filesystem. + + This method copies the checkpoint files to the storage location. + It's up to the user to delete the original checkpoint files if desired. + + For example, the original directory is typically a local temp directory. + + Args: + checkpoint: The checkpoint to persist to + (fs, experiment_fs_path / checkpoint_dir_name). + + Returns: + Checkpoint: A Checkpoint pointing to the persisted checkpoint location. + """ + # TODO(justinvyu): Fix this cyclical import. + from ray.train import Checkpoint + + checkpoint_fs_path = self.build_checkpoint_path_from_name(checkpoint_dir_name) + + logger.debug( + "Copying checkpoint files to storage path:\n" + "({source_fs}, {source}) -> ({dest_fs}, {destination})".format( + source=checkpoint.path, + destination=checkpoint_fs_path, + source_fs=checkpoint.filesystem, + dest_fs=self.storage_filesystem, + ) + ) + + # Raise an error if the storage path is not accessible when + # attempting to upload a checkpoint from a remote worker. + # Ex: If storage_path is a local path, then a validation marker + # will only exist on the head node but not the worker nodes. + self._check_validation_file() + + self.storage_filesystem.create_dir(checkpoint_fs_path) + _pyarrow_fs_copy_files( + source=checkpoint.path, + destination=checkpoint_fs_path, + source_filesystem=checkpoint.filesystem, + destination_filesystem=self.storage_filesystem, + ) + + persisted_checkpoint = Checkpoint( + filesystem=self.storage_filesystem, + path=checkpoint_fs_path, + ) + logger.info(f"Checkpoint successfully created at: {persisted_checkpoint}") + return persisted_checkpoint + + @property + def experiment_fs_path(self) -> str: + """The path on the `storage_filesystem` to the experiment directory. + + NOTE: This does not have a URI prefix anymore, since it has been stripped + by pyarrow.fs.FileSystem.from_uri already. The URI scheme information is + kept in `storage_filesystem` instead. + """ + return Path(self.storage_fs_path, self.experiment_dir_name).as_posix() + + @property + def local_working_directory(self) -> str: + """Every ray train worker will set this directory as its working directory.""" + if self.experiment_dir_name is None: + raise RuntimeError( + "Cannot access `local_working_directory` without " + "setting `experiment_dir_name`" + ) + return Path(_get_ray_train_session_dir(), self.experiment_dir_name).as_posix() + + @property + def checkpoint_manager_snapshot_path(self) -> str: + """The path to the checkpoint manager snapshot file.""" + return Path( + self.experiment_fs_path, CHECKPOINT_MANAGER_SNAPSHOT_FILENAME + ).as_posix() + + @staticmethod + def get_experiment_dir_name(run_obj: Union[str, Callable, Type]) -> str: + from ray.tune.experiment import Experiment + + run_identifier = Experiment.get_trainable_name(run_obj) + + if bool(int(os.environ.get("TUNE_DISABLE_DATED_SUBDIR", 0))): + dir_name = run_identifier + else: + dir_name = "{}_{}".format(run_identifier, date_str()) + return dir_name + + @staticmethod + def make_default_checkpoint_dir_name(): + """Get the name of the checkpoint directory by timestamp.""" + return f"checkpoint_{date_str(include_ms=True)}" + + def extract_checkpoint_dir_name_from_path(self, checkpoint_path: str) -> str: + """Get the checkpoint name from the checkpoint path. + The parent directory of the checkpoint path should be the experiment directory. + """ + # TODO: Use Pathlib to extract the name when supports at least Python 3.9 + experiment_fs_path = self.experiment_fs_path + "/" + if not checkpoint_path.startswith(experiment_fs_path): + raise ValueError( + f"Checkpoint path {checkpoint_path} is not under the experiment " + f"directory {self.experiment_fs_path}." + ) + return checkpoint_path[len(experiment_fs_path) :] + + def build_checkpoint_path_from_name(self, checkpoint_name: str) -> str: + """Get the checkpoint path from the checkpoint name. + The parent directory of the checkpoint path should be the experiment directory. + """ + return Path(self.experiment_fs_path, checkpoint_name).as_posix() diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e7ebee0047663b8ac783ace47f9569f3baa88e4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__init__.py @@ -0,0 +1,16 @@ +from .poll import WorkerGroupPollStatus, WorkerStatus +from .state import WorkerGroupState, WorkerGroupStateBuilder +from .worker import ActorMetadata, RayTrainWorker, Worker +from .worker_group import WorkerGroup, WorkerGroupContext + +__all__ = [ + "ActorMetadata", + "RayTrainWorker", + "Worker", + "WorkerGroup", + "WorkerGroupContext", + "WorkerGroupPollStatus", + "WorkerGroupState", + "WorkerGroupStateBuilder", + "WorkerStatus", +] diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e51d1f2a17f42ab7241620ff1b5f963c0b2f5f8f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/poll.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/poll.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51134580d2e4a9d0257855d7512d42ef1953815f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/poll.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/state.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f3fb4c98c19c1304ddf99edd40b9f34ae346504 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/state.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/thread_runner.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/thread_runner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a6c88e91d0eb9784cddad736925e22241d3790d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/thread_runner.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/worker.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/worker.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad458aed77e8ea3e2c8b1d7391fd5ceb6a7fc4c1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/worker.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/worker_group.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/worker_group.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f031519ba642a26125542f634a9e5f25a8103b02 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/__pycache__/worker_group.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/poll.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/poll.py new file mode 100644 index 0000000000000000000000000000000000000000..5bc219567521797ebaa30c937226e48d7a44f2c5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/poll.py @@ -0,0 +1,49 @@ +from dataclasses import dataclass +from typing import Dict, Optional + +from ray.train._internal.session import _TrainingResult +from ray.types import ObjectRef + + +@dataclass +class WorkerStatus: + running: bool + error: Optional[Exception] = None + training_result: Optional[_TrainingResult] = None + + +@dataclass(frozen=True) +class WorkerGroupPollStatus: + worker_statuses: Dict[int, WorkerStatus] + + @property + def errors(self) -> Dict[int, Exception]: + return { + world_rank: status.error + for world_rank, status in self.worker_statuses.items() + if status.error is not None + } + + @property + def finished(self) -> bool: + return self.worker_statuses and all( + not status.running for status in self.worker_statuses.values() + ) + + def get_error_string(self) -> str: + return "\n".join( + f"[Rank {world_rank}]\n{error}" for world_rank, error in self.errors.items() + ) + + +@dataclass(frozen=True) +class PollTask: + """Represents a poll task for a worker. + + Attributes: + start_time: The time when the poll task was started. + task: The ObjectRef representing the poll task. + """ + + start_time: float + task: ObjectRef diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/state.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/state.py new file mode 100644 index 0000000000000000000000000000000000000000..4992027fcb133e4a5e18efa62612dbc373cbba39 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/state.py @@ -0,0 +1,135 @@ +import logging +from dataclasses import dataclass +from typing import List + +import ray +from ray.actor import ActorHandle +from ray.train.v2._internal.execution.checkpoint.sync_actor import SynchronizationActor +from ray.train.v2._internal.execution.worker_group.worker import Worker +from ray.train.v2._internal.util import time_monotonic +from ray.util.placement_group import PlacementGroup, remove_placement_group + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class WorkerGroupState: + """Ongoing state of an active worker group. + + Attributes: + start_time: The time when the worker group was started. + workers: The workers in the worker group. + These should always be in sorted order by world rank. + placement_group: The placement group for the worker group. + sync_actor: The synchronization actor for the worker group. + """ + + start_time: float + placement_group: PlacementGroup + workers: List[Worker] + sync_actor: ActorHandle + + @property + def num_workers(self) -> int: + return len(self.workers) + + def shutdown(self): + _shutdown_workers(self.workers) + _shutdown_placement_group(self.placement_group) + _shutdown_sync_actor(self.sync_actor) + + +class WorkerGroupStateBuilder: + """Builder for WorkerGroupState. + + Example usage: + ```python + builder = WorkerGroupStateBuilder() + builder.with_placement_group(placement_group) + builder.with_workers(workers) + builder.with_sync_actor(sync_actor) + state = builder.build() + + builder.shutdown(patience_s=10) + ``` + """ + + def __init__(self): + self.placement_group = None + self.workers = None + self.sync_actor = None + + def with_placement_group( + self, placement_group: PlacementGroup + ) -> "WorkerGroupStateBuilder": + self.placement_group = placement_group + return self + + def with_workers(self, workers: List[Worker]) -> "WorkerGroupStateBuilder": + self.workers = workers + return self + + def with_sync_actor( + self, sync_actor: SynchronizationActor + ) -> "WorkerGroupStateBuilder": + self.sync_actor = sync_actor + return self + + def build(self) -> WorkerGroupState: + required_attrs = { + "placement_group": self.placement_group, + "workers": self.workers, + "sync_actor": self.sync_actor, + } + missing = [name for name, attr in required_attrs.items() if attr is None] + if missing: + raise ValueError( + f"Cannot build incomplete state. Missing: {', '.join(missing)}" + ) + return WorkerGroupState( + start_time=time_monotonic(), + placement_group=self.placement_group, + workers=self.workers, + sync_actor=self.sync_actor, + ) + + def shutdown(self): + if self.workers: + _shutdown_workers(self.workers) + self.workers = None + if self.placement_group: + _shutdown_placement_group(self.placement_group) + self.placement_group = None + if self.sync_actor: + _shutdown_sync_actor(self.sync_actor) + self.sync_actor = None + + +def _shutdown_workers(workers: List[Worker], patience_s: float = 5): + # Run the worker shutdown logic on each of the workers. This should + # be a non-blocking call to realize forceful shutdown after patience_s. + _ = [w.actor.shutdown.remote() for w in workers] + + logger.debug(f"Shutting down {len(workers)} workers.") + if patience_s <= 0: + for worker in workers: + ray.kill(worker.actor) + else: + done_refs = [w.actor.__ray_terminate__.remote() for w in workers] + # Wait for actors to die gracefully. + _, not_done = ray.wait( + done_refs, num_returns=len(done_refs), timeout=patience_s + ) + if not_done: + logger.debug("Graceful termination failed. Falling back to force kill.") + # If all actors are not able to die gracefully, then kill them. + for worker in workers: + ray.kill(worker.actor) + + +def _shutdown_sync_actor(sync_actor: SynchronizationActor): + ray.kill(sync_actor) + + +def _shutdown_placement_group(placement_group: PlacementGroup): + remove_placement_group(placement_group) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/thread_runner.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/thread_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..ef19e66583d451ff1773a196db91cd007b1e5331 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/thread_runner.py @@ -0,0 +1,82 @@ +import logging +import threading +import traceback +from typing import Callable, Optional, TypeVar + +from ray.train.v2._internal.exceptions import UserExceptionWithTraceback +from ray.train.v2._internal.util import get_callable_name + +T = TypeVar("T") + +logger = logging.getLogger(__name__) + + +class ThreadRunner: + """Utility to run a user function as a thread and capture its return value + or exception. + """ + + def __init__(self): + self._ret: Optional[T] = None + self._exc: Optional[UserExceptionWithTraceback] = None + + self._thread: Optional[threading.Thread] = None + self._lock = threading.Lock() + + self._is_running = False + + def run(self, target: Callable[[], T]) -> None: + if self._thread is not None: + raise RuntimeError("Thread is already running.") + + def _run_target(): + with self._lock: + self._is_running = True + + try: + result = target() + with self._lock: + self._ret = result + except BaseException as e: + with self._lock: + # Exclude the first 2 frames from the traceback, which are + # the `ThreadRunner._run_target` and `construct_train_func` calls. + # TODO(justinvyu): This is brittle and may break if the call stack + # changes. Figure out a more robust way to exclude these frames. + exc_traceback_str = traceback.format_exc( + limit=-(len(traceback.extract_tb(e.__traceback__)) - 2) + ) + logger.error(f"Error in training function:\n{exc_traceback_str}") + self._exc = UserExceptionWithTraceback( + e, traceback_str=exc_traceback_str + ) + + with self._lock: + self._is_running = False + + self._thread = threading.Thread( + target=_run_target, + daemon=True, + name=f"TrainingThread({get_callable_name(target)})", + ) + self._thread.start() + + def is_running(self) -> bool: + with self._lock: + return self._is_running + + def get_error(self) -> Optional[BaseException]: + with self._lock: + return self._exc + + def get_return_value(self) -> Optional[T]: + with self._lock: + return self._ret + + def join(self, timeout: Optional[float] = None) -> T: + if self._thread is None: + raise RuntimeError("Must call `run` before trying to `join`.") + + self._thread.join(timeout=timeout) + + return self.get_return_value() diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/worker.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..93e055c168710cb129958adc964291f10c3b651f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/worker.py @@ -0,0 +1,223 @@ +import logging +import os +import queue +import socket +from dataclasses import dataclass +from functools import cached_property +from typing import Callable, Dict, List, Optional, TypeVar, Union + +import ray +import ray._private.ray_constants as ray_constants +from .thread_runner import ThreadRunner +from ray.actor import ActorHandle +from ray.data.iterator import DataIterator +from ray.train import Checkpoint +from ray.train.v2._internal.constants import ( + DEFAULT_ENABLE_WORKER_LOGGING, + ENABLE_WORKER_STRUCTURED_LOGGING_ENV_VAR, +) +from ray.train.v2._internal.execution.callback import ( + TrainContextCallback, + WorkerCallback, +) +from ray.train.v2._internal.execution.checkpoint.sync_actor import SynchronizationActor +from ray.train.v2._internal.execution.context import ( + DistributedContext, + ExecutionContext, + TrainContext, + TrainRunContext, + get_train_context, + set_train_context, +) +from ray.train.v2._internal.execution.storage import StorageContext +from ray.train.v2._internal.execution.worker_group.poll import WorkerStatus +from ray.train.v2._internal.logging.logging import configure_worker_logger +from ray.train.v2._internal.logging.patch_print import patch_print_function +from ray.train.v2._internal.util import ObjectRefWrapper +from ray.types import ObjectRef + +T = TypeVar("T") + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class ActorMetadata: + hostname: str + node_id: str + node_ip: str + pid: int + accelerator_ids: Dict[str, List[Union[int, str]]] + + @property + def gpu_ids(self) -> List[Union[int, str]]: + return self.accelerator_ids.get("GPU", []) + + @cached_property + def _repr(self) -> str: + indent = " " + repr_lines = [ + "ActorMetadata(", + f"{indent}hostname={repr(self.hostname)},", + f"{indent}node_id={repr(self.node_id)},", + f"{indent}node_ip={repr(self.node_ip)},", + f"{indent}pid={repr(self.pid)},", + ] + non_empty_accelerator_ids = {k: v for k, v in self.accelerator_ids.items() if v} + if non_empty_accelerator_ids: + repr_lines.append(f"{indent}accelerator_ids={non_empty_accelerator_ids},") + + repr_lines.append(")") + return "\n".join(repr_lines) + + def __repr__(self) -> str: + return self._repr + + +@dataclass +class Worker: + actor: ActorHandle + metadata: ActorMetadata + resources: Dict[str, float] + distributed_context: Optional[DistributedContext] = None + log_file_path: Optional[str] = None + + @cached_property + def _repr(self) -> str: + indent = " " + metadata_repr = repr(self.metadata).replace("\n", f"\n{indent}") + context_repr = repr(self.distributed_context).replace("\n", f"\n{indent}") + + repr_lines = [ + "Worker(", + f"{indent}actor={repr(self.actor)},", + f"{indent}metadata={metadata_repr},", + f"{indent}distributed_context={context_repr},", + f"{indent}log_file_path={repr(self.log_file_path)},", + ")", + ] + return "\n".join(repr_lines) + + def __repr__(self) -> str: + return self._repr + + def execute_async(self, fn: Callable[..., T], *fn_args, **fn_kwargs) -> ObjectRef: + """Execute ``func`` on worker. + + Returns: + (ObjectRef) An ObjectRef representing the output of func. + + """ + return self.actor.execute.options(name=f"execute.{fn.__name__}").remote( + fn, *fn_args, **fn_kwargs + ) + + +class RayTrainWorker: + def __init__(self): + self._callbacks: List[WorkerCallback] = [] + + def execute(self, fn: Callable[..., T], *fn_args, **fn_kwargs) -> T: + return fn(*fn_args, **fn_kwargs) + + def run_train_fn(self, train_fn_ref: ObjectRefWrapper[Callable[[], None]]): + """Run the training function in a separate thread. + + This function should return immediately, freeing up the main actor thread + to perform other tasks such as polling the status. + """ + try: + train_fn = train_fn_ref.get() + except Exception as e: + logger.error(f"Error deserializing the training function: {e}") + raise + + # Create and start the training thread. + get_train_context().execution_context.training_thread_runner.run(train_fn) + + def get_metadata(self) -> ActorMetadata: + return ActorMetadata( + hostname=socket.gethostname(), + node_id=ray.get_runtime_context().get_node_id(), + node_ip=ray.util.get_node_ip_address(), + pid=os.getpid(), + accelerator_ids=ray.get_runtime_context().get_accelerator_ids(), + ) + + def poll_status(self) -> WorkerStatus: + execution_context = get_train_context().execution_context + + # TODO: We can implement two phase commit here. + # Only mark the task done when the result has been processed by the controller. + try: + training_result = execution_context.result_queue.get_nowait() + execution_context.result_queue.task_done() + except queue.Empty: + training_result = None + + error = execution_context.training_thread_runner.get_error() + + # TODO: The running state should not be conflated with queue flushing. + # Running should only be true if the user code is still running. + # This relies on `worker_group_status.finished` returning False + # until all training results have been flushed. + running = execution_context.training_thread_runner.is_running() or bool( + training_result + ) + + return WorkerStatus( + running=running, error=error, training_result=training_result + ) + + def shutdown(self): + """Shutdown the worker. + + This method is not doing the real shutdown, but it is used by the worker + group to signal the worker to stop running the training function. + Any shutdown worker callbacks can hook on this method to implement the + corresponding shutdown logic. Note that the shutdown logic needs to be + thread-safe if it is running in a separate thread. + """ + for callback in self._callbacks: + callback.before_worker_shutdown() + + def init_train_context( + self, + train_run_context: TrainRunContext, + distributed_context: DistributedContext, + synchronization_actor: SynchronizationActor, + storage_context: StorageContext, + worker_callbacks: List[Union[WorkerCallback, TrainContextCallback]], + dataset_shards: Dict[str, DataIterator] = None, + checkpoint: Optional[Checkpoint] = None, + ): + self._callbacks = [c for c in worker_callbacks if isinstance(c, WorkerCallback)] + context_callbacks_to_propagate = [ + c for c in worker_callbacks if isinstance(c, TrainContextCallback) + ] + context = TrainContext( + train_run_context=train_run_context, + distributed_context=distributed_context, + execution_context=ExecutionContext( + synchronization_actor=synchronization_actor, + # Make the queue size 1 to avoid building up too + # many unprocessed results. + result_queue=queue.Queue(maxsize=1), + training_thread_runner=ThreadRunner(), + train_context_callbacks=context_callbacks_to_propagate, + ), + storage_context=storage_context, + dataset_shards=dataset_shards or {}, + checkpoint=checkpoint, + ) + # Configure the train and root logger for the worker processes. + if ray_constants.env_bool( + ENABLE_WORKER_STRUCTURED_LOGGING_ENV_VAR, DEFAULT_ENABLE_WORKER_LOGGING + ): + configure_worker_logger(context) + patch_print_function() + # Set the train context global variable for the worker. + set_train_context(context) + + for callback in self._callbacks: + callback.after_init_train_context() diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/worker_group.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/worker_group.py new file mode 100644 index 0000000000000000000000000000000000000000..e707c77b7d2fde27d130bfc67fa6a69f3cde2194 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/execution/worker_group/worker_group.py @@ -0,0 +1,804 @@ +import collections +import logging +import os +import traceback +from dataclasses import dataclass +from typing import Any, Callable, Dict, List, Optional, TypeVar, Union + +import ray +from ray._private.ray_constants import env_float +from ray.actor import ActorHandle +from ray.exceptions import GetTimeoutError, RayActorError +from ray.runtime_env import RuntimeEnv +from ray.train.v2._internal.constants import ( + DEFAULT_REPORT_BARRIER_TIMEOUT_S, + DEFAULT_REPORT_BARRIER_WARN_INTERVAL_S, + DEFAULT_WORKER_GROUP_START_TIMEOUT_S, + DEFAULT_WORKER_HEALTH_CHECK_TIMEOUT_S, + REPORT_BARRIER_TIMEOUT_S_ENV_VAR, + REPORT_BARRIER_WARN_INTERVAL_S_ENV_VAR, + WORKER_GROUP_START_TIMEOUT_S_ENV_VAR, + WORKER_HEALTH_CHECK_TIMEOUT_S_ENV_VAR, + get_env_vars_to_propagate, +) +from ray.train.v2._internal.exceptions import ( + WorkerGroupStartupFailedError, + WorkerGroupStartupTimeoutError, + WorkerHealthCheckFailedError, + WorkerHealthCheckTimeoutError, +) +from ray.train.v2._internal.execution.callback import ( + TrainContextCallback, + WorkerCallback, + WorkerGroupCallback, +) +from ray.train.v2._internal.execution.checkpoint.sync_actor import SynchronizationActor +from ray.train.v2._internal.execution.context import ( + DistributedContext, + StorageContext, + TrainRunContext, +) +from ray.train.v2._internal.execution.worker_group.poll import ( + PollTask, + WorkerGroupPollStatus, +) +from ray.train.v2._internal.execution.worker_group.state import ( + WorkerGroupState, + WorkerGroupStateBuilder, +) +from ray.train.v2._internal.execution.worker_group.worker import ( + RayTrainWorker, + Worker, + WorkerStatus, +) +from ray.train.v2._internal.logging.logging import get_train_application_worker_log_path +from ray.train.v2._internal.util import ( + ObjectRefWrapper, + bundle_to_remote_args, + invoke_context_managers, + ray_get_safe, + time_monotonic, +) +from ray.types import ObjectRef +from ray.util.placement_group import ( + PlacementGroup, + placement_group, + remove_placement_group, +) +from ray.util.scheduling_strategies import ( + NodeAffinitySchedulingStrategy, + PlacementGroupSchedulingStrategy, +) + +logger = logging.getLogger(__name__) + +T = TypeVar("T") + + +@dataclass(frozen=True) +class WorkerGroupContext: + """Context for a worker group. + + This stores the context that is shared when starting a worker group. + + Attributes: + run_attempt_id: The ID of the run attempt. + train_fn_ref: An object store reference to the training function to execute. + num_workers: The number of workers in the worker group. + resources_per_worker: The resources per worker. + placement_strategy: Strategy for placing workers. + """ + + run_attempt_id: str + train_fn_ref: ObjectRefWrapper[Callable[[], None]] + num_workers: int + resources_per_worker: Dict[str, float] + placement_strategy: str = "PACK" + + +class WorkerGroup: + _worker_cls = RayTrainWorker + + @classmethod + def create( + cls, + train_run_context: TrainRunContext, + worker_group_context: WorkerGroupContext, + callbacks: Optional[ + List[Union[WorkerGroupCallback, WorkerCallback, TrainContextCallback]] + ] = None, + ) -> "WorkerGroup": + """Create and start a new worker group. + + Args: + train_run_context: The training run context. + worker_group_context: The worker group context. + callbacks: Optional callbacks to attach. + + Returns: + An active WorkerGroup instance. + + Raises: + WorkerGroupStartupTimeoutError: If worker group startup times out. + WorkerGroupStartupFailedError: If worker group fails to start. + """ + + worker_group = cls(train_run_context, worker_group_context, callbacks) + worker_group._start() + return worker_group + + def __init__( + self, + train_run_context: TrainRunContext, + worker_group_context: WorkerGroupContext, + callbacks: Optional[ + List[Union[WorkerGroupCallback, WorkerCallback, TrainContextCallback]] + ] = None, + ): + """Initialize a WorkerGroup instance. + + Note: This should not be called directly. Use WorkerGroup.create() instead. + """ + self._train_run_context = train_run_context + run_config = self._train_run_context.run_config + self._storage_context = StorageContext( + storage_path=run_config.storage_path, + experiment_dir_name=run_config.name, + storage_filesystem=run_config.storage_filesystem, + ) + + self._worker_group_context: WorkerGroupContext = worker_group_context + + callbacks = callbacks or [] + # Group of callbacks that are specific to worker group itself. + self._callbacks = [c for c in callbacks if isinstance(c, WorkerGroupCallback)] + # Group of callbacks that will be propagated and called on the worker actors. + self._worker_callbacks_to_propagate = [ + c + for c in callbacks + if isinstance(c, (WorkerCallback, TrainContextCallback)) + ] + + self._worker_group_state: Optional[WorkerGroupState] = None + # Maps world rank to the ongoing poll task. + self._world_rank_to_ongoing_poll: Dict[int, PollTask] = {} + self._latest_poll_status: Optional[WorkerGroupPollStatus] = None + # Environment variables + self._worker_group_start_timeout_s = float( + os.environ.get( + WORKER_GROUP_START_TIMEOUT_S_ENV_VAR, + DEFAULT_WORKER_GROUP_START_TIMEOUT_S, + ) + ) + self._worker_health_check_timeout_s = float( + os.getenv( + WORKER_HEALTH_CHECK_TIMEOUT_S_ENV_VAR, + DEFAULT_WORKER_HEALTH_CHECK_TIMEOUT_S, + ) + ) + self._report_barrier_timeout_s = env_float( + REPORT_BARRIER_TIMEOUT_S_ENV_VAR, DEFAULT_REPORT_BARRIER_TIMEOUT_S + ) + self._report_barrier_warn_interval_s = env_float( + REPORT_BARRIER_WARN_INTERVAL_S_ENV_VAR, + DEFAULT_REPORT_BARRIER_WARN_INTERVAL_S, + ) + + ################################################################################ + # Start Worker Group + ################################################################################ + + def _start( + self, + ): + """Internal method to start the worker group.""" + + worker_group_state_builder = WorkerGroupStateBuilder() + + try: + self._start_impl( + worker_group_state_builder, + ) + except Exception as e: + if not self.has_started(): + # Clean up partial worker group state. + worker_group_state_builder.shutdown() + raise e + + assert self.has_started(), "Worker group failed to start." + + def _start_impl( + self, + worker_group_state_builder: WorkerGroupStateBuilder, + ): + """Implementation of worker group startup. + + Args: + worker_group_state_builder: Builder for constructing worker group state. + + Raises: + ValueError: If workers are already started. + WorkerGroupStartupTimeoutError: If startup times out requesting resources. + WorkerGroupStartupFailedError: If workers fail during initialization. + """ + self._assert_inactive() + worker_group_context = self._worker_group_context + + # TODO: Review the order of `on_xyz_start` and `after_xyz_start` callbacks. + # The current execution order is as follows:`on_worker_group_start` callbacks + # are triggered before the `after_worker_group_start` callbacks. + with invoke_context_managers( + [callback.on_worker_group_start for callback in self._callbacks] + ): + for callback in self._callbacks: + callback.before_worker_group_start(worker_group_context) + + pg = placement_group( + bundles=[worker_group_context.resources_per_worker] + * worker_group_context.num_workers, + strategy=worker_group_context.placement_strategy, + ) + logger.info( + f"Attempting to start training worker group of size {worker_group_context.num_workers} with " + f"the following resources: [{worker_group_context.resources_per_worker}] * {worker_group_context.num_workers}" + ) + + # Wait for the placement group to be ready before proceeding + # to create actors. + # This could hang if the resources are not available, so we should + # time out if this hangs for a while to try again with a different size. + # For example, the controller may try to set a worker group size + # based on stale information about cluster resources. + try: + ray.get(pg.ready(), timeout=self._worker_group_start_timeout_s) + except GetTimeoutError as timeout_exc: + remove_placement_group(pg) + raise WorkerGroupStartupTimeoutError( + num_workers=worker_group_context.num_workers + ) from timeout_exc + + # TODO: Figure out ordering between these different calls/callbacks. + worker_group_state_builder.with_placement_group(pg) + + # Initialize the synchronization actor on the driver node + sync_actor = SynchronizationActor.options( + scheduling_strategy=NodeAffinitySchedulingStrategy( + node_id=ray.get_runtime_context().get_node_id(), + soft=False, + ) + ).remote( + timeout_s=self._report_barrier_timeout_s, + warn_interval_s=self._report_barrier_warn_interval_s, + ) + worker_group_state_builder.with_sync_actor(sync_actor) + + workers = self._create_workers( + worker_group_context.num_workers, + pg, + worker_group_context.resources_per_worker, + ) + worker_group_state_builder.with_workers(workers) + + # All the ray.get calls in this try block can possibly error if the + # worker actors die during initialization. + # To prevent the driver from crashing, catch all `RayActorError`s and + # raise a specially handled error to the controller. + try: + train_context_args = {} + for callable in self._callbacks: + args = callable.before_init_train_context(workers) + for arg, arg_values in args.items(): + assert len(arg_values) == worker_group_context.num_workers, ( + f"Callback {callable} returned {arg} with " + f"{len(arg_values)} values, expected {worker_group_context.num_workers}." + ) + assert ( + arg not in train_context_args + ), f"Callback {callable} returned {arg} which is already set." + train_context_args[arg] = arg_values + + self._init_train_context_on_workers( + workers, sync_actor, train_context_args + ) + + self._worker_group_state = worker_group_state_builder.build() + + for callback in self._callbacks: + callback.after_worker_group_start(self) + + except RayActorError as actor_error: + error_msg = "At least one of the worker actors failed to initialize." + raise WorkerGroupStartupFailedError(error_msg) from actor_error + + # Launch the training function on each worker. + # This task should start a worker thread and return immediately. + ray_get_safe( + [ + worker.actor.run_train_fn.remote(worker_group_context.train_fn_ref) + for worker in workers + ] + ) + + workers_info = "\n".join( + [ + f"- (ip={w.metadata.node_ip}, pid={w.metadata.pid}) " + f"world_rank={w.distributed_context.world_rank}, " + f"local_rank={w.distributed_context.local_rank}, " + f"node_rank={w.distributed_context.node_rank}" + for w in workers + ] + ) + logger.info( + f"Started training worker group of size {len(workers)}: \n{workers_info}" + ) + + for callback in self._callbacks: + callback.after_worker_group_training_start(self) + + def _create_workers( + self, + num_workers: int, + placement_group: PlacementGroup, + resources_per_worker: Dict[str, float], + ) -> List[Worker]: + + runtime_env = self._get_worker_runtime_env( + custom_runtime_env=self._train_run_context.run_config.worker_runtime_env + ) + worker_actor_cls = ray.remote( + runtime_env=runtime_env, + **bundle_to_remote_args(resources_per_worker), + )(self._worker_cls) + + actors = [ + worker_actor_cls.options( + scheduling_strategy=PlacementGroupSchedulingStrategy( + placement_group=placement_group, placement_group_bundle_index=i + ), + ).remote() + for i in range(num_workers) + ] + + try: + actor_metadatas = ray_get_safe( + [actor.get_metadata.remote() for actor in actors] + ) + except RayActorError as actor_error: + for actor in actors: + ray.kill(actor) + + error_msg = ( + "One of the worker actors failed to initialize due to error:\n" + f"{traceback.format_exc()}" + ) + raise WorkerGroupStartupFailedError(error_msg) from actor_error + + workers = [ + Worker(actor, meta, resources_per_worker) + for actor, meta in zip(actors, actor_metadatas) + ] + return WorkerGroup._assign_worker_ranks(workers) + + def _init_train_context_on_workers( + self, + workers: List[Worker], + sync_actor: ActorHandle, + train_context_args: Dict[str, List[Any]], + ) -> None: + context_init_tasks = [ + worker.actor.init_train_context.remote( + train_run_context=self._train_run_context, + distributed_context=worker.distributed_context, + synchronization_actor=sync_actor, + storage_context=self._storage_context, + worker_callbacks=self._worker_callbacks_to_propagate, + **{ + arg: arg_values[i] for arg, arg_values in train_context_args.items() + }, + ) + for i, worker in enumerate(workers) + ] + ray_get_safe(context_init_tasks) + + self._decorate_worker_log_file_paths(workers) + + ##################################################################################### + # Shutdown Worker Group + ##################################################################################### + + def shutdown(self): + """Shutdown all the workers in this worker group.""" + self._assert_active() + + with invoke_context_managers( + [callback.on_worker_group_shutdown for callback in self._callbacks] + ): + if self.has_started(): + for callback in self._callbacks: + callback.before_worker_group_shutdown(self) + + self._worker_group_state.shutdown() + + self._clear_state() + + logger.debug("Worker group shutdown successful.") + + def _clear_state(self): + self._worker_group_state = None + self._world_rank_to_ongoing_poll = {} + + def abort(self): + """Abort the worker group.""" + # TODO: consider shutting down the workers in the future. + # We don't do this for now due to this risk of hanging e.g. when calling + # `destroy_process_group` on an active group. + self._assert_active() + for callback in self._callbacks: + callback.before_worker_group_abort(self._worker_group_context) + + ##################################################################################### + # Polling Worker Group + ##################################################################################### + + def poll_status(self, timeout: Optional[float] = None) -> WorkerGroupPollStatus: + """Poll the status of all workers in the worker group. + + Args: + timeout: The maximum time to wait for the poll tasks to complete. + """ + self._assert_active() + + poll_results = self._poll_workers_and_collect_errors(timeout) + + worker_group_poll_status = WorkerGroupPollStatus( + worker_statuses=dict(enumerate(poll_results)), + ) + + for callback in self._callbacks: + callback.after_worker_group_poll_status(worker_group_poll_status) + + self._latest_poll_status = worker_group_poll_status + return worker_group_poll_status + + def _poll_workers_and_collect_errors( + self, timeout: Optional[float] + ) -> List[WorkerStatus]: + """Launch poll tasks on each worker and collect the results. + + The poll task should involve very little computation and should + return almost immediately. + + If a worker does not return the result of the poll task within + the timeout, it is considered as a missed health check. + The timeout is set to ~seconds, so a missed health check usually + means that something is wrong with the worker. + Subsequent calls to poll the worker will continue waiting on the + hanging poll task. + + If a worker's health check hangs for too long, it is marked as dead + and a WorkerHealthCheckTimeoutError is propagated as the error in the + worker status for the controller to handle. + + If a worker's poll task fails, a WorkerHealthCheckFailedError is similarly + propagated in the worker status. + + Returns: + poll_results: A list of WorkerStatus objects. + If polling a certain worker hangs or fails, the corresponding + WorkerStatus object will include a system error mentioned above. + """ + workers = self.get_workers() + start_time = time_monotonic() + poll_tasks = self._get_poll_tasks() + poll_task_to_world_rank = { + poll_task: i for i, poll_task in enumerate(poll_tasks) + } + done_polls, hanging_polls = ray.wait( + list(poll_task_to_world_rank), + num_returns=len(poll_task_to_world_rank), + timeout=timeout, + ) + + poll_task_to_result = {} + + for hanging_poll in hanging_polls: + hanging_rank = poll_task_to_world_rank[hanging_poll] + + # The hanging poll task should be saved and awaited in the next round. + # Save the start time of the poll task to check for timeouts. + # Don't overwrite the ongoing poll task if it already exists. + ongoing_poll = self._world_rank_to_ongoing_poll.setdefault( + hanging_rank, PollTask(start_time, hanging_poll) + ) + + error = None + elapsed_time_s = time_monotonic() - ongoing_poll.start_time + if elapsed_time_s > self._worker_health_check_timeout_s: + error_msg = ( + f"A worker health check has been hanging for {elapsed_time_s:.2f} " + "seconds. Marking the worker as dead.\n" + f"Worker info: {workers[hanging_rank]}" + ) + error = WorkerHealthCheckTimeoutError(error_msg) + + poll_task_to_result[hanging_poll] = WorkerStatus( + running=True, error=error, training_result=None + ) + + for done_poll in done_polls: + done_rank = poll_task_to_world_rank[done_poll] + + # Remove the ongoing poll task for the worker. + self._world_rank_to_ongoing_poll.pop(done_rank, None) + + try: + poll_result: WorkerStatus = ray.get(done_poll) + except Exception as e: + error_msg = ( + "A worker health check failed.\n" + f"Worker info: {workers[done_rank]}" + ) + poll_result = WorkerStatus( + running=False, + error=WorkerHealthCheckFailedError(error_msg, failure=e), + training_result=None, + ) + + poll_task_to_result[done_poll] = poll_result + + # Collect the results and errors in the order of the workers. + results = [ + poll_task_to_result.get(poll_task) for poll_task in poll_task_to_world_rank + ] + return results + + def _get_poll_tasks(self) -> List[ObjectRef]: + """Get the poll tasks for each worker. + + If there is an ongoing poll task for a worker that did not finish + in the timeout on the previous round, return that task instead of + queueing up a new one. + + Spawns a new poll task for the worker if there is no ongoing poll task. + """ + workers = self.get_workers() + poll_tasks = [] + for i, worker in enumerate(workers): + if i in self._world_rank_to_ongoing_poll: + ongoing_poll = self._world_rank_to_ongoing_poll[i] + poll_tasks.append(ongoing_poll.task) + else: + poll_tasks.append(worker.actor.poll_status.remote()) + return poll_tasks + + ##################################################################################### + # Execution Methods + ##################################################################################### + + def execute_async(self, fn: Callable, *fn_args, **fn_kwargs) -> List[ObjectRef]: + """Execute ``func`` on each worker and return the futures. + + Returns: + (List[ObjectRef]) A list of ``ObjectRef`` representing the + output of ``func`` from each worker. The order is the same + as ``self.workers``. + + """ + self._assert_active() + workers = self.get_workers() + + return [worker.execute_async(fn, *fn_args, **fn_kwargs) for worker in workers] + + def execute(self, fn: Callable[..., T], *fn_args, **fn_kwargs) -> List[T]: + """Execute ``func`` on each worker and return the outputs of ``func``. + + Returns: + (List[T]) A list containing the output of ``func`` from each + worker. The order is the same as ``self.workers``. + + """ + return ray_get_safe(self.execute_async(fn, *fn_args, **fn_kwargs)) + + def execute_single_async( + self, rank: int, fn: Callable[..., T], *fn_args, **fn_kwargs + ) -> ObjectRef: + """Execute ``func`` on worker with ``rank`` and return futures. + + Returns: + (ObjectRef) An ObjectRef representing the output of func. + + """ + self._assert_active() + workers = self.get_workers() + + if rank >= len(workers): + raise ValueError( + f"The provided {rank=} is " f"not valid for {len(workers)} workers." + ) + + return workers[rank].execute_async(fn, *fn_args, **fn_kwargs) + + def execute_single( + self, rank: int, fn: Callable[..., T], *fn_args, **fn_kwargs + ) -> T: + """Execute ``func`` on worker with ``rank``. + + Returns: + (T) The output of func. + + """ + return ray.get(self.execute_single_async(rank, fn, *fn_args, **fn_kwargs)) + + ##################################################################################### + # Utility Methods + ##################################################################################### + + def has_started(self) -> bool: + return self._worker_group_state is not None + + def _assert_active(self): + """Assert that the worker group is active (not shut down).""" + if not self.has_started(): + raise ValueError( + "Worker group is not active. " + "Call WorkerGroup.create() to create a new worker group." + ) + + def _assert_inactive(self): + """Assert that the worker group is inactive (shut down).""" + if self.has_started(): + raise ValueError( + "Worker group is active. " + "Call WorkerGroup.shutdown() to shut down the worker group." + ) + + def get_workers(self) -> List[Worker]: + self._assert_active() + return self._worker_group_state.workers + + def get_worker_group_context(self) -> WorkerGroupContext: + return self._worker_group_context + + def get_worker_group_state(self) -> WorkerGroupState: + self._assert_active() + return self._worker_group_state + + def get_latest_poll_status(self) -> Optional[WorkerGroupPollStatus]: + self._assert_active() + return self._latest_poll_status + + def __len__(self) -> int: + self._assert_active() + return len(self.get_workers()) + + ######################################################################################### + # Static Utility Methods + ######################################################################################### + + @staticmethod + def _assign_worker_ranks(workers: List[Worker]) -> List[Worker]: + """Assign world ranks to workers by increasing node id and GPU id. + + Initializes the `DistributedContext` for each worker. + + Returns: + workers: Workers sorted by increasing world rank, + with the `DistributedContext` set. + """ + workers = WorkerGroup._sort_workers_by_node_id_and_gpu_id(workers) + + node_ip_to_workers = collections.defaultdict(list) + for worker in workers: + node_ip_to_workers[worker.metadata.node_ip].append(worker) + node_ips = list(node_ip_to_workers.keys()) + + for world_rank, worker in enumerate(workers): + distributed_context = DistributedContext( + local_rank=node_ip_to_workers[worker.metadata.node_ip].index(worker), + local_world_size=len(node_ip_to_workers[worker.metadata.node_ip]), + world_rank=world_rank, + world_size=len(workers), + node_rank=node_ips.index(worker.metadata.node_ip), + ) + worker.distributed_context = distributed_context + + return workers + + @staticmethod + def _decorate_worker_log_file_paths(workers: List[Worker]) -> List[Worker]: + """Decorate worker log file paths. + + Returns: + workers: Workers with log file paths set. + """ + # Execute all tasks in parallel and then get results + log_path_refs = [ + worker.execute_async(get_train_application_worker_log_path) + for worker in workers + ] + log_paths = ray_get_safe(log_path_refs) + + # Assign log paths to workers + for worker, log_path in zip(workers, log_paths): + worker.log_file_path = log_path + + return workers + + @staticmethod + def _sort_workers_by_node_id_and_gpu_id( + workers: List[Worker], _first_id: Optional[str] = None + ) -> List[Worker]: + """Reorder the workers by their node id and the lowest GPU id. + + Example: + Given workers with the following attributes: + worker_0: id=1, gpu_ids=[1] + worker_1: id=0, gpu_ids=[0] + worker_2: id=1, gpu_ids=[0] + worker_3: id=0, gpu_ids=[1] + + The function will perform the following steps: + 1. Group by node IP: + id=0: worker_1, worker_3 + id=1: worker_0, worker_2 + + 2. Sort each group by GPU ID: + id=0: worker_1 (gpu_id=0), worker_3 (gpu_id=1) + id=1: worker_2 (gpu_id=0), worker_0 (gpu_id=1) + + Resulting in the order: [worker_1, worker_3, worker_2, worker_0] + + Args: + _first_id: The first node id to group by. + """ + node_id_to_workers = collections.defaultdict(list) + + if _first_id is not None: + node_id_to_workers[_first_id] = [] + + for worker in workers: + node_id_to_workers[worker.metadata.node_id].append(worker) + + # Sort workers on the same node by the lowest GPU id + # More details: https://github.com/ray-project/ray/issues/40803 + def get_lowest_gpu_id(worker) -> int: + gpu_ids = worker.metadata.accelerator_ids.get("GPU", []) + # If there are no GPU IDs, return 0 as a default + if not gpu_ids: + return 0 + + # Attempt to convert GPU IDs to integers and find the minimum ID. + # Fallback to return the minimum string-based ID + try: + return min(int(gpu_id) for gpu_id in gpu_ids) + except ValueError: + return min(gpu_ids) + + for node_id in node_id_to_workers: + node_id_to_workers[node_id].sort(key=get_lowest_gpu_id) + + sorted_workers = [] + for workers in node_id_to_workers.values(): + sorted_workers.extend(workers) + return sorted_workers + + @staticmethod + def _get_worker_runtime_env( + custom_runtime_env: Union[Dict, RuntimeEnv], + ) -> Union[Dict, RuntimeEnv]: + """Update custom runtime env with internal Ray Train env vars + that should be propagated from the driver to worker processes. + + Args: + custom_runtime_env: The custom runtime env dict passed in by the user. + + Returns: + A copy of the custom runtime env dict updated with internal + Ray Train environment variables to propagate to worker processes. + """ + merged_env_vars = get_env_vars_to_propagate() + merged_env_vars.update(custom_runtime_env.get("env_vars", {})) + + runtime_env = dict(custom_runtime_env) + runtime_env["env_vars"] = merged_env_vars + return runtime_env diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1eb15d5d919d319c2297f114c57d8e8fc310c547 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/__pycache__/logging.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/__pycache__/logging.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c56503a30e5f7c1d461f816d095379f5e7533c09 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/__pycache__/logging.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/__pycache__/patch_print.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/__pycache__/patch_print.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a5e6f651b0d8a6bf28d09f51652c29d0ee1d2c8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/__pycache__/patch_print.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/logging.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..537f3ff2a60a86e1128dd02b2ecf5f0efd4c81e1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/logging.py @@ -0,0 +1,288 @@ +import logging.config +import os +from enum import Enum +from typing import Optional, Union + +import ray +from ray._private.log import PlainRayHandler +from ray._private.ray_logging.filters import CoreContextFilter +from ray._private.ray_logging.formatters import JSONFormatter +from ray.train.v2._internal.execution.context import TrainContext, TrainRunContext +from ray.train.v2._internal.util import get_module_name + + +def _get_base_logger_config_dict(context: Union[TrainRunContext, TrainContext]) -> dict: + """Return the base logging configuration dictionary.""" + # Using Ray worker ID as the file identifier where logs are written to. + file_identifier = ray.get_runtime_context().get_worker_id() + # Return the base logging configuration as a Python dictionary. + return { + "version": 1, + "disable_existing_loggers": False, + "formatters": { + "ray_json": {"class": get_module_name(JSONFormatter)}, + }, + "filters": { + "core_context_filter": {"()": CoreContextFilter}, + "train_context_filter": {"()": TrainContextFilter, "context": context}, + }, + "handlers": { + "console": {"class": get_module_name(PlainRayHandler)}, + "file_train_sys_controller": { + "class": get_module_name(SessionFileHandler), + "formatter": "ray_json", + "filename": f"ray-train-sys-controller-{file_identifier}.log", + "filters": ["core_context_filter", "train_context_filter"], + }, + "file_train_app_controller": { + "class": get_module_name(SessionFileHandler), + "formatter": "ray_json", + "filename": f"ray-train-app-controller-{file_identifier}.log", + "filters": ["core_context_filter", "train_context_filter"], + }, + "file_train_sys_worker": { + "class": get_module_name(SessionFileHandler), + "formatter": "ray_json", + "filename": f"ray-train-sys-worker-{file_identifier}.log", + "filters": ["core_context_filter", "train_context_filter"], + }, + "file_train_app_worker": { + "class": get_module_name(SessionFileHandler), + "formatter": "ray_json", + "filename": f"ray-train-app-worker-{file_identifier}.log", + "filters": ["core_context_filter", "train_context_filter"], + }, + }, + "loggers": {}, + } + + +def get_controller_logger_config_dict(context: TrainRunContext) -> dict: + """Return the controller logger configuration dictionary. + + On the controller process, only the `ray.train` logger is configured. + This logger emits logs to the following three locations: + - `file_train_sys_controller`: Ray Train system logs. + - `file_train_app_controller`: Ray Train application logs. + - `console`: Logs to the console. + """ + + config_dict = _get_base_logger_config_dict(context) + config_dict["loggers"]["ray.train"] = { + "level": "INFO", + "handlers": [ + "file_train_sys_controller", + "file_train_app_controller", + "console", + ], + "propagate": False, + } + return config_dict + + +def get_worker_logger_config_dict(context: TrainContext) -> dict: + """Return the worker loggers configuration dictionary. + + On the worker process, there are two loggers being configured: + + First, the `ray.train` logger is configured and emits logs to the + following three locations: + - `file_train_sys_worker`: Ray Train system logs. + - `file_train_app_worker`: Ray Train application logs. + - `console`: Logs to the console. + Second, the root logger is configured and emits logs to the following + two locations: + - `console`: Logs to the console. + - `file_train_app_worker`: Ray Train application logs. + The root logger will not emit Ray Train system logs and thus not writing to + `file_train_sys_worker` file handler. + """ + + config_dict = _get_base_logger_config_dict(context) + config_dict["loggers"]["ray.train"] = { + "level": "INFO", + "handlers": ["file_train_sys_worker", "file_train_app_worker", "console"], + "propagate": False, + } + config_dict["root"] = { + "level": "INFO", + "handlers": ["file_train_app_worker", "console"], + } + return config_dict + + +class TrainContextFilter(logging.Filter): + """Add Ray Train metadata to the log records. + + This filter is applied to Ray Train controller and worker processes. + """ + + # Log keys for Ray Train controller and worker processes. + class LogKey(str, Enum): + RUN_NAME = "run_name" + COMPONENT = "component" + WORLD_RANK = "world_rank" + LOCAL_RANK = "local_rank" + NODE_RANK = "node_rank" + + # Ray Train Component by process types + class TrainComponent(str, Enum): + CONTROLLER = "controller" + WORKER = "worker" + + def __init__(self, context: Union[TrainRunContext, TrainContext]): + self._is_worker: bool = isinstance(context, TrainContext) + if self._is_worker: + self._run_name: str = context.train_run_context.get_run_config().name + self._world_rank: int = context.get_world_rank() + self._local_rank: int = context.get_local_rank() + self._node_rank: int = context.get_node_rank() + self._component: str = TrainContextFilter.TrainComponent.WORKER + else: + self._run_name: str = context.get_run_config().name + self._component: str = TrainContextFilter.TrainComponent.CONTROLLER + + def controller_filter(self, record): + # Add the run_id and component to Ray Train controller processes. + setattr(record, TrainContextFilter.LogKey.RUN_NAME, self._run_name) + setattr(record, TrainContextFilter.LogKey.COMPONENT, self._component) + return True + + def worker_filter(self, record): + # Add the run_id and component to Ray Train worker processes. + setattr(record, TrainContextFilter.LogKey.RUN_NAME, self._run_name) + setattr(record, TrainContextFilter.LogKey.COMPONENT, self._component) + # Add all the rank related information to the log record for worker processes. + setattr(record, TrainContextFilter.LogKey.WORLD_RANK, self._world_rank) + setattr(record, TrainContextFilter.LogKey.LOCAL_RANK, self._local_rank) + setattr(record, TrainContextFilter.LogKey.NODE_RANK, self._node_rank) + return True + + def filter(self, record): + if self._is_worker: + return self.worker_filter(record) + else: + return self.controller_filter(record) + + +class SessionFileHandler(logging.Handler): + """A handler that writes to a log file in the Ray session directory. + + The Ray session directory isn't available until Ray is initialized, so any logs + emitted before Ray is initialized will be lost. + This handler will not create the file handler until you emit a log record. + + Args: + filename: The name of the log file. The file is created in the 'logs/train' + directory of the Ray session directory. + """ + + # TODO (hpguo): This handler class is shared by both Ray Train and ray data. We + # should move this to ray core and make it available to both libraries. + + def __init__(self, filename: str): + super().__init__() + self._filename = filename + self._handler = None + self._formatter = None + self._path = None + + def emit(self, record): + if self._handler is None: + self._try_create_handler() + if self._handler is not None: + self._handler.emit(record) + + def setFormatter(self, fmt: logging.Formatter) -> None: + if self._handler is not None: + self._handler.setFormatter(fmt) + self._formatter = fmt + + def get_log_file_path(self) -> Optional[str]: + if self._handler is None: + self._try_create_handler() + return self._path + + def _try_create_handler(self): + assert self._handler is None + + # Get the Ray Train log directory. If not in a Ray session, return. + # This handler will only be created within a Ray session. + log_directory = get_log_directory() + if log_directory is None: + return + + os.makedirs(log_directory, exist_ok=True) + + # Create the log file. + self._path = os.path.join(log_directory, self._filename) + self._handler = logging.FileHandler(self._path) + if self._formatter is not None: + self._handler.setFormatter(self._formatter) + + +def configure_controller_logger(context: TrainRunContext) -> None: + """ + Configure the logger on the controller process, which is the `ray.train` logger. + """ + config = get_controller_logger_config_dict(context) + logging.config.dictConfig(config) + # TODO: Return the controller log file path. + + +def configure_worker_logger(context: TrainContext) -> None: + """ + Configure the loggers on the worker process, which contains the + `ray.train` logger and the root logger. + """ + config = get_worker_logger_config_dict(context) + logging.config.dictConfig(config) + # TODO: Return the worker log file path. + + +def get_log_directory() -> Optional[str]: + """Return the directory where Ray Train writes log files. + + If not in a Ray session, return None. + + This path looks like: "/tmp/ray/session_xxx/logs/train/" + """ + global_node = ray._private.worker._global_node + + if global_node is None: + return None + + root_dir = global_node.get_session_dir_path() + return os.path.join(root_dir, "logs", "train") + + +def get_train_application_controller_log_path() -> Optional[str]: + """ + Return the path to the file train application controller log file. + """ + # TODO: This is a temporary solution. We should return the log file path in + # the `configure_controller_logger` function. + logger = logging.getLogger("ray.train") + for handler in logger.handlers: + if ( + isinstance(handler, SessionFileHandler) + and "ray-train-app-controller" in handler._filename + ): + return handler.get_log_file_path() + return None + + +def get_train_application_worker_log_path() -> Optional[str]: + """ + Return the path to the file train application worker log file. + """ + # TODO: This is a temporary solution. We should return the log file path in + # the `configure_worker_logger` function. + logger = logging.getLogger("ray.train") + for handler in logger.handlers: + if ( + isinstance(handler, SessionFileHandler) + and "ray-train-app-worker" in handler._filename + ): + return handler.get_log_file_path() + return None diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/patch_print.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/patch_print.py new file mode 100644 index 0000000000000000000000000000000000000000..2fe1d336380c0db002a3cec3d6eef7eec0063422 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/logging/patch_print.py @@ -0,0 +1,65 @@ +import builtins +import contextlib +import logging +import sys +from typing import Callable + +from ray._private.ray_constants import env_bool +from ray.train.v2._internal.constants import ( + DEFAULT_ENABLE_PRINT_PATCH, + ENABLE_PRINT_PATCH_ENV_VAR, +) + +# Save the original print function +_original_print = builtins.print + + +@contextlib.contextmanager +def print_context_manager(print_fn: Callable): + """Context manager to set the builtin print function as print_fn.""" + current_print = builtins.print + builtins.print = print_fn + yield + builtins.print = current_print + + +def redirected_print(*objects, sep=" ", end="\n", file=None, flush=False): + """Implement python's print function to redirect logs to Train's logger. + + If the file is set to anything other than stdout, stderr, or None, call the + builtin print. Else, construct the message and redirect to Train's logger. + + This makes sure that print to customized file in user defined function will not + be overwritten by the redirected print function. + + See https://docs.python.org/3/library/functions.html#print + """ + # TODO (hpguo): This handler class is shared by both ray train and ray serve. We + # should move this to ray core and make it available to both libraries. + + if file not in [sys.stdout, sys.stderr, None]: + return _original_print(objects, sep=sep, end=end, file=file, flush=flush) + + root_logger = logging.getLogger() + message = sep.join(map(str, objects)) + # Use the original `print` method for the scope of the logger call, in order to + # avoid infinite recursion errors if any exceptions get raised (since exception + # handling involves another `print(..., file=sys.stderr)`. + # Note that an exception being raised here is not expected (e.g. it would be a + # bug in our own logging code), so this is just to keep the error logs sane + # during development. + with print_context_manager(_original_print): + # We want this log to be associated with the line of code where user calls + # `print`, which is stacklevel 2. + # Frame [stacklevel]: + # User's call to print [2] -> `redirected_print` [1] -> root_logger.log [0] + root_logger.log(logging.INFO, message, stacklevel=2) + + +def patch_print_function() -> None: + """ + Patch the print function to redirect logs to Train's logger. + Only patch the print function if the environment variable is set to "1" + """ + if env_bool(ENABLE_PRINT_PATCH_ENV_VAR, DEFAULT_ENABLE_PRINT_PATCH): + builtins.print = redirected_print diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a93b4788cc5282ed6256184047a794d64864dc3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/base.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49379fe260283b470e5e243dfdae2ab407e6dee2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/controller.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/controller.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e37759d703b202a4b2a69534e8af40771d94283 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/controller.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/worker.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/worker.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26f135310a4ed5cf0770fd036fee111517ae4199 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/__pycache__/worker.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/base.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a6a70cc02f6f2d18380cf5b1fa8df84b6cd5be1f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/base.py @@ -0,0 +1,166 @@ +from abc import ABC, abstractmethod +from enum import Enum +from typing import Dict, Generic, Optional, Tuple, TypeVar + +from ray.util.metrics import Gauge + +RUN_NAME_TAG_KEY = "ray_train_run_name" +RUN_ID_TAG_KEY = "ray_train_run_id" + +T = TypeVar("T") +E = TypeVar("E", bound=Enum) + + +class Metric(ABC): + def __init__( + self, + name: str, + default: T, + description: str, + base_tags: Dict[str, str], + ): + """ + Initialize a new metric. + + Args: + name: The name of the metric. + default: The default value of the metric. + description: The description of the metric. + base_tags: The base tags for the metric. + """ + self._default = default + self._base_tags = base_tags + self._gauge = Gauge( + name, + description=description, + tag_keys=self._get_tag_keys(), + ) + + @abstractmethod + def record(self, value: T): + """Update the metric value. + + Args: + value: The value to update the metric with. + """ + pass + + @abstractmethod + def get_value(self) -> T: + """Get the value of the metric. + + Returns: + The value of the metric. If the metric has not been recorded, + the default value is returned. + """ + pass + + @abstractmethod + def reset(self): + """Reset values and clean up resources.""" + pass + + def _get_tag_keys(self) -> Tuple[str, ...]: + return tuple(self._base_tags.keys()) + + +class TimeMetric(Metric): + """A metric for tracking elapsed time.""" + + def __init__( + self, + name: str, + description: str, + base_tags: Dict[str, str], + ): + self._current_value = 0.0 + super().__init__( + name=name, + default=0.0, + description=description, + base_tags=base_tags, + ) + + def record(self, value: float): + """Update the time metric value by accumulating the time. + + Args: + value: The time value to increment the metric by. + """ + self._current_value += value + self._gauge.set(self._current_value, self._base_tags) + + def get_value(self) -> float: + return self._current_value + + def reset(self): + self._current_value = self._default + self._gauge.set(self._default, self._base_tags) + + +class EnumMetric(Metric, Generic[E]): + """A metric for tracking enum values.""" + + DEFAULT_VALUE = 0 + RECORDED_VALUE = 1 + + def __init__( + self, + name: str, + description: str, + base_tags: Dict[str, str], + enum_tag_key: str, + ): + self._enum_tag_key = enum_tag_key + self._current_value: Optional[E] = None + super().__init__( + name=name, + default=self.DEFAULT_VALUE, + description=description, + base_tags=base_tags, + ) + + def record(self, enum_value: E): + """Record a specific enum value. + + The metric will be reset to 0 for the previous value and set to 1 for the new value. + + Args: + enum_value: The enum value to record for. + """ + if enum_value == self._current_value: + return + + if self._current_value is not None: + previous_tags = self._get_tags(self._current_value) + self._gauge.set(self._default, previous_tags) + + current_tags = self._get_tags(enum_value) + self._gauge.set(self.RECORDED_VALUE, current_tags) + + self._current_value = enum_value + + def get_value(self, enum_value: E) -> int: + """Get the value for a specific enum value. + + Args: + enum_value: The enum value to get the value for + + Returns: + The value for the enum value + """ + return int(enum_value == self._current_value) + + def reset(self): + if self._current_value is not None: + tags = self._get_tags(self._current_value) + self._gauge.set(self._default, tags) + self._current_value = None + + def _get_tag_keys(self) -> Tuple[str, ...]: + return tuple(self._base_tags.keys()) + (self._enum_tag_key,) + + def _get_tags(self, enum_value: E) -> Dict[str, str]: + tags = self._base_tags.copy() + tags[self._enum_tag_key] = enum_value.name + return tags diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/controller.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..3f56d879890b0d6e28df2d0ea6a49d80d0faac9c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/controller.py @@ -0,0 +1,66 @@ +from typing import Dict, Union + +from ray.train.v2._internal.execution.controller.state import TrainControllerStateType +from ray.train.v2._internal.metrics.base import ( + RUN_ID_TAG_KEY, + RUN_NAME_TAG_KEY, + EnumMetric, + TimeMetric, +) + + +class ControllerMetrics: + """Factory for creating controller-specific metrics. + + This class defines all metrics used to track the state and performance of the + training controller. Each metric is defined with its name, type, default value, + description, and required tags. + """ + + # ===== Metric Names ===== + CONTROLLER_STATE = "train_controller_state" + WORKER_GROUP_START_TOTAL_TIME_S = "train_worker_group_start_total_time_s" + WORKER_GROUP_SHUTDOWN_TOTAL_TIME_S = "train_worker_group_shutdown_total_time_s" + + # ===== Tag Keys ===== + CONTROLLER_STATE_TAG_KEY = "ray_train_controller_state" + + @classmethod + def _create_time_metric( + cls, name: str, description: str, base_tags: Dict[str, str] + ) -> TimeMetric: + return TimeMetric( + name=name, + description=description, + base_tags=base_tags, + ) + + @classmethod + def _create_controller_state_metric( + cls, base_tags: Dict[str, str] + ) -> EnumMetric[TrainControllerStateType]: + return EnumMetric[TrainControllerStateType]( + name=cls.CONTROLLER_STATE, + description="Current state of the Ray Train controller", + base_tags=base_tags, + enum_tag_key=cls.CONTROLLER_STATE_TAG_KEY, + ) + + @classmethod + def get_controller_metrics( + cls, run_name: str, run_id: str + ) -> Dict[str, Union[TimeMetric, EnumMetric[TrainControllerStateType]]]: + base_tags = {RUN_NAME_TAG_KEY: run_name, RUN_ID_TAG_KEY: run_id} + return { + cls.WORKER_GROUP_START_TOTAL_TIME_S: cls._create_time_metric( + cls.WORKER_GROUP_START_TOTAL_TIME_S, + "Total time taken to start the worker group", + base_tags, + ), + cls.WORKER_GROUP_SHUTDOWN_TOTAL_TIME_S: cls._create_time_metric( + cls.WORKER_GROUP_SHUTDOWN_TOTAL_TIME_S, + "Total time taken to shutdown the worker group", + base_tags, + ), + cls.CONTROLLER_STATE: cls._create_controller_state_metric(base_tags), + } diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/worker.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..66edcbf5a2e3c540a570f8d741fe567ad8784d15 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/metrics/worker.py @@ -0,0 +1,52 @@ +from typing import Dict + +from ray.train.v2._internal.metrics.base import ( + RUN_ID_TAG_KEY, + RUN_NAME_TAG_KEY, + TimeMetric, +) + +WORKER_WORLD_RANK_TAG_KEY = "ray_train_worker_world_rank" +WORKER_ACTOR_ID_TAG_KEY = "ray_train_worker_actor_id" + + +class WorkerMetrics: + """Factory for creating worker-specific metrics. + + This class defines all metrics used to track the state and performance of the + training workers. Each metric is defined with its name, type, default value, + description, and required tags. + """ + + # ===== Metric Names ===== + REPORT_TOTAL_BLOCKED_TIME_S = "train_report_total_blocked_time_s" + + @classmethod + def _create_time_metric( + cls, name: str, description: str, base_tags: Dict[str, str] + ) -> TimeMetric: + """Create a time-based metric.""" + return TimeMetric( + name=name, + description=description, + base_tags=base_tags, + ) + + @classmethod + def get_worker_metrics( + cls, run_name: str, run_id: str, world_rank: int, worker_actor_id: str + ) -> Dict[str, TimeMetric]: + """Get all worker metrics.""" + base_tags = { + RUN_NAME_TAG_KEY: run_name, + RUN_ID_TAG_KEY: run_id, + WORKER_WORLD_RANK_TAG_KEY: str(world_rank), + WORKER_ACTOR_ID_TAG_KEY: worker_actor_id, + } + return { + cls.REPORT_TOTAL_BLOCKED_TIME_S: cls._create_time_metric( + cls.REPORT_TOTAL_BLOCKED_TIME_S, + "Cumulative time in seconds to report a checkpoint to the storage.", + base_tags, + ), + } diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/migration_utils.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/migration_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bf5527856300bb610f338f6d27212722f63ea4bb --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/migration_utils.py @@ -0,0 +1,70 @@ +from ray.train.constants import V2_MIGRATION_GUIDE_MESSAGE + +FAIL_FAST_DEPRECATION_MESSAGE = ( + "`ray.train.FailureConfig(fail_fast)` is deprecated since it is " + "only relevant in the context of multiple trials running in Ray Tune. " + "This parameter is still available in `ray.tune.FailureConfig` " + "for passing into a `ray.tune.Tuner`. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) + +TRAINER_RESOURCES_DEPRECATION_MESSAGE = ( + "`ray.train.ScalingConfig(trainer_resources)` is deprecated. " + "This parameter was an advanced configuration that specified " + "resources for the Ray Train driver actor, which doesn't " + "need to reserve logical resources because it doesn't perform " + "any heavy computation. " + "Only the `resources_per_worker` parameter should be used " + "to specify resources for the training workers. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) + +VERBOSE_DEPRECATION_MESSAGE = ( + "`ray.train.RunConfig(verbose)` is deprecated. " + "This parameter controls Ray Tune logging verbosity, " + "and is only relevant when using Ray Tune. " + "This parameter is still available in `ray.tune.RunConfig` " + "for passing into a `ray.tune.Tuner`. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) + +LOG_TO_FILE_DEPRECATION_MESSAGE = ( + "`ray.train.RunConfig(log_to_file)` is deprecated. " + "The Ray Train driver actor and the training worker actors " + "already log stdout/stderr as part of Ray's logging system. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) + +STOP_DEPRECATION_MESSAGE = ( + "`ray.train.RunConfig(stop)` is deprecated. " + "This parameter is only relevant when using Ray Tune " + "and is still available in `ray.tune.RunConfig` " + "for passing into a `ray.tune.Tuner`. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) + +CALLBACKS_DEPRECATION_MESSAGE = ( + "`ray.train.RunConfig(callbacks: List[ray.tune.Callback])` is deprecated. " + "Ray Train no longer accepts Ray Tune callbacks, since the Ray Train " + "execution backend is being separated from Ray Tune. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) + +PROGRESS_REPORTER_DEPRECATION_MESSAGE = ( + "`ray.train.RunConfig(progress_reporter)` is deprecated. " + "This parameter controls the Ray Tune console output reporter, " + "and is only relevant when using Ray Tune. " + "This parameter is still available in `ray.tune.RunConfig` " + "for passing into a `ray.tune.Tuner`. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) + +SYNC_CONFIG_DEPRECATION_MESSAGE = ( + "`ray.train.RunConfig(sync_config)` is deprecated. " + "This configuration controls advanced syncing behavior, " + "which is either not supported or not relevant in the reworked Ray Train. " + "This parameter is still available in `ray.tune.RunConfig` " + "for passing into a `ray.tune.Tuner`. " + "The `SyncConfig` class has been moved to `ray.tune.SyncConfig`. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1d7eb545a9f6bc17b7501c80b2a083a5306e4f1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/export.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/export.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f3c2a725f078eaee8ff765d4e8dd902c787c436 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/export.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/schema.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/schema.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5407ded93c4601682d03f448f1b9e5b69d9443d1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/schema.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/state_actor.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/state_actor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf4c935962c84ad34aae080f0e9a01c49204df2c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/state_actor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/state_manager.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/state_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a4061ec3b81a5304f260d3d60cf4fa9aaed40ae Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/__pycache__/state_manager.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/export.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/export.py new file mode 100644 index 0000000000000000000000000000000000000000..6aa56605d1330510b432c832ea45928a90549e8e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/export.py @@ -0,0 +1,128 @@ +from ray.core.generated.export_train_state_pb2 import ( + ExportTrainRunAttemptEventData as ProtoTrainRunAttempt, + ExportTrainRunEventData as ProtoTrainRun, +) +from ray.dashboard.modules.metrics.dashboards.common import Panel +from ray.dashboard.modules.metrics.dashboards.train_dashboard_panels import ( + TRAIN_RUN_PANELS, + TRAIN_WORKER_PANELS, +) +from ray.train.v2._internal.state.schema import ( + ActorStatus, + RunAttemptStatus, + RunStatus, + TrainRun, + TrainRunAttempt, + TrainWorker, +) + +TRAIN_SCHEMA_VERSION = 2 +RAY_TRAIN_VERSION = 2 + +# Status mapping dictionaries +_ACTOR_STATUS_MAP = { + ActorStatus.ALIVE: ProtoTrainRunAttempt.ActorStatus.ALIVE, + ActorStatus.DEAD: ProtoTrainRunAttempt.ActorStatus.DEAD, +} + +_RUN_ATTEMPT_STATUS_MAP = { + RunAttemptStatus.PENDING: ProtoTrainRunAttempt.RunAttemptStatus.PENDING, + RunAttemptStatus.RUNNING: ProtoTrainRunAttempt.RunAttemptStatus.RUNNING, + RunAttemptStatus.FINISHED: ProtoTrainRunAttempt.RunAttemptStatus.FINISHED, + RunAttemptStatus.ERRORED: ProtoTrainRunAttempt.RunAttemptStatus.ERRORED, + RunAttemptStatus.ABORTED: ProtoTrainRunAttempt.RunAttemptStatus.ABORTED, +} + +_RUN_STATUS_MAP = { + RunStatus.INITIALIZING: ProtoTrainRun.RunStatus.INITIALIZING, + RunStatus.SCHEDULING: ProtoTrainRun.RunStatus.SCHEDULING, + RunStatus.RUNNING: ProtoTrainRun.RunStatus.RUNNING, + RunStatus.RESTARTING: ProtoTrainRun.RunStatus.RESTARTING, + RunStatus.RESIZING: ProtoTrainRun.RunStatus.RESIZING, + RunStatus.FINISHED: ProtoTrainRun.RunStatus.FINISHED, + RunStatus.ERRORED: ProtoTrainRun.RunStatus.ERRORED, + RunStatus.ABORTED: ProtoTrainRun.RunStatus.ABORTED, +} + + +# Helper conversion functions +def _to_proto_resources(resources: dict) -> ProtoTrainRunAttempt.TrainResources: + """Convert resources dictionary to protobuf TrainResources.""" + return ProtoTrainRunAttempt.TrainResources(resources=resources) + + +def _to_proto_worker(worker: TrainWorker) -> ProtoTrainRunAttempt.TrainWorker: + """Convert TrainWorker to protobuf format.""" + status = None + if worker.status is not None: + status = _ACTOR_STATUS_MAP[worker.status] + + return ProtoTrainRunAttempt.TrainWorker( + world_rank=worker.world_rank, + local_rank=worker.local_rank, + node_rank=worker.node_rank, + actor_id=bytes.fromhex(worker.actor_id), + node_id=bytes.fromhex(worker.node_id), + node_ip=worker.node_ip, + pid=worker.pid, + gpu_ids=worker.gpu_ids, + status=status, + resources=_to_proto_resources(worker.resources.resources), + log_file_path=worker.log_file_path, + ) + + +# Main conversion functions +def train_run_attempt_to_proto(attempt: TrainRunAttempt) -> ProtoTrainRunAttempt: + """Convert TrainRunAttempt to protobuf format.""" + proto_attempt = ProtoTrainRunAttempt( + schema_version=TRAIN_SCHEMA_VERSION, + ray_train_version=RAY_TRAIN_VERSION, + run_id=attempt.run_id, + attempt_id=attempt.attempt_id, + status=_RUN_ATTEMPT_STATUS_MAP[attempt.status], + status_detail=attempt.status_detail, + start_time_ns=attempt.start_time_ns, + end_time_ns=attempt.end_time_ns, + resources=[_to_proto_resources(r.resources) for r in attempt.resources], + workers=[_to_proto_worker(w) for w in attempt.workers], + ) + + return proto_attempt + + +def _to_proto_dashboard_panel(panel: Panel) -> ProtoTrainRun.DashboardPanelMetadata: + """Convert Dashboard Panel to protobuf format.""" + proto_panel = ProtoTrainRun.DashboardPanelMetadata( + id=str(panel.id), + title=panel.title, + ) + + return proto_panel + + +def train_run_to_proto(run: TrainRun) -> ProtoTrainRun: + """Convert TrainRun to protobuf format.""" + + train_run_panels_proto = [_to_proto_dashboard_panel(p) for p in TRAIN_RUN_PANELS] + train_worker_panels_proto = [ + _to_proto_dashboard_panel(p) for p in TRAIN_WORKER_PANELS + ] + + proto_run = ProtoTrainRun( + schema_version=TRAIN_SCHEMA_VERSION, + ray_train_version=RAY_TRAIN_VERSION, + id=run.id, + name=run.name, + job_id=bytes.fromhex(run.job_id), + controller_actor_id=bytes.fromhex(run.controller_actor_id), + status=_RUN_STATUS_MAP[run.status], + status_detail=run.status_detail, + start_time_ns=run.start_time_ns, + end_time_ns=run.end_time_ns, + controller_log_file_path=run.controller_log_file_path, + train_run_panels=train_run_panels_proto, + train_worker_panels=train_worker_panels_proto, + ) + + return proto_run diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/schema.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..8c8497a47ea33c10f8d0c38fbfe6e12bfa55fc71 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/schema.py @@ -0,0 +1,255 @@ +from enum import Enum +from typing import Dict, List, Optional + +from ray._common.pydantic_compat import BaseModel, Field +from ray.dashboard.modules.job.pydantic_models import JobDetails +from ray.util.annotations import DeveloperAPI + +MAX_ERROR_STACK_TRACE_LENGTH = 50000 + + +@DeveloperAPI +class RunStatus(str, Enum): + """Enumeration of the possible statuses for a Train run.""" + + # ====== Active States ====== + # The Train run is currently in the process of initializing. + INITIALIZING = "INITIALIZING" + # The Train run is waiting to be scheduled. + SCHEDULING = "SCHEDULING" + # The Train run is currently in progress. + RUNNING = "RUNNING" + # The Train run is recovering from a failure or restart. + RESTARTING = "RESTARTING" + # The Train run is resizing. + RESIZING = "RESIZING" + + # ===== Terminal States ====== + # The Train run completed successfully. + FINISHED = "FINISHED" + # The Train run failed due to an error in the training workers. + ERRORED = "ERRORED" + # The Train run was terminated due to system or controller errors. + ABORTED = "ABORTED" + + +@DeveloperAPI +class RunAttemptStatus(str, Enum): + """Enumeration of the possible statuses for a Train run attempt.""" + + # ====== Active States ====== + # The run attempt is waiting to be scheduled. + PENDING = "PENDING" + # The run attempt is currently in progress. + RUNNING = "RUNNING" + + # ===== Terminal States ===== + # The run attempt completed successfully. + FINISHED = "FINISHED" + # The run attempt failed due to an error in the training workers. + ERRORED = "ERRORED" + # The run attempt was terminated due to system or controller errors. + ABORTED = "ABORTED" + + +@DeveloperAPI +class ActorStatus(str, Enum): + """Enumeration of the statuses for a Train worker actor.""" + + # The actor is currently active. + ALIVE = "ALIVE" + # The actor is no longer active. + DEAD = "DEAD" + + +@DeveloperAPI +class TrainResources(BaseModel): + """Resources allocated for a Train worker or run.""" + + resources: Dict[str, float] = Field( + description="A dictionary specifying the types and amounts of resources " + "allocated (e.g., CPU, GPU)." + ) + + +@DeveloperAPI +class TrainWorker(BaseModel): + """Metadata about a Ray Train worker.""" + + world_rank: int = Field( + description="The global rank of the worker in the training cluster." + ) + local_rank: int = Field(description="The local rank of the worker on its node.") + node_rank: int = Field(description="The rank of the worker's node in the cluster.") + actor_id: str = Field(description="The unique ID of the worker's actor.") + node_id: str = Field( + description="The unique ID of the node where the worker is running." + ) + node_ip: str = Field( + description="The IP address of the node where the worker is running." + ) + pid: int = Field(description="The process ID of the worker.") + gpu_ids: List[int] = Field(description="A list of GPU IDs allocated to the worker.") + status: Optional[ActorStatus] = Field( + description="The current status of the worker actor." + ) + resources: TrainResources = Field( + description="The resources allocated to this Train worker." + ) + log_file_path: Optional[str] = Field( + description="The path to the log file for the Train worker." + ) + + +@DeveloperAPI +class MemoryInfo(BaseModel): + """Memory usage information for a process.""" + + rss: int = Field(description="The resident set size (RSS) memory usage in bytes.") + vms: int = Field(description="The virtual memory size (VMS) usage in bytes.") + pfaults: Optional[int] = Field(description="The number of page faults.") + pageins: Optional[int] = Field(description="The number of page-ins.") + + +@DeveloperAPI +class ProcessStats(BaseModel): + """CPU and memory statistics for a process.""" + + cpuPercent: float = Field(description="The percentage of CPU usage.") + mem: Optional[List[int]] = Field( + description="Memory statistics, including total memory, free memory, " + "and memory usage ratio." + ) + memoryInfo: MemoryInfo = Field(description="Detailed memory usage information.") + + +class ProcessGPUUsage(BaseModel): + """GPU usage statistics for a process.""" + + pid: int = Field(description="The process ID.") + gpuMemoryUsage: int = Field(description="The GPU memory usage in bytes.") + + +@DeveloperAPI +class GPUStats(BaseModel): + """Statistics for a GPU.""" + + uuid: str = Field(description="The unique identifier of the GPU.") + index: int = Field(description="The index of the GPU.") + name: str = Field(description="The name of the GPU.") + utilizationGpu: Optional[float] = Field( + description="The percentage utilization of the GPU." + ) + memoryUsed: float = Field(description="The amount of GPU memory used in bytes.") + memoryTotal: float = Field(description="The total amount of GPU memory in bytes.") + processInfo: ProcessGPUUsage = Field( + description="GPU usage statistics for the associated process." + ) + + +@DeveloperAPI +class DecoratedTrainWorker(TrainWorker): + """Detailed metadata for a Ray Train worker, including process and GPU stats.""" + + processStats: Optional[ProcessStats] = Field( + None, description="CPU and memory statistics for the worker process." + ) + gpus: List[GPUStats] = Field( + default_factory=list, + description="A list of GPUs used by the worker process," + " with detailed statistics.", + ) + + +@DeveloperAPI +class TrainRunAttempt(BaseModel): + """Metadata for an individual attempt to execute a Train run.""" + + run_id: str = Field(description="Unique identifier for the parent Train run.") + attempt_id: str = Field( + description="Unique identifier for this specific Train run attempt." + ) + status: RunAttemptStatus = Field( + description="The current execution status of the Train run attempt." + ) + status_detail: Optional[str] = Field( + description="Additional details about the status," + " including error messages if applicable." + ) + start_time_ns: int = Field( + description="The UNIX timestamp (in nanoseconds)" + " when the Train run attempt started." + ) + end_time_ns: Optional[int] = Field( + description="The UNIX timestamp (in nanoseconds)" + " when the Train run attempt ended. " + "If null, the attempt is still ongoing." + ) + resources: List[TrainResources] = Field( + description="The resources (e.g., CPU, GPU) allocated to the Train run attempt." + ) + workers: List[TrainWorker] = Field( + description="List of Train workers participating in this attempt, " + "sorted by global ranks." + ) + + +@DeveloperAPI +class DecoratedTrainRunAttempt(TrainRunAttempt): + """Detailed metadata for a Train run attempt, including decorated worker data.""" + + workers: List[DecoratedTrainWorker] = Field( + description="A list of Train workers with detailed statistics, " + "sorted by global ranks." + ) + + +@DeveloperAPI +class TrainRun(BaseModel): + """Metadata for a Ray Train run, including its details and status.""" + + id: str = Field(description="Unique identifier for the Train run.") + name: str = Field(description="Human-readable name assigned to the Train run.") + job_id: str = Field(description="The Ray Job ID associated with this Train run.") + controller_actor_id: str = Field( + description="Unique ID of the actor managing the Train run." + ) + status: RunStatus = Field( + description="The current execution status of the Train run." + ) + status_detail: Optional[str] = Field( + description="Additional details about the current status, " + "including error messages if applicable." + ) + start_time_ns: int = Field( + description="The UNIX timestamp (in nanoseconds) when the Train run started." + ) + end_time_ns: Optional[int] = Field( + description="The UNIX timestamp (in nanoseconds) when the Train run ended. " + "If null, the run is still in progress." + ) + controller_log_file_path: Optional[str] = Field( + description="The path to the log file for the Train run controller." + ) + + +@DeveloperAPI +class DecoratedTrainRun(TrainRun): + """Detailed metadata for a Ray Train run, including attempts and job details.""" + + attempts: List[DecoratedTrainRunAttempt] = Field( + description="A list of attempts made to execute the Train run." + ) + job_details: Optional[JobDetails] = Field( + None, + description="Detailed information about the job that initiated this Train run.", + ) + + +@DeveloperAPI +class TrainRunsResponse(BaseModel): + """Response containing a list of decorated Train runs.""" + + train_runs: List[DecoratedTrainRun] = Field( + description="A list of Train runs with detailed metadata." + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/state_actor.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/state_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..47021d3e1f587973841ef9ab3f200509a96e208b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/state_actor.py @@ -0,0 +1,164 @@ +import logging +import os +import threading +from collections import defaultdict +from typing import Dict, Optional + +import ray +from ray._private.event.export_event_logger import ( + EventLogType, + check_export_api_enabled, + get_export_event_logger, +) +from ray.actor import ActorHandle +from ray.train.v2._internal.state.schema import TrainRun, TrainRunAttempt + +logger = logging.getLogger(__name__) + + +class TrainStateActor: + def __init__(self): + # NOTE: All runs and attempts are stored in memory. + # This may be a memory issue for large runs. + self._runs: Dict[str, TrainRun] = {} + # {run_id: {attempt_id: TrainRunAttempt}} + self._run_attempts: Dict[str, Dict[str, TrainRunAttempt]] = defaultdict(dict) + ( + self._export_logger, + self._is_train_run_export_api_enabled, + self._is_train_run_attempt_export_api_enabled, + ) = self._init_export_logger() + + def create_or_update_train_run(self, run: TrainRun) -> None: + self._runs[run.id] = run + self._maybe_export_train_run(run) + + def create_or_update_train_run_attempt(self, run_attempt: TrainRunAttempt): + self._run_attempts[run_attempt.run_id][run_attempt.attempt_id] = run_attempt + self._maybe_export_train_run_attempt(run_attempt) + + def get_train_runs(self) -> Dict[str, TrainRun]: + return self._runs + + def get_train_run_attempts(self) -> Dict[str, Dict[str, TrainRunAttempt]]: + return self._run_attempts + + # ============================ + # Export API + # ============================ + + def is_export_api_enabled(self) -> bool: + return self._export_logger is not None + + def _init_export_logger(self) -> tuple[Optional[logging.Logger], bool, bool]: + """Initialize the export logger and check if the export API is enabled. + + Returns: + A tuple containing: + - The export logger (or None if export API is not enabled). + - A boolean indicating if the export API is enabled for train runs. + - A boolean indicating if the export API is enabled for train run attempts. + """ + # Proto schemas should be imported within the scope of TrainStateActor to + # prevent serialization errors. + from ray.core.generated.export_event_pb2 import ExportEvent + + is_train_run_export_api_enabled = check_export_api_enabled( + ExportEvent.SourceType.EXPORT_TRAIN_RUN + ) + is_train_run_attempt_export_api_enabled = check_export_api_enabled( + ExportEvent.SourceType.EXPORT_TRAIN_RUN_ATTEMPT + ) + export_api_enabled = ( + is_train_run_export_api_enabled or is_train_run_attempt_export_api_enabled + ) + + if not export_api_enabled: + return None, False, False + + log_directory = os.path.join( + ray._private.worker._global_node.get_session_dir_path(), "logs" + ) + logger = None + try: + logger = get_export_event_logger( + EventLogType.TRAIN_STATE, + log_directory, + ) + except Exception: + logger.exception( + "Unable to initialize the export event logger, so no Train export " + "events will be written." + ) + + if logger is None: + return None, False, False + + return ( + logger, + is_train_run_export_api_enabled, + is_train_run_attempt_export_api_enabled, + ) + + def _maybe_export_train_run(self, run: TrainRun) -> None: + if not self._is_train_run_export_api_enabled: + return + + from ray.train.v2._internal.state.export import train_run_to_proto + + run_proto = train_run_to_proto(run) + self._export_logger.send_event(run_proto) + + def _maybe_export_train_run_attempt(self, run_attempt: TrainRunAttempt) -> None: + if not self._is_train_run_attempt_export_api_enabled: + return + + from ray.train.v2._internal.state.export import train_run_attempt_to_proto + + run_attempt_proto = train_run_attempt_to_proto(run_attempt) + self._export_logger.send_event(run_attempt_proto) + + +TRAIN_STATE_ACTOR_NAME = "train_v2_state_actor" +TRAIN_STATE_ACTOR_NAMESPACE = "_train_state_actor" + +_state_actor_lock: threading.RLock = threading.RLock() + + +def get_or_create_state_actor() -> ActorHandle: + """Get or create the Ray Train state actor singleton. + + This is a long-living, detached actor living on the head node + that gets initialized when the first Train run happens on the + Ray cluster. + """ + with _state_actor_lock: + state_actor = ( + ray.remote(TrainStateActor) + .options( + num_cpus=0, + name=TRAIN_STATE_ACTOR_NAME, + namespace=TRAIN_STATE_ACTOR_NAMESPACE, + get_if_exists=True, + lifetime="detached", + resources={"node:__internal_head__": 0.001}, + # Escape from the parent's placement group + scheduling_strategy="DEFAULT", + max_restarts=-1, + max_task_retries=-1, + ) + .remote() + ) + + return state_actor + + +def get_state_actor() -> Optional[ActorHandle]: + """Get the `TrainStateActor` if exists, otherwise return None.""" + try: + return ray.get_actor( + name=TRAIN_STATE_ACTOR_NAME, + namespace=TRAIN_STATE_ACTOR_NAMESPACE, + ) + except ValueError: + return None diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/state_manager.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/state_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..dd9050d8d13b5da520b85a6ed62d57ae1a2ffa9d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/state/state_manager.py @@ -0,0 +1,244 @@ +import logging +import time +from collections import defaultdict +from typing import Dict, List, Optional + +from ray.actor import ActorHandle +from ray.train.v2._internal.execution.context import DistributedContext +from ray.train.v2._internal.execution.scaling_policy.scaling_policy import ( + ResizeDecision, +) +from ray.train.v2._internal.execution.worker_group import ActorMetadata, Worker +from ray.train.v2._internal.state.schema import ( + ActorStatus, + RunAttemptStatus, + RunStatus, + TrainResources, + TrainRun, + TrainRunAttempt, + TrainWorker, +) +from ray.train.v2._internal.state.state_actor import get_or_create_state_actor + +logger = logging.getLogger(__name__) + + +class TrainStateManager: + """Manages the state of a train run and run attempts.""" + + def __init__(self) -> None: + self._state_actor = get_or_create_state_actor() + # NOTE: All runs and attempts are stored in memory. + # This may be a memory issue for large runs. + self._runs: Dict[str, TrainRun] = {} + # {run_id: {attempt_id: TrainRunAttempt}} + self._run_attempts: Dict[str, Dict[str, TrainRunAttempt]] = defaultdict(dict) + + def create_train_run( + self, + id: str, + name: str, + job_id: str, + controller_actor_id: str, + controller_log_file_path: str, + ) -> None: + run = TrainRun( + id=id, + name=name, + job_id=job_id, + status=RunStatus.INITIALIZING, + status_detail=None, + controller_actor_id=controller_actor_id, + start_time_ns=_current_time_ns(), + controller_log_file_path=controller_log_file_path, + ) + self._runs[run.id] = run + self._create_or_update_train_run(run) + + def update_train_run_scheduling( + self, + run_id: str, + resize_decision: Optional[ResizeDecision] = None, + ) -> None: + if resize_decision is not None: + status_detail = _get_scheduling_status_detail( + resize_decision.num_workers, resize_decision.resources_per_worker + ) + else: + status_detail = None + + run = self._runs[run_id] + run.status = RunStatus.SCHEDULING + run.status_detail = status_detail + self._create_or_update_train_run(run) + + def update_train_run_running( + self, + run_id: str, + ) -> None: + run = self._runs[run_id] + run.status = RunStatus.RUNNING + run.status_detail = None + self._create_or_update_train_run(run) + + def update_train_run_restarting( + self, + run_id: str, + ) -> None: + run = self._runs[run_id] + run.status = RunStatus.RESTARTING + run.status_detail = None + self._create_or_update_train_run(run) + + def update_train_run_resizing( + self, + run_id: str, + ) -> None: + run = self._runs[run_id] + run.status = RunStatus.RESIZING + run.status_detail = None + self._create_or_update_train_run(run) + + def update_train_run_finished( + self, + run_id: str, + ): + run = self._runs[run_id] + run.status = RunStatus.FINISHED + run.status_detail = None + run.end_time_ns = _current_time_ns() + self._create_or_update_train_run(run) + + def update_train_run_errored( + self, + run_id: str, + status_detail: str, + ): + run = self._runs[run_id] + run.status = RunStatus.ERRORED + run.status_detail = status_detail + run.end_time_ns = _current_time_ns() + self._create_or_update_train_run(run) + + def update_train_run_aborted( + self, + run_id: str, + ): + run = self._runs[run_id] + run.status = RunStatus.ABORTED + run.status_detail = None # TODO: Add status detail. + run.end_time_ns = _current_time_ns() + self._create_or_update_train_run(run) + + def create_train_run_attempt( + self, + run_id: str, + attempt_id: str, + num_workers: int, + resources_per_worker: Dict[str, float], + ) -> None: + status_detail = _get_scheduling_status_detail(num_workers, resources_per_worker) + resources = [ + TrainResources(resources=resources_per_worker) for _ in range(num_workers) + ] + run_attempt = TrainRunAttempt( + run_id=run_id, + attempt_id=attempt_id, + start_time_ns=_current_time_ns(), + status=RunAttemptStatus.PENDING, + status_detail=status_detail, + resources=resources, + workers=[], # Not started yet. + ) + + self._run_attempts[run_id][attempt_id] = run_attempt + self._create_or_update_train_run_attempt(run_attempt) + + def update_train_run_attempt_running( + self, run_id: str, attempt_id: str, workers: List[Worker] + ) -> None: + def _convert_worker(worker: Worker) -> TrainWorker: + + actor: ActorHandle = worker.actor + distributed_context: DistributedContext = worker.distributed_context + actor_metadata: ActorMetadata = worker.metadata + + return TrainWorker( + world_rank=distributed_context.world_rank, + local_rank=distributed_context.local_rank, + node_rank=distributed_context.node_rank, + actor_id=actor._actor_id.hex(), + node_id=actor_metadata.node_id, + node_ip=actor_metadata.node_ip, + pid=actor_metadata.pid, + gpu_ids=actor_metadata.gpu_ids, + status=ActorStatus.ALIVE, + resources=TrainResources(resources=worker.resources), + log_file_path=worker.log_file_path, + ) + + workers: List[TrainWorker] = [_convert_worker(worker) for worker in workers] + + run_attempt = self._run_attempts[run_id][attempt_id] + run_attempt.status = RunAttemptStatus.RUNNING + run_attempt.status_detail = None + run_attempt.workers = workers + self._create_or_update_train_run_attempt(run_attempt) + + def update_train_run_attempt_finished( + self, + run_id: str, + attempt_id: str, + ): + run_attempt = self._run_attempts[run_id][attempt_id] + run_attempt.status = RunAttemptStatus.FINISHED + run_attempt.status_detail = None + run_attempt.end_time_ns = _current_time_ns() + _mark_workers_dead(run_attempt) + self._create_or_update_train_run_attempt(run_attempt) + + def update_train_run_attempt_errored( + self, + run_id: str, + attempt_id: str, + status_detail: str, + ): + run_attempt = self._run_attempts[run_id][attempt_id] + run_attempt.status = RunAttemptStatus.ERRORED + run_attempt.status_detail = status_detail + run_attempt.end_time_ns = _current_time_ns() + _mark_workers_dead(run_attempt) + self._create_or_update_train_run_attempt(run_attempt) + + def update_train_run_attempt_aborted( + self, + run_id: str, + attempt_id: str, + ): + run_attempt = self._run_attempts[run_id][attempt_id] + run_attempt.status_detail = None # TODO: Add status detail. + run_attempt.status = RunAttemptStatus.ABORTED + run_attempt.end_time_ns = _current_time_ns() + _mark_workers_dead(run_attempt) + self._create_or_update_train_run_attempt(run_attempt) + + def _create_or_update_train_run(self, run: TrainRun) -> None: + self._state_actor.create_or_update_train_run.remote(run) + + def _create_or_update_train_run_attempt(self, run_attempt: TrainRunAttempt) -> None: + self._state_actor.create_or_update_train_run_attempt.remote(run_attempt) + + +def _current_time_ns() -> int: + return time.time_ns() + + +def _get_scheduling_status_detail( + num_workers: int, resources_per_worker: Dict[str, float] +) -> str: + return f"Scheduling {num_workers} workers, each requiring: {resources_per_worker}." + + +def _mark_workers_dead(run_attempt: TrainRunAttempt) -> None: + for worker in run_attempt.workers: + worker.status = ActorStatus.DEAD diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/_internal/util.py b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/util.py new file mode 100644 index 0000000000000000000000000000000000000000..8ce512af8d90e7a6aedd2217310ab1153787f2ef --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/_internal/util.py @@ -0,0 +1,212 @@ +import contextlib +import functools +import time +from datetime import datetime +from typing import ( + Any, + Callable, + ContextManager, + Dict, + Generator, + Generic, + List, + Optional, + TypeVar, + Union, +) + +import ray +from ray.train._internal.utils import count_required_parameters +from ray.types import ObjectRef + +T = TypeVar("T") + + +def bundle_to_remote_args(bundle: dict) -> dict: + """Convert a bundle of resources to Ray actor/task arguments. + + >>> bundle_to_remote_args({"GPU": 1, "memory": 1, "custom": 0.1}) + {'num_cpus': 0, 'num_gpus': 1, 'memory': 1, 'resources': {'custom': 0.1}} + """ + bundle = bundle.copy() + args = { + "num_cpus": bundle.pop("CPU", 0), + "num_gpus": bundle.pop("GPU", 0), + "memory": bundle.pop("memory", 0), + } + if bundle: + args["resources"] = bundle + return args + + +def construct_train_func( + train_func: Union[Callable[[], T], Callable[[Dict[str, Any]], T]], + config: Optional[Dict[str, Any]], + train_func_context: ContextManager, + fn_arg_name: Optional[str] = "train_loop_per_worker", +) -> Callable[[], T]: + """Validates and constructs the training function to execute. + Args: + train_func: The training function to execute. + This can either take in no arguments or a ``config`` dict. + config (Optional[Dict]): Configurations to pass into + ``train_func``. If None then an empty Dict will be created. + train_func_context: Context manager for user's `train_func`, which executes + backend-specific logic before and after the training function. + fn_arg_name (Optional[str]): The name of training function to use for error + messages. + Returns: + A valid training function. + Raises: + ValueError: if the input ``train_func`` is invalid. + """ + num_required_params = count_required_parameters(train_func) + + if num_required_params > 1: + err_msg = ( + f"{fn_arg_name} should take in 0 or 1 required arguments, but it accepts " + f"{num_required_params} required arguments instead." + ) + raise ValueError(err_msg) + + if num_required_params == 1: + config = config or {} + + @functools.wraps(train_func) + def train_fn(): + with train_func_context(): + return train_func(config) + + else: # num_params == 0 + + @functools.wraps(train_func) + def train_fn(): + with train_func_context(): + return train_func() + + return train_fn + + +class ObjectRefWrapper(Generic[T]): + """Thin wrapper around ray.put to manually control dereferencing.""" + + def __init__(self, obj: T): + self._ref = ray.put(obj) + + def get(self) -> T: + return ray.get(self._ref) + + +def date_str(include_ms: bool = False): + pattern = "%Y-%m-%d_%H-%M-%S" + if include_ms: + pattern += ".%f" + return datetime.today().strftime(pattern) + + +def time_monotonic(): + return time.monotonic() + + +def _copy_doc(copy_func): + def wrapped(func): + func.__doc__ = copy_func.__doc__ + return func + + return wrapped + + +def ray_get_safe( + object_refs: Union[ObjectRef, List[ObjectRef]], +) -> Union[Any, List[Any]]: + """This is a safe version of `ray.get` that raises an exception immediately + if an input task dies, while the others are still running. + + TODO(ml-team, core-team): This is NOT a long-term solution, + and we should not maintain this function indefinitely. + This is a mitigation for a Ray Core bug, and should be removed when + that is fixed. + See here: https://github.com/ray-project/ray/issues/47204 + + Args: + object_refs: A single or list of object refs to wait on. + + Returns: + task_outputs: The outputs of the tasks. + + Raises: + `RayTaskError`/`RayActorError`: if any of the tasks encounter a runtime error + or fail due to actor/task death (ex: node failure). + """ + is_list = isinstance(object_refs, list) + object_refs = object_refs if is_list else [object_refs] + + unready = object_refs + task_to_output = {} + while unready: + ready, unready = ray.wait(unready, num_returns=1) + if ready: + for task, task_output in zip(ready, ray.get(ready)): + task_to_output[task] = task_output + + assert len(task_to_output) == len(object_refs) + ordered_outputs = [task_to_output[task] for task in object_refs] + return ordered_outputs if is_list else ordered_outputs[0] + + +@contextlib.contextmanager +def invoke_context_managers( + context_managers: List[ContextManager], +) -> Generator[None, None, None]: + """ + Utility to invoke a list of context managers and yield sequentially. + + Args: + context_managers: List of context managers to invoke. + """ + with contextlib.ExitStack() as stack: + for context_manager in context_managers: + stack.enter_context(context_manager()) + yield + + +def get_module_name(obj: object) -> str: + """Returns the full module name of the given object, including its qualified name. + + Args: + obj: The object (class, function, etc.) whose module name is required. + + Returns: + Full module and qualified name as a string. + """ + return f"{obj.__module__}.{obj.__qualname__}" + + +def get_callable_name(fn: Callable) -> str: + """Returns a readable name for any callable. + + Examples: + + >>> get_callable_name(lambda x: x) + '' + >>> def foo(a, b): pass + >>> get_callable_name(foo) + 'foo' + >>> from functools import partial + >>> bar = partial(partial(foo, a=1), b=2) + >>> get_callable_name(bar) + 'foo' + >>> class Dummy: + ... def __call__(self, a, b): pass + >>> get_callable_name(Dummy()) + 'Dummy' + """ + if isinstance(fn, functools.partial): + return get_callable_name(fn.func) + + # Use __name__ for regular functions and lambdas + if hasattr(fn, "__name__"): + return fn.__name__ + + # Fallback to the class name for objects that implement __call__ + return fn.__class__.__name__ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64c8cba53782b1fcf8fc0d72bbb4de634bcd9594 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/callback.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/callback.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f14fd718e0c87ddc3f096e3c90787e581e6db12 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/callback.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e45fb6d41fdcafafc141fb286e239f69a80dfc6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/context.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dfad1d60611cb5b35ea55675c30d946cbdad683 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/context.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/data_parallel_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/data_parallel_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..449858011e84299a30aa45d7ca440efa1394a6c4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/data_parallel_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/exceptions.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..353908dedb82146a96ac2d7c90a7d0daae53bce1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/exceptions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/result.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/result.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..484876a3e3bf06ca5a2e2e09322eca14b5826ab6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/result.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/train_fn_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/train_fn_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a8b5b7a8cd99dbecc979e08dc564eac7cf63ca7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/api/__pycache__/train_fn_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/callback.py b/venv/lib/python3.10/site-packages/ray/train/v2/api/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..51db75dfb3560e07fe1a98074b6f5193640fe562 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/api/callback.py @@ -0,0 +1,53 @@ +from typing import Any, Dict, List, Optional + +from ray.train import Checkpoint +from ray.train.v2._internal.execution.context import TrainRunContext +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class RayTrainCallback: + """Base Ray Train callback interface.""" + + pass + + +@DeveloperAPI +class UserCallback(RayTrainCallback): + """Callback interface for custom user-defined callbacks to handling events + during training. + + This callback is called on the Ray Train controller process, not on the + worker processes. + """ + + def after_report( + self, + run_context: TrainRunContext, + metrics: List[Dict[str, Any]], + checkpoint: Optional[Checkpoint], + ): + """Called after all workers have reported a metric + checkpoint + via `ray.train.report`. + + Args: + run_context: The `TrainRunContext` for the current training run. + metrics: A list of metric dictionaries reported by workers, + where metrics[i] is the metrics dict reported by worker i. + checkpoint: A Checkpoint object that has been persisted to + storage. This is None if no workers reported a checkpoint + (e.g. `ray.train.report(metrics, checkpoint=None)`). + """ + pass + + def after_exception( + self, run_context: TrainRunContext, worker_exceptions: Dict[int, Exception] + ): + """Called after one or more workers have raised an exception. + + Args: + run_context: The `TrainRunContext` for the current training run. + worker_exceptions: A dict from worker world rank to the exception + raised by that worker. + """ + pass diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/config.py b/venv/lib/python3.10/site-packages/ray/train/v2/api/config.py new file mode 100644 index 0000000000000000000000000000000000000000..4d7356c5b813c14ef5873b5de12877cc38650e67 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/api/config.py @@ -0,0 +1,196 @@ +import logging +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, List, Optional, Union + +import pyarrow.fs + +from ray.air.config import ( + CheckpointConfig, + FailureConfig as FailureConfigV1, + ScalingConfig as ScalingConfigV1, +) +from ray.runtime_env import RuntimeEnv +from ray.train.v2._internal.constants import _DEPRECATED +from ray.train.v2._internal.migration_utils import ( + FAIL_FAST_DEPRECATION_MESSAGE, + TRAINER_RESOURCES_DEPRECATION_MESSAGE, +) +from ray.train.v2._internal.util import date_str +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.train import UserCallback + + +logger = logging.getLogger(__name__) + + +@dataclass +class ScalingConfig(ScalingConfigV1): + """Configuration for scaling training. + + Args: + num_workers: The number of workers (Ray actors) to launch. + Each worker will reserve 1 CPU by default. The number of CPUs + reserved by each worker can be overridden with the + ``resources_per_worker`` argument. + use_gpu: If True, training will be done on GPUs (1 per worker). + Defaults to False. The number of GPUs reserved by each + worker can be overridden with the ``resources_per_worker`` + argument. + resources_per_worker: If specified, the resources + defined in this Dict is reserved for each worker. + Define the ``"CPU"`` and ``"GPU"`` keys (case-sensitive) to + override the number of CPU or GPUs used by each worker. + placement_strategy: The placement strategy to use for the + placement group of the Ray actors. See :ref:`Placement Group + Strategies ` for the possible options. + accelerator_type: [Experimental] If specified, Ray Train will launch the + training coordinator and workers on the nodes with the specified type + of accelerators. + See :ref:`the available accelerator types `. + Ensure that your cluster has instances with the specified accelerator type + or is able to autoscale to fulfill the request. + + Example: + + .. testcode:: + + from ray.train import ScalingConfig + scaling_config = ScalingConfig( + # Number of distributed workers. + num_workers=2, + # Turn on/off GPU. + use_gpu=True, + ) + + .. testoutput:: + :hide: + + ... + + """ + + trainer_resources: Optional[dict] = None + + def __post_init__(self): + if self.trainer_resources is not None: + raise DeprecationWarning(TRAINER_RESOURCES_DEPRECATION_MESSAGE) + + super().__post_init__() + + @property + def _trainer_resources_not_none(self): + return {} + + +@dataclass +class FailureConfig(FailureConfigV1): + """Configuration related to failure handling of each training run. + + Args: + max_failures: Tries to recover a run at least this many times. + Will recover from the latest checkpoint if present. + Setting to -1 will lead to infinite recovery retries. + Setting to 0 will disable retries. Defaults to 0. + """ + + fail_fast: Union[bool, str] = _DEPRECATED + + def __post_init__(self): + # TODO(justinvyu): Add link to migration guide. + if self.fail_fast != _DEPRECATED: + raise DeprecationWarning(FAIL_FAST_DEPRECATION_MESSAGE) + + +@dataclass +@PublicAPI(stability="stable") +class RunConfig: + """Runtime configuration for training runs. + + Args: + name: Name of the trial or experiment. If not provided, will be deduced + from the Trainable. + storage_path: [Beta] Path where all results and checkpoints are persisted. + Can be a local directory or a destination on cloud storage. + For multi-node training/tuning runs, this must be set to a + shared storage location (e.g., S3, NFS). + This defaults to the local ``~/ray_results`` directory. + storage_filesystem: [Beta] A custom filesystem to use for storage. + If this is provided, `storage_path` should be a path with its + prefix stripped (e.g., `s3://bucket/path` -> `bucket/path`). + failure_config: Failure mode configuration. + checkpoint_config: Checkpointing configuration. + callbacks: [DeveloperAPI] A list of callbacks that the Ray Train controller + will invoke during training. + worker_runtime_env: [DeveloperAPI] Runtime environment configuration + for all Ray Train worker actors. + """ + + name: Optional[str] = None + storage_path: Optional[str] = None + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None + failure_config: Optional[FailureConfig] = None + checkpoint_config: Optional[CheckpointConfig] = None + callbacks: Optional[List["UserCallback"]] = None + worker_runtime_env: Optional[Union[dict, RuntimeEnv]] = None + + sync_config: str = _DEPRECATED + verbose: str = _DEPRECATED + stop: str = _DEPRECATED + progress_reporter: str = _DEPRECATED + log_to_file: str = _DEPRECATED + + def __post_init__(self): + from ray.train.constants import DEFAULT_STORAGE_PATH + + if self.storage_path is None: + self.storage_path = DEFAULT_STORAGE_PATH + + if not self.failure_config: + self.failure_config = FailureConfig() + + if not self.checkpoint_config: + self.checkpoint_config = CheckpointConfig() + + if isinstance(self.storage_path, Path): + self.storage_path = self.storage_path.as_posix() + + # TODO(justinvyu): Add link to migration guide. + run_config_deprecation_message = ( + "`RunConfig({})` is deprecated. This configuration was a " + "Ray Tune API that did not support Ray Train usage well, " + "so we are dropping support going forward. " + "If you heavily rely on these configurations, " + "you can run Ray Train as a single Ray Tune trial. " + "See this issue for more context: " + "https://github.com/ray-project/ray/issues/49454" + ) + + unsupported_params = [ + "sync_config", + "verbose", + "stop", + "progress_reporter", + "log_to_file", + ] + for param in unsupported_params: + if getattr(self, param) != _DEPRECATED: + raise DeprecationWarning(run_config_deprecation_message.format(param)) + + if not self.name: + self.name = f"ray_train_run-{date_str()}" + + self.callbacks = self.callbacks or [] + self.worker_runtime_env = self.worker_runtime_env or {} + + from ray.train.v2.api.callback import RayTrainCallback + + if not all(isinstance(cb, RayTrainCallback) for cb in self.callbacks): + raise ValueError( + "All callbacks must be instances of `ray.train.UserCallback`. " + "Passing in a Ray Tune callback is no longer supported. " + "See this issue for more context: " + "https://github.com/ray-project/ray/issues/49454" + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/context.py b/venv/lib/python3.10/site-packages/ray/train/v2/api/context.py new file mode 100644 index 0000000000000000000000000000000000000000..c2fce63e430f03b6f1f07e98905fca5e68825072 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/api/context.py @@ -0,0 +1,212 @@ +from typing import Any, Dict + +from ray.train.v2._internal.execution.context import ( + get_train_context as get_internal_train_context, +) +from ray.util.annotations import Deprecated, DeveloperAPI, PublicAPI + + +@PublicAPI(stability="stable") +class TrainContext: + @Deprecated + def get_metadata(self) -> Dict[str, Any]: + """[Deprecated] User metadata dict passed to the Trainer constructor.""" + from ray.train.context import _GET_METADATA_DEPRECATION_MESSAGE + + raise DeprecationWarning(_GET_METADATA_DEPRECATION_MESSAGE) + + @Deprecated + def get_trial_name(self) -> str: + """[Deprecated] Trial name for the corresponding trial.""" + from ray.train.context import _TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE + + raise DeprecationWarning( + _TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_trial_name") + ) + + @Deprecated + def get_trial_id(self) -> str: + """[Deprecated] Trial id for the corresponding trial.""" + from ray.train.context import _TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE + + raise DeprecationWarning( + _TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_trial_id") + ) + + @Deprecated + def get_trial_resources(self): + """[Deprecated] Trial resources for the corresponding trial.""" + from ray.train.context import _TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE + + raise DeprecationWarning( + _TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_trial_resources") + ) + + @Deprecated + def get_trial_dir(self) -> str: + """[Deprecated] Log directory corresponding to the trial directory for a Tune session. + This is deprecated for Ray Train and should no longer be called in Ray Train workers. + + If this directory is needed, please pass it into the `train_loop_config` directly. + """ + from ray.train.context import _TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE + + raise DeprecationWarning( + _TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_trial_dir") + ) + + def get_experiment_name(self) -> str: + """Experiment name for the corresponding trial.""" + return get_internal_train_context().get_experiment_name() + + def get_world_size(self) -> int: + """Get the current world size (i.e. total number of workers) for this run. + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.tensorflow import TensorflowTrainer + + NUM_WORKERS = 2 + + def train_loop_per_worker(config): + assert train.get_context().get_world_size() == NUM_WORKERS + + trainer = TensorflowTrainer( + train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=NUM_WORKERS), + ) + trainer.fit() + + .. testoutput:: + :hide: + + ... + """ + return get_internal_train_context().get_world_size() + + def get_world_rank(self) -> int: + """Get the world rank of this worker. + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.tensorflow import TensorflowTrainer + + def train_loop_per_worker(config): + if train.get_context().get_world_rank() == 0: + print("Worker 0") + + trainer = TensorflowTrainer( + train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=2), + ) + trainer.fit() + + .. testoutput:: + :hide: + + ... + """ + return get_internal_train_context().get_world_rank() + + def get_local_rank(self) -> int: + """Get the local rank of this worker (rank of the worker on its node). + + .. testcode:: + + import torch + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.torch import TorchTrainer + + def train_loop_per_worker(config): + if torch.cuda.is_available(): + torch.cuda.set_device(train.get_context().get_local_rank()) + ... + + trainer = TorchTrainer( + train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=2, use_gpu=True), + ) + trainer.fit() + + .. testoutput:: + :hide: + + ... + """ + return get_internal_train_context().get_local_rank() + + def get_local_world_size(self) -> int: + """Get the local world size of this node (i.e. number of workers on this node). + + Example: + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.torch import TorchTrainer + + def train_loop_per_worker(): + print(train.get_context().get_local_world_size()) + + trainer = TorchTrainer( + train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=1), + ) + trainer.fit() + + .. testoutput:: + :hide: + + ... + """ + return get_internal_train_context().get_local_world_size() + + def get_node_rank(self) -> int: + """Get the rank of this node. + + Example: + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.torch import TorchTrainer + + def train_loop_per_worker(): + print(train.get_context().get_node_rank()) + + trainer = TorchTrainer( + train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=1), + ) + trainer.fit() + + .. testoutput:: + :hide: + + ... + """ + return get_internal_train_context().get_node_rank() + + @DeveloperAPI + def get_storage(self): + """Returns the :class:`~ray.train._internal.storage.StorageContext` storage + context which gives advanced access to the filesystem and paths + configured through `RunConfig`. + + NOTE: This is a developer API, and the `StorageContext` interface may change + without notice between minor versions. + """ + return get_internal_train_context().get_storage() diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/data_parallel_trainer.py b/venv/lib/python3.10/site-packages/ray/train/v2/api/data_parallel_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..d5f24e4494d23142e8504bf6185d03522c9ad6a7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/api/data_parallel_trainer.py @@ -0,0 +1,268 @@ +import asyncio +import logging +import signal +import sys +from typing import Any, Callable, Dict, List, Optional, Union + +import ray +from ray._private.ray_constants import env_bool +from ray._private.usage import usage_lib +from ray.actor import ActorHandle +from ray.air._internal.usage import tag_train_v2_trainer +from ray.train import ( + BackendConfig, + Checkpoint, + DataConfig, + Result, + RunConfig, + ScalingConfig, +) +from ray.train.base_trainer import ( + _RESUME_FROM_CHECKPOINT_DEPRECATION_WARNING, + _TRAINER_RESTORE_DEPRECATION_WARNING, +) +from ray.train.constants import RAY_CHDIR_TO_TRIAL_DIR, RAY_TRAIN_ENABLE_STATE_TRACKING +from ray.train.context import _GET_METADATA_DEPRECATION_MESSAGE +from ray.train.v2._internal.callbacks import ( + AcceleratorSetupCallback, + BackendSetupCallback, + DatasetsSetupCallback, + WorkingDirectorySetupCallback, +) +from ray.train.v2._internal.callbacks.datasets import GenDataset +from ray.train.v2._internal.callbacks.env_callback import _initialize_env_callbacks +from ray.train.v2._internal.callbacks.metrics import ( + ControllerMetricsCallback, + WorkerMetricsCallback, +) +from ray.train.v2._internal.callbacks.state_manager import StateManagerCallback +from ray.train.v2._internal.callbacks.user_callback import UserCallbackHandler +from ray.train.v2._internal.constants import ( + DEFAULT_RUN_CONTROLLER_AS_ACTOR, + METRICS_ENABLED_ENV_VAR, + RUN_CONTROLLER_AS_ACTOR_ENV_VAR, + get_env_vars_to_propagate, +) +from ray.train.v2._internal.execution.callback import RayTrainCallback +from ray.train.v2._internal.execution.context import TrainRunContext +from ray.train.v2._internal.execution.controller import TrainController +from ray.train.v2._internal.execution.failure_handling import create_failure_policy +from ray.train.v2._internal.execution.scaling_policy import create_scaling_policy +from ray.train.v2._internal.util import ObjectRefWrapper, construct_train_func +from ray.train.v2.api.callback import UserCallback +from ray.util.annotations import Deprecated, DeveloperAPI +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class DataParallelTrainer: + """Base class for distributed data parallel training on Ray. + + This class supports the SPMD parallelization pattern, where a single + training function is executed in parallel across multiple workers, + and different shards of data are processed by each worker. + """ + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + backend_config: Optional[BackendConfig] = None, + scaling_config: Optional[ScalingConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + dataset_config: Optional[DataConfig] = None, + # TODO: [Deprecated] Remove in future release + resume_from_checkpoint: Optional[Checkpoint] = None, + metadata: Optional[Dict[str, Any]] = None, + ): + self.run_config = run_config or RunConfig() + self.train_loop_per_worker = train_loop_per_worker + self.train_loop_config = train_loop_config + self.scaling_config = scaling_config or ScalingConfig() + self.backend_config = backend_config or BackendConfig() + self.datasets = datasets or {} + self.data_config = dataset_config or DataConfig() + + self.train_run_context = TrainRunContext( + run_config=self.run_config, + train_loop_config=self.train_loop_config, + scaling_config=self.scaling_config, + backend_config=self.backend_config, + datasets=self.datasets, + dataset_config=self.data_config, + ) + + if resume_from_checkpoint is not None: + raise DeprecationWarning(_RESUME_FROM_CHECKPOINT_DEPRECATION_WARNING) + + if metadata is not None: + raise DeprecationWarning(_GET_METADATA_DEPRECATION_MESSAGE) + + usage_lib.record_library_usage("train") + tag_train_v2_trainer(self) + + def fit(self) -> Result: + """Launches the Ray Train controller to run training on workers. + + Returns: + A Result object containing the training result. + + Raises: + ray.train.v2.api.exceptions.TrainingFailedError: If any failures occur + during training and the number of retries configured in + `FailureConfig` is exhausted. + """ + train_fn = construct_train_func( + self.train_loop_per_worker, + config=self.train_loop_config, + train_func_context=self.backend_config.train_func_context, + fn_arg_name="train_loop_per_worker", + ) + train_fn_ref = ObjectRefWrapper(train_fn) + + result = self._initialize_and_run_controller( + train_fn_ref=train_fn_ref, + scaling_policy=create_scaling_policy(self.scaling_config), + failure_policy=create_failure_policy(self.run_config.failure_config), + train_run_context=self.train_run_context, + callbacks=self._create_default_callbacks(), + ) + + if result.error: + # NOTE: If the training run errored out, raise an error back to the + # user's driver script. + # For example, if the Train `FailurePolicy` runs out of retries, + # and one of the workers errors. The controller will exit, and + # the error will be raised here. + raise result.error + + return result + + def _create_default_callbacks(self) -> List[RayTrainCallback]: + # Initialize callbacks from environment variable + callbacks = _initialize_env_callbacks() + + accelerator_setup_callback = AcceleratorSetupCallback( + self.backend_config, self.scaling_config + ) + backend_setup_callback = BackendSetupCallback(self.backend_config) + datasets_setup_callback = DatasetsSetupCallback( + datasets=self.datasets, + data_config=self.data_config, + scaling_config=self.scaling_config, + ) + callbacks.extend( + [ + accelerator_setup_callback, + backend_setup_callback, + datasets_setup_callback, + ] + ) + if env_bool(RAY_CHDIR_TO_TRIAL_DIR, True): + working_directory_setup_callback = WorkingDirectorySetupCallback() + callbacks.append(working_directory_setup_callback) + + if env_bool(METRICS_ENABLED_ENV_VAR, True): + callbacks.append(ControllerMetricsCallback()) + callbacks.append(WorkerMetricsCallback(self.train_run_context)) + + if env_bool(RAY_TRAIN_ENABLE_STATE_TRACKING, False): + callbacks.append(StateManagerCallback()) + + run_config_callbacks = ( + self.run_config.callbacks if self.run_config.callbacks is not None else [] + ) + + # Add internal callback that invokes all user-defined callbacks. + user_callbacks = [ + cb for cb in run_config_callbacks if isinstance(cb, UserCallback) + ] + callbacks.append( + UserCallbackHandler( + user_callbacks=user_callbacks, train_run_context=self.train_run_context + ) + ) + + # Append all other callbacks to the full list. This allows custom workarounds + # built on top of internal callbacks to work. + callbacks.extend( + [cb for cb in run_config_callbacks if not isinstance(cb, UserCallback)] + ) + return callbacks + + def _initialize_and_run_controller(self, **controller_init_kwargs) -> Result: + run_controller_as_actor = env_bool( + RUN_CONTROLLER_AS_ACTOR_ENV_VAR, DEFAULT_RUN_CONTROLLER_AS_ACTOR + ) + if run_controller_as_actor: + # Attach the controller to the node running the driver script. + controller_actor_cls = ray.remote( + num_cpus=0, + scheduling_strategy=NodeAffinitySchedulingStrategy( + node_id=ray.get_runtime_context().get_node_id(), soft=False + ), + runtime_env={"env_vars": get_env_vars_to_propagate()}, + )(TrainController) + + controller = controller_actor_cls.remote(**controller_init_kwargs) + + self._register_sigint_handler(controller) + + ray.get(controller.run.remote()) + return ray.get(controller.get_result.remote()) + else: + controller = TrainController(**controller_init_kwargs) + asyncio.run(controller.run()) + return controller.get_result() + + def _register_sigint_handler(self, controller: ActorHandle[TrainController]): + """Register SIGINT handler so user Ctrl C gracefully aborts run.""" + sigint_count = 0 + + def sigint_handler(signum, frame): + logger.info( + "Received SIGINT. Gracefully aborting the training run — this " + "may take a few seconds. To forcefully abort immediately, you " + "can send a different signal, such as SIGKILL." + ) + nonlocal sigint_count + sigint_count += 1 + if sigint_count >= 3: + logger.info( + "Received SIGINT at least 3 times. " + "Forcefully aborting the training run." + ) + sys.exit(0) + if sigint_count <= 1: + try: + ray.get(controller.abort.remote()) + except ray.exceptions.ActorDiedError: + # We catch the error and exit 0 to indicate graceful termination. + # However, for some reason the process still exits with 1. + sys.exit(0) + + signal.signal(signal.SIGINT, sigint_handler) + + @classmethod + @Deprecated + def restore(cls, *args, **kwargs): + """[Deprecated] Restores a Train experiment from a previously + interrupted/failed run. + + This method is deprecated and will be removed in a future release. + """ + raise DeprecationWarning(_TRAINER_RESTORE_DEPRECATION_WARNING) + + @classmethod + @Deprecated + def can_restore(cls, *args, **kwargs): + """[Deprecated] Checks if a Train experiment can be restored from + a previously interrupted/failed run. + + This method is deprecated and will be removed in a future release. + """ + raise DeprecationWarning(_TRAINER_RESTORE_DEPRECATION_WARNING) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/exceptions.py b/venv/lib/python3.10/site-packages/ray/train/v2/api/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..2f90f73b8eebee95c46a495d6bf16f91b7f7c270 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/api/exceptions.py @@ -0,0 +1,17 @@ +from typing import Dict + +from ray.train.v2._internal.exceptions import RayTrainError +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class TrainingFailedError(RayTrainError): + """Exception raised by `Trainer.fit()` when training fails.""" + + def __init__(self, error_message: str, worker_failures: Dict[int, Exception]): + super().__init__("Training failed due to worker errors:\n" + error_message) + self._error_message = error_message + self.worker_failures = worker_failures + + def __reduce__(self): + return (self.__class__, (self._error_message, self.worker_failures)) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/result.py b/venv/lib/python3.10/site-packages/ray/train/v2/api/result.py new file mode 100644 index 0000000000000000000000000000000000000000..6e1f87c748b371462fb5532a0ce9ba30f8edfe1c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/api/result.py @@ -0,0 +1,44 @@ +import logging +import os +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Tuple, Union + +import pyarrow + +import ray +from ray.air.result import Result as ResultV1 +from ray.train.v2.api.exceptions import TrainingFailedError +from ray.util.annotations import Deprecated, PublicAPI + +logger = logging.getLogger(__name__) + + +@dataclass +class Result(ResultV1): + checkpoint: Optional["ray.train.Checkpoint"] + error: Optional[TrainingFailedError] + best_checkpoints: Optional[ + List[Tuple["ray.train.Checkpoint", Dict[str, Any]]] + ] = None + + @PublicAPI(stability="alpha") + def get_best_checkpoint( + self, metric: str, mode: str + ) -> Optional["ray.train.Checkpoint"]: + return super().get_best_checkpoint(metric, mode) + + @classmethod + def from_path( + cls, + path: Union[str, os.PathLike], + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + ) -> "Result": + raise NotImplementedError("`Result.from_path` is not implemented yet.") + + @property + @Deprecated + def config(self) -> Optional[Dict[str, Any]]: + raise DeprecationWarning( + "The `config` property for a `ray.train.Result` is deprecated, " + "since it is only relevant in the context of Ray Tune." + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/api/train_fn_utils.py b/venv/lib/python3.10/site-packages/ray/train/v2/api/train_fn_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6266f9441b429fd4beb638d67405e023c279fd4f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/api/train_fn_utils.py @@ -0,0 +1,198 @@ +from typing import TYPE_CHECKING, Any, Dict, Optional + +from ray.train import Checkpoint +from ray.train.v2._internal.execution.context import get_train_context +from ray.train.v2.api.context import TrainContext +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.data import DataIterator + + +@PublicAPI(stability="stable") +def report( + metrics: Dict[str, Any], + checkpoint: Optional[Checkpoint] = None, + checkpoint_dir_name: Optional[str] = None, +): + """Report metrics and optionally save a checkpoint. + + If a checkpoint is provided, it will be + :ref:`persisted to storage `. + + If this is called in multiple distributed training workers: + + - Only the metrics reported by the rank 0 worker will be attached to the checkpoint. + - A checkpoint will be registered as long as one or more workers reports + checkpoint that is not None. + See the :ref:`checkpointing guide `. + - Checkpoints from multiple workers will be merged into one directory + in persistent storage. + See :ref:`the distributed checkpointing guide `. + + + .. warning:: + + All workers must call `ray.train.report` the same number of times + so that Ray Train can properly synchronize the training state across + workers. This method acts as a barrier across all workers, so be sure + that every worker reaches this method. + + Example: + + .. testcode:: + + import tempfile + + from ray import train + from ray.train import Checkpoint + from ray.train.torch import TorchTrainer + + + def train_func(config): + start_epoch = 0 + checkpoint = train.get_checkpoint() + if checkpoint: + with checkpoint.as_directory() as checkpoint_dir: + # Load back training state + ... + + for epoch in range(start_epoch, config.get("num_epochs", 10)): + # Do training... + + metrics = {"loss": ...} + + with tempfile.TemporaryDirectory() as temp_checkpoint_dir: + # Save the checkpoint... + # torch.save(...) + + checkpoint = Checkpoint.from_directory(temp_checkpoint_dir) + + # Example: Only the rank 0 worker uploads the checkpoint. + if ray.train.get_context().get_world_rank() == 0: + train.report(metrics, checkpoint=checkpoint) + else: + train.report(metrics, checkpoint=None) + + trainer = TorchTrainer( + train_func, scaling_config=train.ScalingConfig(num_workers=2) + ) + + Args: + metrics: The metrics you want to report. + checkpoint: The optional checkpoint you want to report. + checkpoint_dir_name: Custom name for the checkpoint directory. + If not provided, a unique directory name will be automatically generated. + If provided, it must be unique across all checkpoints per worker to avoid + naming collisions. Consider including identifiers such as the epoch or batch + index in the name. + """ + + get_train_context().report( + metrics=metrics, checkpoint=checkpoint, checkpoint_dir_name=checkpoint_dir_name + ) + + +@PublicAPI(stability="stable") +def get_context() -> TrainContext: + """Get or create a singleton training context. + + The context is only available within a function passed to Ray Train. + + See the :class:`~ray.train.TrainContext` API reference to see available methods. + """ + # TODO: Return a dummy train context on the controller and driver process + # instead of raising an exception if the train context does not exist. + return TrainContext() + + +@PublicAPI(stability="stable") +def get_checkpoint() -> Optional[Checkpoint]: + """Access the latest reported checkpoint to resume from if one exists. + + Example: + + .. testcode:: + + import tempfile + + from ray import train + from ray.train import Checkpoint + from ray.train.torch import TorchTrainer + + + def train_func(config): + start_epoch = 0 + checkpoint = train.get_checkpoint() + if checkpoint: + with checkpoint.as_directory() as checkpoint_dir: + # Load back training state + ... + + for epoch in range(start_epoch, config.get("num_epochs", 10)): + # Do training... + + metrics = {"loss": ...} + + with tempfile.TemporaryDirectory() as temp_checkpoint_dir: + # Save the checkpoint... + + checkpoint = Checkpoint.from_directory(temp_checkpoint_dir) + train.report(metrics, checkpoint=checkpoint) + + trainer = TorchTrainer( + train_func, scaling_config=train.ScalingConfig(num_workers=2) + ) + + Returns: + Checkpoint object if the session is currently being resumed. + Otherwise, return None. + """ + return get_train_context().get_checkpoint() + + +@PublicAPI(stability="stable") +def get_dataset_shard(dataset_name: Optional[str] = None) -> Optional["DataIterator"]: + """Returns the :class:`ray.data.DataIterator` shard for this worker. + + Call :meth:`~ray.data.DataIterator.iter_torch_batches` or + :meth:`~ray.data.DataIterator.to_tf` on this shard to convert it to the + appropriate framework-specific data type. + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.torch import TorchTrainer + + def train_loop_per_worker(config): + ... + for epoch in range(2): + # Trainer will automatically handle sharding. + data_shard = train.get_dataset_shard("train") + for batch in data_shard.iter_torch_batches(): + ... + + train_dataset = ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv") + trainer = TorchTrainer( + train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=2), + datasets={"train": train_dataset} + ) + trainer.fit() + + .. testoutput:: + :hide: + + ... + + Args: + dataset_name: If a Dictionary of Datasets was passed to ``Trainer``, then + specifies which dataset shard to return. + + Returns: + The ``DataIterator`` shard to use for this worker. + If no dataset is passed into Trainer, then return None. + """ + return get_train_context().get_dataset_shard(dataset_name) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/horovod/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/horovod/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/horovod/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/horovod/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a22e20349d5ff9c75e881e60d4a9a34641f5e9ec Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/horovod/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/horovod/__pycache__/horovod_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/horovod/__pycache__/horovod_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dad1b4560cfafed2aca395611ee5b2617604479 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/horovod/__pycache__/horovod_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/horovod/horovod_trainer.py b/venv/lib/python3.10/site-packages/ray/train/v2/horovod/horovod_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..e9443ad9d89a395aae72c6f94b9273ca8c695e87 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/horovod/horovod_trainer.py @@ -0,0 +1,34 @@ +from typing import Any, Callable, Dict, Optional, Union + +from ray.air.config import RunConfig, ScalingConfig +from ray.train import Checkpoint, DataConfig +from ray.train.data_parallel_trainer import DataParallelTrainer +from ray.train.horovod.config import HorovodConfig +from ray.train.trainer import GenDataset +from ray.util.annotations import Deprecated + + +@Deprecated +class HorovodTrainer(DataParallelTrainer): + """A Trainer for data parallel Horovod training. HorovodTrainer is deprecated.""" + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + horovod_config: Optional[HorovodConfig] = None, + scaling_config: Optional[ScalingConfig] = None, + dataset_config: Optional[DataConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + raise DeprecationWarning( + "`HorovodTrainer` is not supported and is scheduled to be removed " + "in the future. " + "Please consider using `TorchTrainer` or `TensorflowTrainer`, " + "fall back to the old implementation with `RAY_TRAIN_V2_ENABLED=0`, " + "or file an issue on Github describing your use case." + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/lightgbm/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/lightgbm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/lightgbm/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/lightgbm/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c20ea9ee73aec3b025c24fc3497ce795af1a578a Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/lightgbm/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/lightgbm/__pycache__/lightgbm_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/lightgbm/__pycache__/lightgbm_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa2dc1a0484b3e9681d27942d5313fd00c036e58 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/lightgbm/__pycache__/lightgbm_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/lightgbm/lightgbm_trainer.py b/venv/lib/python3.10/site-packages/ray/train/v2/lightgbm/lightgbm_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..06655d763c825126f5cd7de0b7996c72ecd87e35 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/lightgbm/lightgbm_trainer.py @@ -0,0 +1,176 @@ +import logging +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union + +import ray.train +from ray.train import Checkpoint +from ray.train.trainer import GenDataset +from ray.train.v2.api.config import RunConfig, ScalingConfig +from ray.train.v2.api.data_parallel_trainer import DataParallelTrainer +from ray.util.annotations import Deprecated + +if TYPE_CHECKING: + from ray.train.lightgbm import LightGBMConfig + +logger = logging.getLogger(__name__) + + +class LightGBMTrainer(DataParallelTrainer): + """A Trainer for distributed data-parallel LightGBM training. + + Example + ------- + + .. testcode:: + + import lightgbm as lgb + + import ray.data + import ray.train + from ray.train.lightgbm import RayTrainReportCallback + from ray.train.lightgbm.v2 import LightGBMTrainer + + + def train_fn_per_worker(config: dict): + # (Optional) Add logic to resume training state from a checkpoint. + # ray.train.get_checkpoint() + + # 1. Get the dataset shard for the worker and convert to a `lgb.Dataset` + train_ds_iter, eval_ds_iter = ( + ray.train.get_dataset_shard("train"), + ray.train.get_dataset_shard("validation"), + ) + train_ds, eval_ds = train_ds_iter.materialize(), eval_ds_iter.materialize() + train_df, eval_df = train_ds.to_pandas(), eval_ds.to_pandas() + train_X, train_y = train_df.drop("y", axis=1), train_df["y"] + eval_X, eval_y = eval_df.drop("y", axis=1), eval_df["y"] + + train_set = lgb.Dataset(train_X, label=train_y) + eval_set = lgb.Dataset(eval_X, label=eval_y) + + # 2. Run distributed data-parallel training. + # `get_network_params` sets up the necessary configurations for LightGBM + # to set up the data parallel training worker group on your Ray cluster. + params = { + "objective": "regression", + # Adding the line below is the only change needed + # for your `lgb.train` call! + **ray.train.lightgbm.v2.get_network_params(), + } + lgb.train( + params, + train_set, + valid_sets=[eval_set], + valid_names=["eval"], + # To access the checkpoint from trainer, you need this callback. + callbacks=[RayTrainReportCallback()], + ) + + train_ds = ray.data.from_items([{"x": x, "y": x + 1} for x in range(32)]) + eval_ds = ray.data.from_items( + [{"x": x, "y": x + 1} for x in range(32, 32 + 16)] + ) + trainer = LightGBMTrainer( + train_fn_per_worker, + datasets={"train": train_ds, "validation": eval_ds}, + scaling_config=ray.train.ScalingConfig(num_workers=4), + ) + result = trainer.fit() + booster = RayTrainReportCallback.get_model(result.checkpoint) + + .. testoutput:: + :hide: + + ... + + Args: + train_loop_per_worker: The training function to execute on each worker. + This function can either take in zero arguments or a single ``Dict`` + argument which is set by defining ``train_loop_config``. + Within this function you can use any of the + :ref:`Ray Train Loop utilities `. + train_loop_config: A configuration ``Dict`` to pass in as an argument to + ``train_loop_per_worker``. + This is typically used for specifying hyperparameters. + lightgbm_config: The configuration for setting up the distributed lightgbm + backend. See :class:`~ray.train.lightgbm.LightGBMConfig` for more info. + scaling_config: The configuration for how to scale data parallel training. + ``num_workers`` determines how many Python processes are used for training, + and ``use_gpu`` determines whether or not each process should use GPUs. + See :class:`~ray.train.ScalingConfig` for more info. + run_config: The configuration for the execution of the training run. + See :class:`~ray.train.RunConfig` for more info. + datasets: The Ray Datasets to ingest for training. + Datasets are keyed by name (``{name: dataset}``). + Each dataset can be accessed from within the ``train_loop_per_worker`` + by calling ``ray.train.get_dataset_shard(name)``. + Sharding and additional configuration can be done by + passing in a ``dataset_config``. + dataset_config: The configuration for ingesting the input ``datasets``. + By default, all the Ray Dataset are split equally across workers. + See :class:`~ray.train.DataConfig` for more details. + resume_from_checkpoint: A checkpoint to resume training from. + This checkpoint can be accessed from within ``train_loop_per_worker`` + by calling ``ray.train.get_checkpoint()``. + metadata: Dict that should be made available via + `ray.train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + """ + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + lightgbm_config: Optional["LightGBMConfig"] = None, + scaling_config: Optional[ScalingConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + dataset_config: Optional[ray.train.DataConfig] = None, + # TODO: [Deprecated] + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + # TODO: [Deprecated] Legacy LightGBMTrainer API + label_column: Optional[str] = None, + params: Optional[Dict[str, Any]] = None, + num_boost_round: Optional[int] = None, + ): + if ( + label_column is not None + or params is not None + or num_boost_round is not None + ): + raise DeprecationWarning( + "The legacy LightGBMTrainer API is deprecated. " + "Please switch to passing in a custom `train_loop_per_worker` " + "function instead. " + "See this issue for more context: " + "https://github.com/ray-project/ray/issues/50042" + ) + from ray.train.lightgbm import LightGBMConfig + + super(LightGBMTrainer, self).__init__( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + backend_config=lightgbm_config or LightGBMConfig(), + scaling_config=scaling_config, + dataset_config=dataset_config, + run_config=run_config, + datasets=datasets, + resume_from_checkpoint=resume_from_checkpoint, + metadata=metadata, + ) + + @classmethod + @Deprecated + def get_model( + cls, + checkpoint: Checkpoint, + ): + """Retrieve the LightGBM model stored in this checkpoint. + + This API is deprecated. Use `RayTrainReportCallback.get_model` instead. + """ + raise DeprecationWarning( + "`LightGBMTrainer.get_model` is deprecated. " + "Use `RayTrainReportCallback.get_model` instead." + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/lightning/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/lightning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/lightning/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/lightning/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b880b3cab85c5f2bccd0e88726410d976911de3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/lightning/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/lightning/__pycache__/lightning_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/lightning/__pycache__/lightning_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d69f51bcf49932047ecb3cbd40b0da72c485d88 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/lightning/__pycache__/lightning_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/lightning/lightning_utils.py b/venv/lib/python3.10/site-packages/ray/train/v2/lightning/lightning_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..41a3637b3daa976b622961176bbdf96d6badbfbf --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/lightning/lightning_utils.py @@ -0,0 +1,58 @@ +import os +import shutil +import tempfile +from pathlib import Path + +import ray.train +from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag +from ray.train.lightning._lightning_utils import ( + RayTrainReportCallback as RayTrainReportCallbackV1, + import_lightning, +) +from ray.util import PublicAPI + +pl = import_lightning() + + +@PublicAPI(stability="beta") +class RayTrainReportCallback(RayTrainReportCallbackV1): + """A simple callback that reports checkpoints to Ray on train epoch end. + + This callback is a subclass of `lightning.pytorch.callbacks.Callback + `_. + + It fetches the latest `trainer.callback_metrics` and reports together with + the checkpoint on each training epoch end. + + Checkpoints will be saved in the following structure: + + checkpoint_{timestamp}/ Ray Train's checkpoint folder + └─ checkpoint.ckpt Lightning's checkpoint format + + For customized reporting and checkpointing logic, implement your own + `lightning.pytorch.callbacks.Callback` following this user + guide: :ref:`Saving and Loading Checkpoints `. + """ + + def __init__(self) -> None: + # TODO: Upstream this change into ray.train.lightning. + # The difference in this version is removing the trial directory usage. + job_id = ray.get_runtime_context().get_job_id() + experiment_name = ray.train.get_context().get_experiment_name() + self.local_rank = ray.train.get_context().get_local_rank() + + # Create a root temporary directory for storing local checkpoints + # before persisting to storage. + # Lightning's checkpointing implementation requires that this directory + # is a common path across all workers. + # Construct the path prefix with the job id and experiment name, + # which are shared across workers for a Ray Train run. + # This path should not be shared across different Ray Train runs. + self.tmpdir_prefix = Path( + tempfile.gettempdir(), + f"lightning_checkpoints-job_id={job_id}-name={experiment_name}", + ).as_posix() + if os.path.isdir(self.tmpdir_prefix) and self.local_rank == 0: + shutil.rmtree(self.tmpdir_prefix) + + record_extra_usage_tag(TagKey.TRAIN_LIGHTNING_RAYTRAINREPORTCALLBACK, "1") diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/tensorflow/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/tensorflow/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/tensorflow/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/tensorflow/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1308887e677b8174e67fb772fd311508f6f7f8a0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/tensorflow/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/tensorflow/__pycache__/tensorflow_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/tensorflow/__pycache__/tensorflow_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64d8f973f3b969b3b0d46811f747971399743b9e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/tensorflow/__pycache__/tensorflow_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/tensorflow/tensorflow_trainer.py b/venv/lib/python3.10/site-packages/ray/train/v2/tensorflow/tensorflow_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..208f224cc4f9b0959418d5cd018d591c804dfc53 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/tensorflow/tensorflow_trainer.py @@ -0,0 +1,191 @@ +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union + +from ray.train import Checkpoint, DataConfig +from ray.train.trainer import GenDataset +from ray.train.v2.api.config import RunConfig, ScalingConfig +from ray.train.v2.api.data_parallel_trainer import DataParallelTrainer +from ray.util import PublicAPI + +if TYPE_CHECKING: + from ray.train.tensorflow import TensorflowConfig + + +@PublicAPI(stability="beta") +class TensorflowTrainer(DataParallelTrainer): + """A Trainer for data parallel Tensorflow training. + + At a high level, this Trainer does the following: + + 1. Launches multiple workers as defined by the ``scaling_config``. + 2. Sets up a distributed Tensorflow environment + on these workers as defined by the ``tensorflow_config``. + 3. Ingests the input ``datasets`` based on the ``dataset_config``. + 4. Runs the input ``train_loop_per_worker(train_loop_config)`` + on all workers. + + For more details, see: + + * :ref:`Tensorflow Guide ` + + Inside the ``train_loop_per_worker`` function, you can use any of the + :ref:`Ray Train loop methods `. + + .. warning:: + Ray will not automatically set any environment variables or configuration + related to local parallelism / threading + :ref:`aside from "OMP_NUM_THREADS" `. + If you desire greater control over TensorFlow threading, use + the ``tf.config.threading`` module (eg. + ``tf.config.threading.set_inter_op_parallelism_threads(num_cpus)``) + at the beginning of your ``train_loop_per_worker`` function. + + + .. testcode:: + + from ray import train + + def train_loop_per_worker(): + # Report intermediate results for callbacks or logging and + # checkpoint data. + train.report(...) + + # Returns dict of last saved checkpoint. + train.get_checkpoint() + + # Returns the Dataset shard for the given key. + train.get_dataset_shard("my_dataset") + + # Returns the total number of workers executing training. + train.get_context().get_world_size() + + # Returns the rank of this worker. + train.get_context().get_world_rank() + + # Returns the rank of the worker on the current node. + train.get_context().get_local_rank() + + Any returns from the ``train_loop_per_worker`` will be discarded and not + used or persisted anywhere. + + Example: + + .. testcode:: + + import os + import tempfile + import tensorflow as tf + + import ray + from ray import train + from ray.train import Checkpoint, ScalingConfig + from ray.train.tensorflow import TensorflowTrainer + + def build_model(): + # toy neural network : 1-layer + return tf.keras.Sequential( + [tf.keras.layers.Dense( + 1, activation="linear", input_shape=(1,))] + ) + + def train_loop_per_worker(config): + dataset_shard = train.get_dataset_shard("train") + strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy() + with strategy.scope(): + model = build_model() + model.compile( + optimizer="Adam", loss="mean_squared_error", metrics=["mse"]) + + tf_dataset = dataset_shard.to_tf( + feature_columns="x", + label_columns="y", + batch_size=1 + ) + for epoch in range(config["num_epochs"]): + model.fit(tf_dataset) + + # Create checkpoint. + checkpoint_dir = tempfile.mkdtemp() + model.save_weights( + os.path.join(checkpoint_dir, "my_checkpoint") + ) + checkpoint = Checkpoint.from_directory(checkpoint_dir) + + train.report( + {}, + checkpoint=checkpoint, + ) + + train_dataset = ray.data.from_items([{"x": x, "y": x + 1} for x in range(32)]) + trainer = TensorflowTrainer( + train_loop_per_worker=train_loop_per_worker, + scaling_config=ScalingConfig(num_workers=3, use_gpu=True), + datasets={"train": train_dataset}, + train_loop_config={"num_epochs": 2}, + ) + result = trainer.fit() + + .. testoutput:: + :options:+ELLIPSIS + :hide: + + ... + + Args: + train_loop_per_worker: The training function to execute on each worker. + This function can either take in zero arguments or a single ``Dict`` + argument which is set by defining ``train_loop_config``. + Within this function you can use any of the + :ref:`Ray Train Loop utilities `. + train_loop_config: A configuration ``Dict`` to pass in as an argument to + ``train_loop_per_worker``. + This is typically used for specifying hyperparameters. Passing large + datasets via `train_loop_config` is not recommended and may introduce + large overhead and unknown issues with serialization and deserialization. + tensorflow_config: The configuration for setting up the Tensorflow + Distributed backend. If set to None, a default configuration will be + used in which GPU training uses NCCL and CPU training uses Gloo. + scaling_config: The configuration for how to scale data parallel training. + ``num_workers`` determines how many Python processes are used for training, + and ``use_gpu`` determines whether or not each process should use GPUs. + See :class:`~ray.train.ScalingConfig` for more info. + run_config: The configuration for the execution of the training run. + See :class:`~ray.train.RunConfig` for more info. + datasets: The Ray Datasets to ingest for training. + Datasets are keyed by name (``{name: dataset}``). + Each dataset can be accessed from within the ``train_loop_per_worker`` + by calling ``ray.train.get_dataset_shard(name)``. + Sharding and additional configuration can be done by + passing in a ``dataset_config``. + resume_from_checkpoint: A checkpoint to resume training from. + metadata: Dict that should be made available via + `ray.train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + """ + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + tensorflow_config: Optional["TensorflowConfig"] = None, + scaling_config: Optional[ScalingConfig] = None, + dataset_config: Optional[DataConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + # TODO: [Deprecated] + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + from ray.train.tensorflow import TensorflowConfig + + super(TensorflowTrainer, self).__init__( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + backend_config=tensorflow_config or TensorflowConfig(), + scaling_config=scaling_config, + dataset_config=dataset_config, + run_config=run_config, + datasets=datasets, + resume_from_checkpoint=resume_from_checkpoint, + metadata=metadata, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/torch/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/torch/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/torch/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80e5944aa58fb6e3960e4273465baf7af4efa912 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/torch/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/torch/__pycache__/torch_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/torch/__pycache__/torch_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..910758b79271c575e1333e60916bc9036f4c6a54 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/torch/__pycache__/torch_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/torch/__pycache__/train_loop_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/torch/__pycache__/train_loop_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11ae20a0be79f74b98fbd3453ce590fbb8aa62b0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/torch/__pycache__/train_loop_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/torch/torch_trainer.py b/venv/lib/python3.10/site-packages/ray/train/v2/torch/torch_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..a3bc1a7e9a8b4540ced253b6b12602d002933205 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/torch/torch_trainer.py @@ -0,0 +1,215 @@ +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union + +from ray.train import Checkpoint, DataConfig +from ray.train.trainer import GenDataset +from ray.train.v2.api.config import RunConfig, ScalingConfig +from ray.train.v2.api.data_parallel_trainer import DataParallelTrainer +from ray.util import PublicAPI + +if TYPE_CHECKING: + # NOTE: `ray.train.torch` module imports in this file will break + # with a circular import error if the TorchTrainer class is captured + # in the scope of a Ray task. + from ray.train.torch.config import TorchConfig + + +@PublicAPI(stability="stable") +class TorchTrainer(DataParallelTrainer): + """A Trainer for data parallel PyTorch training. + + At a high level, this Trainer does the following: + + 1. Launches multiple workers as defined by the ``scaling_config``. + 2. Sets up a distributed PyTorch environment + on these workers as defined by the ``torch_config``. + 3. Ingests the input ``datasets`` based on the ``dataset_config``. + 4. Runs the input ``train_loop_per_worker(train_loop_config)`` + on all workers. + + For more details, see: + + * :ref:`PyTorch Guide ` + * :ref:`PyTorch Lightning Guide ` + * :ref:`Hugging Face Transformers Guide ` + + Example: + + .. testcode:: + + import os + import tempfile + + import torch + from torch import nn + from torch.nn.parallel import DistributedDataParallel + + import ray + from ray.train import Checkpoint, CheckpointConfig, RunConfig, ScalingConfig + from ray.train.torch import TorchTrainer + + # If using GPUs, set this to True. + use_gpu = False + # Number of processes to run training on. + num_workers = 4 + + # Define your network structure. + class NeuralNetwork(nn.Module): + def __init__(self): + super(NeuralNetwork, self).__init__() + self.layer1 = nn.Linear(1, 32) + self.relu = nn.ReLU() + self.layer2 = nn.Linear(32, 1) + + def forward(self, input): + return self.layer2(self.relu(self.layer1(input))) + + # Training loop. + def train_loop_per_worker(config): + + # Read configurations. + lr = config["lr"] + batch_size = config["batch_size"] + num_epochs = config["num_epochs"] + + # Fetch training dataset. + train_dataset_shard = ray.train.get_dataset_shard("train") + + # Instantiate and prepare model for training. + model = NeuralNetwork() + model = ray.train.torch.prepare_model(model) + + # Define loss and optimizer. + loss_fn = nn.MSELoss() + optimizer = torch.optim.SGD(model.parameters(), lr=lr) + + # Create data loader. + dataloader = train_dataset_shard.iter_torch_batches( + batch_size=batch_size, dtypes=torch.float + ) + + # Train multiple epochs. + for epoch in range(num_epochs): + + # Train epoch. + for batch in dataloader: + output = model(batch["input"]) + loss = loss_fn(output, batch["label"]) + optimizer.zero_grad() + loss.backward() + optimizer.step() + + # Create checkpoint. + base_model = (model.module + if isinstance(model, DistributedDataParallel) else model) + checkpoint_dir = tempfile.mkdtemp() + torch.save( + {"model_state_dict": base_model.state_dict()}, + os.path.join(checkpoint_dir, "model.pt"), + ) + checkpoint = Checkpoint.from_directory(checkpoint_dir) + + # Report metrics and checkpoint. + ray.train.report({"loss": loss.item()}, checkpoint=checkpoint) + + + # Define configurations. + train_loop_config = {"num_epochs": 20, "lr": 0.01, "batch_size": 32} + scaling_config = ScalingConfig(num_workers=num_workers, use_gpu=use_gpu) + run_config = RunConfig(checkpoint_config=CheckpointConfig(num_to_keep=1)) + + # Define datasets. + train_dataset = ray.data.from_items( + [{"input": [x], "label": [2 * x + 1]} for x in range(2000)] + ) + datasets = {"train": train_dataset} + + # Initialize the Trainer. + trainer = TorchTrainer( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + scaling_config=scaling_config, + run_config=run_config, + datasets=datasets + ) + + # Train the model. + result = trainer.fit() + + # Inspect the results. + final_loss = result.metrics["loss"] + + .. testoutput:: + :hide: + + ... + + Args: + + train_loop_per_worker: The training function to execute on each worker. + This function can either take in zero arguments or a single ``Dict`` + argument which is set by defining ``train_loop_config``. + Within this function you can use any of the + :ref:`Ray Train Loop utilities `. + train_loop_config: A configuration ``Dict`` to pass in as an argument to + ``train_loop_per_worker``. + This is typically used for specifying hyperparameters. Passing large + datasets via `train_loop_config` is not recommended and may introduce + large overhead and unknown issues with serialization and deserialization. + torch_config: The configuration for setting up the PyTorch Distributed backend. + If set to None, a default configuration will be used in which + GPU training uses NCCL and CPU training uses Gloo. + scaling_config: The configuration for how to scale data parallel training. + ``num_workers`` determines how many Python processes are used for training, + and ``use_gpu`` determines whether or not each process should use GPUs. + See :class:`~ray.train.ScalingConfig` for more info. + run_config: The configuration for the execution of the training run. + See :class:`~ray.train.RunConfig` for more info. + datasets: The Ray Datasets to ingest for training. + Datasets are keyed by name (``{name: dataset}``). + Each dataset can be accessed from within the ``train_loop_per_worker`` + by calling ``ray.train.get_dataset_shard(name)``. + Sharding and additional configuration can be done by + passing in a ``dataset_config``. + dataset_config: The configuration for ingesting the input ``datasets``. + By default, all the Ray Dataset are split equally across workers. + See :class:`~ray.train.DataConfig` for more details. + resume_from_checkpoint: A checkpoint to resume training from. + This checkpoint can be accessed from within ``train_loop_per_worker`` + by calling ``ray.train.get_checkpoint()``. + metadata: Dict that should be made available via + `ray.train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + """ + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + torch_config: Optional["TorchConfig"] = None, + scaling_config: Optional[ScalingConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + dataset_config: Optional[DataConfig] = None, + # TODO: [Deprecated] + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + from ray.train.torch.config import TorchConfig + + torch_config = torch_config or TorchConfig() + if not torch_config.backend: + is_gpu_training = scaling_config and scaling_config.use_gpu + torch_config.backend = "nccl" if is_gpu_training else "gloo" + + super(TorchTrainer, self).__init__( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + backend_config=torch_config, + scaling_config=scaling_config, + run_config=run_config, + dataset_config=dataset_config, + datasets=datasets, + resume_from_checkpoint=resume_from_checkpoint, + metadata=metadata, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/torch/train_loop_utils.py b/venv/lib/python3.10/site-packages/ray/train/v2/torch/train_loop_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5cec6625c353346b58c4d3ac93efd048c7be4c3c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/torch/train_loop_utils.py @@ -0,0 +1,301 @@ +import logging +import os +import random +from typing import Any, Callable, Dict, Optional, Union + +import numpy as np +import torch +from packaging.version import Version +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import ( + DataLoader, + DistributedSampler, + IterableDataset, + RandomSampler, + SequentialSampler, +) + +import ray.train.torch +from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag +from ray.train.torch.train_loop_utils import _WrappedDataLoader +from ray.util.annotations import Deprecated, PublicAPI + +logger = logging.getLogger(__name__) + + +_TORCH_AMP_DEPRECATION_MESSAGE = ( + "The `accelerate`, `backward`, and `prepare_optimizer` utility methods " + "in the `ray.train.torch` module are deprecated and will be removed in a " + "future release. " + "Please use the native PyTorch mixed precision API directly, or " + "a library such as Lightning or HuggingFace Transformers/Accelerate. " + "See this issue for more context: " + "https://github.com/ray-project/ray/issues/49454" +) + + +def prepare_model( + model: torch.nn.Module, + move_to_device: Union[bool, torch.device] = True, + parallel_strategy: Optional[str] = "ddp", + parallel_strategy_kwargs: Optional[Dict[str, Any]] = None, +) -> torch.nn.Module: + """Prepares the model for distributed execution. + + This allows you to use the same exact code regardless of number of + workers or the device type being used (CPU, GPU). + + Args: + model (torch.nn.Module): A torch model to prepare. + move_to_device: Either a boolean indiciating whether to move + the model to the correct device or an actual device to + move the model to. If set to False, the model needs + to manually be moved to the correct device. + parallel_strategy ("ddp", "fsdp", or None): Whether to wrap models + in ``DistributedDataParallel``, ``FullyShardedDataParallel``, + or neither. + parallel_strategy_kwargs (Dict[str, Any]): Args to pass into + ``DistributedDataParallel`` or ``FullyShardedDataParallel`` + initialization if ``parallel_strategy`` is set to "ddp" + or "fsdp", respectively. + """ + if parallel_strategy == "fsdp" and Version(torch.__version__) < Version("1.11.0"): + raise ImportError( + "FullyShardedDataParallel requires torch>=1.11.0. " + "Run `pip install 'torch>=1.11.0'` to use FullyShardedDataParallel." + ) + + record_extra_usage_tag(TagKey.TRAIN_TORCH_PREPARE_MODEL, "1") + + parallel_strategy_kwargs = parallel_strategy_kwargs or {} + + rank = ray.train.get_context().get_local_rank() + + if isinstance(move_to_device, torch.device): + device = move_to_device + else: + device = ray.train.torch.get_device() + if isinstance(device, list): + device = device[0] + + if torch.cuda.is_available(): + torch.cuda.set_device(device) + + if move_to_device: + if rank == 0: + logger.info(f"Moving model to device: {device}") + else: + logger.debug(f"Moving model to device: {device}") + model = model.to(device) + + world_size = ray.train.get_context().get_world_size() + + if parallel_strategy and world_size > 1: + if parallel_strategy == "ddp": + DataParallel = DistributedDataParallel + if torch.cuda.is_available(): + parallel_strategy_kwargs = { + "device_ids": [device], + "output_device": device, + **parallel_strategy_kwargs, + } + else: + if not torch.cuda.is_available(): + raise RuntimeError( + "FSDP is only available with GPU-enabled " + "training. Set " + "`use_gpu=True` in your Trainer to train with " + "GPUs." + ) + from torch.distributed.fsdp import FullyShardedDataParallel + + DataParallel = FullyShardedDataParallel + if rank == 0: + logger.info(f"Wrapping provided model in {DataParallel.__name__}.") + else: + logger.debug(f"Wrapping provided model in {DataParallel.__name__}.") + model = DataParallel(model, **parallel_strategy_kwargs) + + return model + + +@PublicAPI(stability="stable") +def prepare_data_loader( + data_loader: torch.utils.data.DataLoader, + add_dist_sampler: bool = True, + move_to_device: bool = True, + auto_transfer: bool = True, +) -> torch.utils.data.DataLoader: + """Prepares :class:`~torch.utils.data.DataLoader` for distributed execution. + + This allows you to use the same exact code regardless of number of + workers or the device type being used (CPU, GPU). + + .. note:: + + This method adds a `DistributedSampler` to the `DataLoader` if the + number of training workers is greater than 1. If shuffling is + enabled on the original `DataLoader`, then `shuffle=True` will also + be passed into the `DistributedSampler` constructor. `shuffle=False` + on the original `DataLoader` also means that shuffling is disabled + on the sampler. + + With more than 1 worker, calling the `DistributedSampler.set_epoch` method + at the beginning of each epoch before creating the DataLoader iterator + is necessary to make shuffling work properly across multiple epochs. + Otherwise, the same ordering will be always used. + See: https://pytorch.org/docs/stable/data.html#torch.utils.data.distributed.DistributedSampler # noqa: E501 + + Example: + + .. testcode: + :skipif: True + + import torch + + import ray.train.torch + + train_dataloader = torch.utils.data.DataLoader( + ..., batch_size=..., shuffle=True + ) + train_dataloader = ray.train.torch.prepare_data_loader(train_loader) + + for epoch in range(10): + if ray.train.get_context().get_world_size() > 1: + # Required for the distributed sampler to shuffle properly across epochs + train_dataloader.sampler.set_epoch(epoch) + + for X, y in train_loader: + # No need to move data to GPU, this is done by `prepare_data_loader`! + # X, y = X.to("cuda"), y.to("cuda") + ... + + Args: + data_loader (torch.utils.data.DataLoader): The DataLoader to + prepare. + add_dist_sampler: Whether to add a DistributedSampler to + the provided DataLoader. + move_to_device: If set, automatically move the data + returned by the data loader to the correct device. + auto_transfer: If set and device is GPU, another CUDA stream + is created to automatically copy data from host (CPU) memory + to device (GPU) memory (the default CUDA stream still runs the + training procedure). If device is CPU, it will be disabled + regardless of the setting. This configuration will be ignored + if ``move_to_device`` is False. + """ + record_extra_usage_tag(TagKey.TRAIN_TORCH_PREPARE_DATALOADER, "1") + + world_size = ray.train.get_context().get_world_size() + world_rank = ray.train.get_context().get_world_rank() + + # Only add Distributed Sampler if the following conditions hold: + # 1. More than one training worker is being used. + # 2. A DistributedSampler has not already been added by the user. + # 3. The dataset is not an IterableDataset. Samplers do not worker with + # IterableDatasets. + if ( + world_size > 1 + and not isinstance(data_loader.sampler, DistributedSampler) + and not ( + hasattr(data_loader, "dataset") + and isinstance(data_loader.dataset, IterableDataset) + ) + and add_dist_sampler + ): + + def with_sampler(loader): + # Automatically set the DistributedSampler + + # If you're using a sampler, the DataLoader shuffle flag must be set to + # False. Shuffling is instead determined by the shuffle argument passed + # to the DistributedSampler constructor. + + # If no sampler is passed to the DataLoader constructor, Torch + # constructs a default sampler. The default sampler is a RandomSampler + # if shuffling is enabled and a SequentialSampler otherwise. DataLoader + # does not have a shuffle attribute, so we instead identify whether + # shuffling is enabled by checking the default sampler type. + shuffle = not isinstance(loader.sampler, SequentialSampler) + worker_init_fn: Optional[Callable[[int], None]] = loader.worker_init_fn + generator: Optional[torch.Generator] = loader.generator + + using_default_sampler = isinstance( + loader.sampler, (SequentialSampler, RandomSampler) + ) + if not using_default_sampler and world_rank == 0: + logger.warning( + f"The {loader.sampler.__class__.__name__} will be overwritten " + "with a DistributedSampler. You can disable this by setting " + "`with_sampler` to False in `prepare_data_loader`." + ) + + data_loader_args = { + "dataset": loader.dataset, + "batch_size": loader.batch_size, + "shuffle": False, + "num_workers": loader.num_workers, + "collate_fn": loader.collate_fn, + "pin_memory": loader.pin_memory, + "drop_last": loader.drop_last, + "timeout": loader.timeout, + "worker_init_fn": worker_init_fn, + "generator": generator, + "sampler": DistributedSampler(loader.dataset, shuffle=shuffle), + } + return DataLoader(**data_loader_args) + + data_loader = with_sampler(data_loader) + + if move_to_device: + device = ray.train.torch.get_device() + data_loader = _WrappedDataLoader(data_loader, device, auto_transfer) + + return data_loader + + +@Deprecated +def accelerate(amp: bool = False) -> None: + raise DeprecationWarning(_TORCH_AMP_DEPRECATION_MESSAGE) + + +@Deprecated +def prepare_optimizer(optimizer: torch.optim.Optimizer) -> torch.optim.Optimizer: + raise DeprecationWarning(_TORCH_AMP_DEPRECATION_MESSAGE) + + +@Deprecated +def backward(tensor: torch.Tensor) -> None: + raise DeprecationWarning(_TORCH_AMP_DEPRECATION_MESSAGE) + + +@PublicAPI(stability="stable") +def enable_reproducibility(seed: int = 0) -> None: + """Limits sources of nondeterministic behavior. + + This function: + + * Seeds PyTorch, Python, and NumPy. + * Disables CUDA convolution benchmarking. + * Configures PyTorch to use determinstic algorithms. + * Seeds workers spawned for multi-process data loading. + + Args: + seed: The number to seed libraries and data workers with. + + .. warning:: ``train.torch.enable_reproducibility()`` can't guarantee + completely reproducible results across executions. To learn more, read + the `PyTorch notes on randomness + `_. + """ + torch.manual_seed(seed) + random.seed(seed) + np.random.seed(seed) + + torch.use_deterministic_algorithms(True) + torch.backends.cudnn.benchmark = False + + # If you want to use deterministic algorithms with CUDA, then you need to set + # the CUBLAS_WORKSPACE_CONFIG environment variable; otherwise, Torch errors. + # See https://docs.nvidia.com/cuda/cublas/index.html#cublasApi_reproducibility. + os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/xgboost/__init__.py b/venv/lib/python3.10/site-packages/ray/train/v2/xgboost/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/xgboost/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/xgboost/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49e5356f6c2077ef6f708534f46e19b540081e65 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/xgboost/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/xgboost/__pycache__/xgboost_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/v2/xgboost/__pycache__/xgboost_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0b9e0975c6ebb3f7219afd38c5090100d65430e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/v2/xgboost/__pycache__/xgboost_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/v2/xgboost/xgboost_trainer.py b/venv/lib/python3.10/site-packages/ray/train/v2/xgboost/xgboost_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..5078e40ed3c5184537b265144ab96373765dc59f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/v2/xgboost/xgboost_trainer.py @@ -0,0 +1,171 @@ +import logging +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union + +import ray.train +from ray.train import Checkpoint +from ray.train.trainer import GenDataset +from ray.train.v2.api.config import RunConfig, ScalingConfig +from ray.train.v2.api.data_parallel_trainer import DataParallelTrainer +from ray.util.annotations import Deprecated + +if TYPE_CHECKING: + from ray.train.xgboost import XGBoostConfig + +logger = logging.getLogger(__name__) + + +class XGBoostTrainer(DataParallelTrainer): + """A Trainer for distributed data-parallel XGBoost training. + + Example + ------- + + .. testcode:: + + import xgboost + + import ray.data + import ray.train + from ray.train.xgboost import RayTrainReportCallback + from ray.train.xgboost import XGBoostTrainer + + def train_fn_per_worker(config: dict): + # (Optional) Add logic to resume training state from a checkpoint. + # ray.train.get_checkpoint() + + # 1. Get the dataset shard for the worker and convert to a `xgboost.DMatrix` + train_ds_iter, eval_ds_iter = ( + ray.train.get_dataset_shard("train"), + ray.train.get_dataset_shard("validation"), + ) + train_ds, eval_ds = train_ds_iter.materialize(), eval_ds_iter.materialize() + + train_df, eval_df = train_ds.to_pandas(), eval_ds.to_pandas() + train_X, train_y = train_df.drop("y", axis=1), train_df["y"] + eval_X, eval_y = eval_df.drop("y", axis=1), eval_df["y"] + + dtrain = xgboost.DMatrix(train_X, label=train_y) + deval = xgboost.DMatrix(eval_X, label=eval_y) + + params = { + "tree_method": "approx", + "objective": "reg:squarederror", + "eta": 1e-4, + "subsample": 0.5, + "max_depth": 2, + } + + # 2. Do distributed data-parallel training. + # Ray Train sets up the necessary coordinator processes and + # environment variables for your workers to communicate with each other. + bst = xgboost.train( + params, + dtrain=dtrain, + evals=[(deval, "validation")], + num_boost_round=10, + callbacks=[RayTrainReportCallback()], + ) + + train_ds = ray.data.from_items([{"x": x, "y": x + 1} for x in range(32)]) + eval_ds = ray.data.from_items([{"x": x, "y": x + 1} for x in range(16)]) + trainer = XGBoostTrainer( + train_fn_per_worker, + datasets={"train": train_ds, "validation": eval_ds}, + scaling_config=ray.train.ScalingConfig(num_workers=4), + ) + result = trainer.fit() + booster = RayTrainReportCallback.get_model(result.checkpoint) + + .. testoutput:: + :hide: + + ... + + Args: + train_loop_per_worker: The training function to execute on each worker. + This function can either take in zero arguments or a single ``Dict`` + argument which is set by defining ``train_loop_config``. + Within this function you can use any of the + :ref:`Ray Train Loop utilities `. + train_loop_config: A configuration ``Dict`` to pass in as an argument to + ``train_loop_per_worker``. + This is typically used for specifying hyperparameters. + xgboost_config: The configuration for setting up the distributed xgboost + backend. Defaults to using the "rabit" backend. + See :class:`~ray.train.xgboost.XGBoostConfig` for more info. + scaling_config: The configuration for how to scale data parallel training. + ``num_workers`` determines how many Python processes are used for training, + and ``use_gpu`` determines whether or not each process should use GPUs. + See :class:`~ray.train.ScalingConfig` for more info. + run_config: The configuration for the execution of the training run. + See :class:`~ray.train.RunConfig` for more info. + datasets: The Ray Datasets to ingest for training. + Datasets are keyed by name (``{name: dataset}``). + Each dataset can be accessed from within the ``train_loop_per_worker`` + by calling ``ray.train.get_dataset_shard(name)``. + Sharding and additional configuration can be done by + passing in a ``dataset_config``. + dataset_config: The configuration for ingesting the input ``datasets``. + By default, all the Ray Dataset are split equally across workers. + See :class:`~ray.train.DataConfig` for more details. + resume_from_checkpoint: A checkpoint to resume training from. + This checkpoint can be accessed from within ``train_loop_per_worker`` + by calling ``ray.train.get_checkpoint()``. + metadata: Dict that should be made available via + `ray.train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + """ + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + xgboost_config: Optional["XGBoostConfig"] = None, + scaling_config: Optional[ScalingConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + dataset_config: Optional[ray.train.DataConfig] = None, + # TODO: [Deprecated] + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + # TODO(justinvyu): [Deprecated] Legacy XGBoostTrainer API + label_column: Optional[str] = None, + params: Optional[Dict[str, Any]] = None, + num_boost_round: Optional[int] = None, + ): + if ( + label_column is not None + or params is not None + or num_boost_round is not None + ): + raise DeprecationWarning( + "The legacy XGBoostTrainer API is deprecated. " + "Please switch to passing in a custom `train_loop_per_worker` " + "function instead. " + "See this issue for more context: " + "https://github.com/ray-project/ray/issues/50042" + ) + + from ray.train.xgboost import XGBoostConfig + + super(XGBoostTrainer, self).__init__( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + backend_config=xgboost_config or XGBoostConfig(), + scaling_config=scaling_config, + dataset_config=dataset_config, + run_config=run_config, + datasets=datasets, + resume_from_checkpoint=resume_from_checkpoint, + metadata=metadata, + ) + + @classmethod + @Deprecated + def get_model(cls, checkpoint: Checkpoint): + """[Deprecated] Retrieve the XGBoost model stored in this checkpoint.""" + raise DeprecationWarning( + "`XGBoostTrainer.get_model` is deprecated. " + "Use `RayTrainReportCallback.get_model` instead." + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/__init__.py b/venv/lib/python3.10/site-packages/ray/train/xgboost/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa2d1c88d11b0b1049cf834fb75a39e669f5fbb2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/xgboost/__init__.py @@ -0,0 +1,20 @@ +from ray.train.v2._internal.constants import is_v2_enabled +from ray.train.xgboost._xgboost_utils import RayTrainReportCallback +from ray.train.xgboost.config import XGBoostConfig +from ray.train.xgboost.xgboost_checkpoint import XGBoostCheckpoint +from ray.train.xgboost.xgboost_predictor import XGBoostPredictor +from ray.train.xgboost.xgboost_trainer import XGBoostTrainer + +if is_v2_enabled(): + from ray.train.v2.xgboost.xgboost_trainer import XGBoostTrainer # noqa: F811 + +__all__ = [ + "RayTrainReportCallback", + "XGBoostCheckpoint", + "XGBoostConfig", + "XGBoostPredictor", + "XGBoostTrainer", +] + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f5b7f8b70e15294aebdaa0587adff00cfa9a5ea Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/_xgboost_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/_xgboost_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eda1f9a5d01423d5ae7c6ecbdd1d11e2a553519 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/_xgboost_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eab35698a8c02efed11a16befdca563b1261ca1d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/v2.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/v2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aa72f891b4f2c5dae98e6dd485f1453364332d5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/v2.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/xgboost_checkpoint.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/xgboost_checkpoint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6dadadcbc51e982c70fe3e5343847755804d6c5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/xgboost_checkpoint.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/xgboost_predictor.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/xgboost_predictor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5c214ed072676b88e1e5bab569021a843d8e5c6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/xgboost_predictor.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/xgboost_trainer.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/xgboost_trainer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf2db3854c1541c27d2505b700de95041111f4b3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/train/xgboost/__pycache__/xgboost_trainer.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/_xgboost_utils.py b/venv/lib/python3.10/site-packages/ray/train/xgboost/_xgboost_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..459dfcf07a2208659f469eb6769f5f3c5e2e8fbc --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/xgboost/_xgboost_utils.py @@ -0,0 +1,210 @@ +import tempfile +from collections import OrderedDict +from contextlib import contextmanager +from pathlib import Path +from typing import Callable, Dict, List, Optional, Union + +from xgboost.core import Booster + +import ray.train +from ray.train import Checkpoint +from ray.tune.utils import flatten_dict +from ray.util.annotations import PublicAPI + +try: + from xgboost.callback import TrainingCallback +except ImportError: + + class TrainingCallback: + pass + + +class TuneCallback(TrainingCallback): + # TODO(justinvyu): [code_removal] Remove this after enforcing min xgboost version. + """Base class for Tune's XGBoost callbacks.""" + + def __call__(self, env): + """Compatibility with xgboost<1.3""" + return self.after_iteration( + env.model, env.iteration, env.evaluation_result_list + ) + + def after_iteration(self, model: Booster, epoch: int, evals_log: Dict): + raise NotImplementedError + + +@PublicAPI(stability="beta") +class RayTrainReportCallback(TuneCallback): + """XGBoost callback to save checkpoints and report metrics. + + Args: + metrics: Metrics to report. If this is a list, + each item describes the metric key reported to XGBoost, + and it will be reported under the same name. + This can also be a dict of {: }, + which can be used to rename xgboost default metrics. + filename: Customize the saved checkpoint file type by passing + a filename. Defaults to "model.ubj". + frequency: How often to save checkpoints, in terms of iterations. + Defaults to 0 (no checkpoints are saved during training). + checkpoint_at_end: Whether or not to save a checkpoint at the end of training. + results_postprocessing_fn: An optional Callable that takes in + the metrics dict that will be reported (after it has been flattened) + and returns a modified dict. For example, this can be used to + average results across CV fold when using ``xgboost.cv``. + + Examples + -------- + + Reporting checkpoints and metrics to Ray Tune when running many + independent xgboost trials (without data parallelism within a trial). + + .. testcode:: + :skipif: True + + import xgboost + + from ray.tune import Tuner + from ray.train.xgboost import RayTrainReportCallback + + def train_fn(config): + # Report log loss to Ray Tune after each validation epoch. + bst = xgboost.train( + ..., + callbacks=[ + RayTrainReportCallback( + metrics={"loss": "eval-logloss"}, frequency=1 + ) + ], + ) + + tuner = Tuner(train_fn) + results = tuner.fit() + + Loading a model from a checkpoint reported by this callback. + + .. testcode:: + :skipif: True + + from ray.train.xgboost import RayTrainReportCallback + + # Get a `Checkpoint` object that is saved by the callback during training. + result = trainer.fit() + booster = RayTrainReportCallback.get_model(result.checkpoint) + + """ + + CHECKPOINT_NAME = "model.ubj" + + def __init__( + self, + metrics: Optional[Union[str, List[str], Dict[str, str]]] = None, + filename: str = CHECKPOINT_NAME, + frequency: int = 0, + checkpoint_at_end: bool = True, + results_postprocessing_fn: Optional[ + Callable[[Dict[str, Union[float, List[float]]]], Dict[str, float]] + ] = None, + ): + if isinstance(metrics, str): + metrics = [metrics] + self._metrics = metrics + self._filename = filename + self._frequency = frequency + self._checkpoint_at_end = checkpoint_at_end + self._results_postprocessing_fn = results_postprocessing_fn + + # Keeps track of the eval metrics from the last iteration, + # so that the latest metrics can be reported with the checkpoint + # at the end of training. + self._evals_log = None + # Keep track of the last checkpoint iteration to avoid double-checkpointing + # when using `checkpoint_at_end=True`. + self._last_checkpoint_iteration = None + + @classmethod + def get_model( + cls, checkpoint: Checkpoint, filename: str = CHECKPOINT_NAME + ) -> Booster: + """Retrieve the model stored in a checkpoint reported by this callback. + + Args: + checkpoint: The checkpoint object returned by a training run. + The checkpoint should be saved by an instance of this callback. + filename: The filename to load the model from, which should match + the filename used when creating the callback. + """ + with checkpoint.as_directory() as checkpoint_path: + booster = Booster() + booster.load_model(Path(checkpoint_path, filename).as_posix()) + return booster + + def _get_report_dict(self, evals_log): + if isinstance(evals_log, OrderedDict): + # xgboost>=1.3 + result_dict = flatten_dict(evals_log, delimiter="-") + for k in list(result_dict): + result_dict[k] = result_dict[k][-1] + else: + # xgboost<1.3 + result_dict = dict(evals_log) + if not self._metrics: + report_dict = result_dict + else: + report_dict = {} + for key in self._metrics: + if isinstance(self._metrics, dict): + metric = self._metrics[key] + else: + metric = key + report_dict[key] = result_dict[metric] + + if self._results_postprocessing_fn: + report_dict = self._results_postprocessing_fn(report_dict) + + return report_dict + + @contextmanager + def _get_checkpoint(self, model: Booster) -> Optional[Checkpoint]: + # NOTE: The world rank returns None for Tune usage without Train. + if ray.train.get_context().get_world_rank() in (0, None): + with tempfile.TemporaryDirectory() as temp_checkpoint_dir: + model.save_model(Path(temp_checkpoint_dir, self._filename).as_posix()) + yield Checkpoint(temp_checkpoint_dir) + else: + yield None + + def after_iteration(self, model: Booster, epoch: int, evals_log: Dict): + self._evals_log = evals_log + + checkpointing_disabled = self._frequency == 0 + # Ex: if frequency=2, checkpoint at epoch 1, 3, 5, ... (counting from 0) + should_checkpoint = ( + not checkpointing_disabled and (epoch + 1) % self._frequency == 0 + ) + + report_dict = self._get_report_dict(evals_log) + if should_checkpoint: + self._last_checkpoint_iteration = epoch + with self._get_checkpoint(model=model) as checkpoint: + ray.train.report(report_dict, checkpoint=checkpoint) + else: + ray.train.report(report_dict) + + def after_training(self, model: Booster) -> Booster: + if not self._checkpoint_at_end: + return model + + if ( + self._last_checkpoint_iteration is not None + and model.num_boosted_rounds() - 1 == self._last_checkpoint_iteration + ): + # Avoids a duplicate checkpoint if the checkpoint frequency happens + # to align with the last iteration. + return model + + report_dict = self._get_report_dict(self._evals_log) if self._evals_log else {} + with self._get_checkpoint(model=model) as checkpoint: + ray.train.report(report_dict, checkpoint=checkpoint) + + return model diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/config.py b/venv/lib/python3.10/site-packages/ray/train/xgboost/config.py new file mode 100644 index 0000000000000000000000000000000000000000..725326c70ffbff9d679c7498fe2f01c77e0c0531 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/xgboost/config.py @@ -0,0 +1,202 @@ +import json +import logging +import os +import threading +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Optional + +import xgboost +from packaging.version import Version +from xgboost import RabitTracker +from xgboost.collective import CommunicatorContext + +import ray +from ray.train._internal.worker_group import WorkerGroup +from ray.train.backend import Backend, BackendConfig + +logger = logging.getLogger(__name__) + + +@dataclass +class XGBoostConfig(BackendConfig): + """Configuration for xgboost collective communication setup. + + Ray Train will set up the necessary coordinator processes and environment + variables for your workers to communicate with each other. + Additional configuration options can be passed into the + `xgboost.collective.CommunicatorContext` that wraps your own `xgboost.train` code. + + See the `xgboost.collective` module for more information: + https://github.com/dmlc/xgboost/blob/master/python-package/xgboost/collective.py + + Args: + xgboost_communicator: The backend to use for collective communication for + distributed xgboost training. For now, only "rabit" is supported. + """ + + xgboost_communicator: str = "rabit" + + @property + def train_func_context(self): + @contextmanager + def collective_communication_context(): + with CommunicatorContext(**_get_xgboost_args()): + yield + + return collective_communication_context + + @property + def backend_cls(self): + if self.xgboost_communicator == "rabit": + return ( + _XGBoostRabitBackend + if Version(xgboost.__version__) >= Version("2.1.0") + else _XGBoostRabitBackend_pre_xgb210 + ) + + raise NotImplementedError(f"Unsupported backend: {self.xgboost_communicator}") + + +class _XGBoostRabitBackend(Backend): + def __init__(self): + self._tracker: Optional[RabitTracker] = None + self._wait_thread: Optional[threading.Thread] = None + + def _setup_xgboost_distributed_backend(self, worker_group: WorkerGroup): + # Set up the rabit tracker on the Train driver. + num_workers = len(worker_group) + rabit_args = {"n_workers": num_workers} + train_driver_ip = ray.util.get_node_ip_address() + + # NOTE: sortby="task" is needed to ensure that the xgboost worker ranks + # align with Ray Train worker ranks. + # The worker ranks will be sorted by `dmlc_task_id`, + # which is defined below. + self._tracker = RabitTracker( + n_workers=num_workers, host_ip=train_driver_ip, sortby="task" + ) + self._tracker.start() + + # The RabitTracker is started in a separate thread, and the + # `wait_for` method must be called for `worker_args` to return. + self._wait_thread = threading.Thread(target=self._tracker.wait_for, daemon=True) + self._wait_thread.start() + + rabit_args.update(self._tracker.worker_args()) + + start_log = ( + "RabitTracker coordinator started with parameters:\n" + f"{json.dumps(rabit_args, indent=2)}" + ) + logger.debug(start_log) + + def set_xgboost_communicator_args(args): + import ray.train + + args["dmlc_task_id"] = ( + f"[xgboost.ray-rank={ray.train.get_context().get_world_rank():08}]:" + f"{ray.get_runtime_context().get_actor_id()}" + ) + + _set_xgboost_args(args) + + worker_group.execute(set_xgboost_communicator_args, rabit_args) + + def on_training_start( + self, worker_group: WorkerGroup, backend_config: XGBoostConfig + ): + assert backend_config.xgboost_communicator == "rabit" + self._setup_xgboost_distributed_backend(worker_group) + + def on_shutdown(self, worker_group: WorkerGroup, backend_config: XGBoostConfig): + timeout = 5 + + if self._wait_thread is not None: + self._wait_thread.join(timeout=timeout) + + if self._wait_thread.is_alive(): + logger.warning( + "During shutdown, the RabitTracker thread failed to join " + f"within {timeout} seconds. " + "The process will still be terminated as part of Ray actor cleanup." + ) + + +class _XGBoostRabitBackend_pre_xgb210(Backend): + def __init__(self): + self._tracker: Optional[RabitTracker] = None + + def _setup_xgboost_distributed_backend(self, worker_group: WorkerGroup): + # Set up the rabit tracker on the Train driver. + num_workers = len(worker_group) + rabit_args = {"DMLC_NUM_WORKER": num_workers} + train_driver_ip = ray.util.get_node_ip_address() + + # NOTE: sortby="task" is needed to ensure that the xgboost worker ranks + # align with Ray Train worker ranks. + # The worker ranks will be sorted by `DMLC_TASK_ID`, + # which is defined below. + self._tracker = RabitTracker( + n_workers=num_workers, host_ip=train_driver_ip, sortby="task" + ) + self._tracker.start(n_workers=num_workers) + + worker_args = self._tracker.worker_envs() + rabit_args.update(worker_args) + + start_log = ( + "RabitTracker coordinator started with parameters:\n" + f"{json.dumps(rabit_args, indent=2)}" + ) + logger.debug(start_log) + + def set_xgboost_env_vars(): + import ray.train + + for k, v in rabit_args.items(): + os.environ[k] = str(v) + + # Ranks are assigned in increasing order of the worker's task id. + # This task id will be sorted by increasing world rank. + os.environ["DMLC_TASK_ID"] = ( + f"[xgboost.ray-rank={ray.train.get_context().get_world_rank():08}]:" + f"{ray.get_runtime_context().get_actor_id()}" + ) + + worker_group.execute(set_xgboost_env_vars) + + def on_training_start( + self, worker_group: WorkerGroup, backend_config: XGBoostConfig + ): + assert backend_config.xgboost_communicator == "rabit" + self._setup_xgboost_distributed_backend(worker_group) + + def on_shutdown(self, worker_group: WorkerGroup, backend_config: XGBoostConfig): + if not self._tracker: + return + + timeout = 5 + self._tracker.thread.join(timeout=timeout) + + if self._tracker.thread.is_alive(): + logger.warning( + "During shutdown, the RabitTracker thread failed to join " + f"within {timeout} seconds. " + "The process will still be terminated as part of Ray actor cleanup." + ) + + +_xgboost_args: dict = {} +_xgboost_args_lock = threading.Lock() + + +def _set_xgboost_args(args): + with _xgboost_args_lock: + global _xgboost_args + _xgboost_args = args + + +def _get_xgboost_args() -> dict: + with _xgboost_args_lock: + return _xgboost_args diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/v2.py b/venv/lib/python3.10/site-packages/ray/train/xgboost/v2.py new file mode 100644 index 0000000000000000000000000000000000000000..8d87dcd5d932bb632682d6d89475dc12341a7537 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/xgboost/v2.py @@ -0,0 +1,132 @@ +import logging +from typing import Any, Callable, Dict, Optional, Union + +import ray.train +from ray.train import Checkpoint +from ray.train.data_parallel_trainer import DataParallelTrainer +from ray.train.trainer import GenDataset +from ray.train.xgboost import XGBoostConfig + +logger = logging.getLogger(__name__) + + +class XGBoostTrainer(DataParallelTrainer): + """A Trainer for distributed data-parallel XGBoost training. + + Example + ------- + + .. testcode:: + + import xgboost + + import ray.data + import ray.train + from ray.train.xgboost import RayTrainReportCallback, XGBoostTrainer + + def train_fn_per_worker(config: dict): + # (Optional) Add logic to resume training state from a checkpoint. + # ray.train.get_checkpoint() + + # 1. Get the dataset shard for the worker and convert to a `xgboost.DMatrix` + train_ds_iter, eval_ds_iter = ( + ray.train.get_dataset_shard("train"), + ray.train.get_dataset_shard("validation"), + ) + train_ds, eval_ds = train_ds_iter.materialize(), eval_ds_iter.materialize() + + train_df, eval_df = train_ds.to_pandas(), eval_ds.to_pandas() + train_X, train_y = train_df.drop("y", axis=1), train_df["y"] + eval_X, eval_y = eval_df.drop("y", axis=1), eval_df["y"] + + dtrain = xgboost.DMatrix(train_X, label=train_y) + deval = xgboost.DMatrix(eval_X, label=eval_y) + + params = { + "tree_method": "approx", + "objective": "reg:squarederror", + "eta": 1e-4, + "subsample": 0.5, + "max_depth": 2, + } + + # 2. Do distributed data-parallel training. + # Ray Train sets up the necessary coordinator processes and + # environment variables for your workers to communicate with each other. + bst = xgboost.train( + params, + dtrain=dtrain, + evals=[(deval, "validation")], + num_boost_round=10, + callbacks=[RayTrainReportCallback()], + ) + + train_ds = ray.data.from_items([{"x": x, "y": x + 1} for x in range(32)]) + eval_ds = ray.data.from_items([{"x": x, "y": x + 1} for x in range(16)]) + trainer = XGBoostTrainer( + train_fn_per_worker, + datasets={"train": train_ds, "validation": eval_ds}, + scaling_config=ray.train.ScalingConfig(num_workers=4), + ) + result = trainer.fit() + booster = RayTrainReportCallback.get_model(result.checkpoint) + + .. testoutput:: + :hide: + + ... + + Args: + train_loop_per_worker: The training function to execute on each worker. + This function can either take in zero arguments or a single ``Dict`` + argument which is set by defining ``train_loop_config``. + Within this function you can use any of the + :ref:`Ray Train Loop utilities `. + train_loop_config: A configuration ``Dict`` to pass in as an argument to + ``train_loop_per_worker``. + This is typically used for specifying hyperparameters. + xgboost_config: The configuration for setting up the distributed xgboost + backend. Defaults to using the "rabit" backend. + See :class:`~ray.train.xgboost.XGBoostConfig` for more info. + datasets: The Ray Datasets to use for training and validation. + dataset_config: The configuration for ingesting the input ``datasets``. + By default, all the Ray Datasets are split equally across workers. + See :class:`~ray.train.DataConfig` for more details. + scaling_config: The configuration for how to scale data parallel training. + ``num_workers`` determines how many Python processes are used for training, + and ``use_gpu`` determines whether or not each process should use GPUs. + See :class:`~ray.train.ScalingConfig` for more info. + run_config: The configuration for the execution of the training run. + See :class:`~ray.train.RunConfig` for more info. + resume_from_checkpoint: A checkpoint to resume training from. + This checkpoint can be accessed from within ``train_loop_per_worker`` + by calling ``ray.train.get_checkpoint()``. + metadata: Dict that should be made available via + `ray.train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + """ + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + xgboost_config: Optional[XGBoostConfig] = None, + scaling_config: Optional[ray.train.ScalingConfig] = None, + run_config: Optional[ray.train.RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + dataset_config: Optional[ray.train.DataConfig] = None, + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + super(XGBoostTrainer, self).__init__( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + backend_config=xgboost_config or XGBoostConfig(), + scaling_config=scaling_config, + dataset_config=dataset_config, + run_config=run_config, + datasets=datasets, + resume_from_checkpoint=resume_from_checkpoint, + metadata=metadata, + ) diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/xgboost_checkpoint.py b/venv/lib/python3.10/site-packages/ray/train/xgboost/xgboost_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..fc8b70465b5c01f85d8f16f841eda2c0969748b8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/xgboost/xgboost_checkpoint.py @@ -0,0 +1,75 @@ +import tempfile +from pathlib import Path +from typing import TYPE_CHECKING, Optional + +import xgboost + +from ray.train._internal.framework_checkpoint import FrameworkCheckpoint +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.data.preprocessor import Preprocessor + + +@PublicAPI(stability="beta") +class XGBoostCheckpoint(FrameworkCheckpoint): + """A :py:class:`~ray.train.Checkpoint` with XGBoost-specific functionality.""" + + MODEL_FILENAME = "model.json" + + @classmethod + def from_model( + cls, + booster: xgboost.Booster, + *, + preprocessor: Optional["Preprocessor"] = None, + path: Optional[str] = None, + ) -> "XGBoostCheckpoint": + """Create a :py:class:`~ray.train.Checkpoint` that stores an XGBoost + model. + + Args: + booster: The XGBoost model to store in the checkpoint. + preprocessor: A fitted preprocessor to be applied before inference. + path: The path to the directory where the checkpoint file will be saved. + This should start as an empty directory, since the *entire* + directory will be treated as the checkpoint when reported. + By default, a temporary directory will be created. + + Returns: + An :py:class:`XGBoostCheckpoint` containing the specified ``Estimator``. + + Examples: + + ... testcode:: + + import numpy as np + import ray + from ray.train.xgboost import XGBoostCheckpoint + import xgboost + + train_X = np.array([[1, 2], [3, 4]]) + train_y = np.array([0, 1]) + + model = xgboost.XGBClassifier().fit(train_X, train_y) + checkpoint = XGBoostCheckpoint.from_model(model.get_booster()) + + """ + checkpoint_path = Path(path or tempfile.mkdtemp()) + + if not checkpoint_path.is_dir(): + raise ValueError(f"`path` must be a directory, but got: {checkpoint_path}") + + booster.save_model(checkpoint_path.joinpath(cls.MODEL_FILENAME).as_posix()) + + checkpoint = cls.from_directory(checkpoint_path.as_posix()) + if preprocessor: + checkpoint.set_preprocessor(preprocessor) + return checkpoint + + def get_model(self) -> xgboost.Booster: + """Retrieve the XGBoost model stored in this checkpoint.""" + with self.as_directory() as checkpoint_path: + booster = xgboost.Booster() + booster.load_model(Path(checkpoint_path, self.MODEL_FILENAME).as_posix()) + return booster diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/xgboost_predictor.py b/venv/lib/python3.10/site-packages/ray/train/xgboost/xgboost_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..1b319b93b299bc02a5b83a2f1cdcfa1e8fab6e8e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/xgboost/xgboost_predictor.py @@ -0,0 +1,160 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union + +import pandas as pd +import xgboost + +from ray.air.constants import TENSOR_COLUMN_NAME +from ray.air.data_batch_type import DataBatchType +from ray.air.util.data_batch_conversion import _unwrap_ndarray_object_type_if_needed +from ray.train.predictor import Predictor +from ray.train.xgboost import XGBoostCheckpoint +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.data.preprocessor import Preprocessor + + +@PublicAPI(stability="beta") +class XGBoostPredictor(Predictor): + """A predictor for XGBoost models. + + Args: + model: The XGBoost booster to use for predictions. + preprocessor: A preprocessor used to transform data batches prior + to prediction. + """ + + def __init__( + self, model: xgboost.Booster, preprocessor: Optional["Preprocessor"] = None + ): + self.model = model + super().__init__(preprocessor) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(model={self.model!r}, " + f"preprocessor={self._preprocessor!r})" + ) + + @classmethod + def from_checkpoint(cls, checkpoint: XGBoostCheckpoint) -> "XGBoostPredictor": + """Instantiate the predictor from a Checkpoint. + + This is a helper constructor that instantiates the predictor from a + framework-specific XGBoost checkpoint. + + Args: + checkpoint: The checkpoint to load the model and preprocessor from. + + """ + model = checkpoint.get_model() + preprocessor = checkpoint.get_preprocessor() + return cls(model=model, preprocessor=preprocessor) + + def predict( + self, + data: DataBatchType, + feature_columns: Optional[Union[List[str], List[int]]] = None, + dmatrix_kwargs: Optional[Dict[str, Any]] = None, + **predict_kwargs, + ) -> DataBatchType: + """Run inference on data batch. + + The data is converted into an XGBoost DMatrix before being inputted to + the model. + + Args: + data: A batch of input data. + feature_columns: The names or indices of the columns in the + data to use as features to predict on. If None, then use + all columns in ``data``. + dmatrix_kwargs: Dict of keyword arguments passed to ``xgboost.DMatrix``. + **predict_kwargs: Keyword arguments passed to ``xgboost.Booster.predict``. + + + Examples: + + .. testcode:: + + import numpy as np + import xgboost as xgb + from ray.train.xgboost import XGBoostPredictor + train_X = np.array([[1, 2], [3, 4]]) + train_y = np.array([0, 1]) + model = xgb.XGBClassifier().fit(train_X, train_y) + predictor = XGBoostPredictor(model=model.get_booster()) + data = np.array([[1, 2], [3, 4]]) + predictions = predictor.predict(data) + # Only use first and second column as the feature + data = np.array([[1, 2, 8], [3, 4, 9]]) + predictions = predictor.predict(data, feature_columns=[0, 1]) + + .. testcode:: + + import pandas as pd + import xgboost as xgb + from ray.train.xgboost import XGBoostPredictor + train_X = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) + train_y = pd.Series([0, 1]) + model = xgb.XGBClassifier().fit(train_X, train_y) + predictor = XGBoostPredictor(model=model.get_booster()) + # Pandas dataframe. + data = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) + predictions = predictor.predict(data) + # Only use first and second column as the feature + data = pd.DataFrame([[1, 2, 8], [3, 4, 9]], columns=["A", "B", "C"]) + predictions = predictor.predict(data, feature_columns=["A", "B"]) + + + Returns: + Prediction result. + + """ + return Predictor.predict( + self, + data, + feature_columns=feature_columns, + dmatrix_kwargs=dmatrix_kwargs, + **predict_kwargs, + ) + + def _predict_pandas( + self, + data: "pd.DataFrame", + feature_columns: Optional[Union[List[str], List[int]]] = None, + dmatrix_kwargs: Optional[Dict[str, Any]] = None, + **predict_kwargs, + ) -> "pd.DataFrame": + dmatrix_kwargs = dmatrix_kwargs or {} + + feature_names = None + if TENSOR_COLUMN_NAME in data: + data = data[TENSOR_COLUMN_NAME].to_numpy() + data = _unwrap_ndarray_object_type_if_needed(data) + if feature_columns: + # In this case feature_columns is a list of integers + data = data[:, feature_columns] + elif feature_columns: + # feature_columns is a list of integers or strings + data = data[feature_columns].to_numpy() + # Only set the feature names if they are strings + if all(isinstance(fc, str) for fc in feature_columns): + feature_names = feature_columns + else: + feature_columns = data.columns.tolist() + data = data.to_numpy() + + if all(isinstance(fc, str) for fc in feature_columns): + feature_names = feature_columns + + if feature_names: + dmatrix_kwargs["feature_names"] = feature_names + + matrix = xgboost.DMatrix(data, **dmatrix_kwargs) + df = pd.DataFrame(self.model.predict(matrix, **predict_kwargs)) + df.columns = ( + ["predictions"] + if len(df.columns) == 1 + else [f"predictions_{i}" for i in range(len(df.columns))] + ) + return df diff --git a/venv/lib/python3.10/site-packages/ray/train/xgboost/xgboost_trainer.py b/venv/lib/python3.10/site-packages/ray/train/xgboost/xgboost_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..07004caa691c38a138779289e747e9643b9d9746 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/train/xgboost/xgboost_trainer.py @@ -0,0 +1,318 @@ +import logging +from functools import partial +from typing import Any, Callable, Dict, Optional, Union + +import xgboost +from packaging.version import Version + +import ray.train +from ray.train import Checkpoint +from ray.train.constants import TRAIN_DATASET_KEY +from ray.train.trainer import GenDataset +from ray.train.xgboost import RayTrainReportCallback, XGBoostConfig +from ray.train.xgboost.v2 import XGBoostTrainer as SimpleXGBoostTrainer +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + + +LEGACY_XGBOOST_TRAINER_DEPRECATION_MESSAGE = ( + "Passing in `xgboost.train` kwargs such as `params`, `num_boost_round`, " + "`label_column`, etc. to `XGBoostTrainer` is deprecated " + "in favor of the new API which accepts a ``train_loop_per_worker`` argument, " + "similar to the other DataParallelTrainer APIs (ex: TorchTrainer). " + "See this issue for more context: " + "https://github.com/ray-project/ray/issues/50042" +) + + +def _xgboost_train_fn_per_worker( + config: dict, + label_column: str, + num_boost_round: int, + dataset_keys: set, + xgboost_train_kwargs: dict, +): + checkpoint = ray.train.get_checkpoint() + starting_model = None + remaining_iters = num_boost_round + if checkpoint: + starting_model = RayTrainReportCallback.get_model(checkpoint) + starting_iter = starting_model.num_boosted_rounds() + remaining_iters = num_boost_round - starting_iter + logger.info( + f"Model loaded from checkpoint will train for " + f"additional {remaining_iters} iterations (trees) in order " + "to achieve the target number of iterations " + f"({num_boost_round=})." + ) + + train_ds_iter = ray.train.get_dataset_shard(TRAIN_DATASET_KEY) + train_df = train_ds_iter.materialize().to_pandas() + + eval_ds_iters = { + k: ray.train.get_dataset_shard(k) + for k in dataset_keys + if k != TRAIN_DATASET_KEY + } + eval_dfs = {k: d.materialize().to_pandas() for k, d in eval_ds_iters.items()} + + train_X, train_y = train_df.drop(label_column, axis=1), train_df[label_column] + dtrain = xgboost.DMatrix(train_X, label=train_y) + + # NOTE: Include the training dataset in the evaluation datasets. + # This allows `train-*` metrics to be calculated and reported. + evals = [(dtrain, TRAIN_DATASET_KEY)] + + for eval_name, eval_df in eval_dfs.items(): + eval_X, eval_y = eval_df.drop(label_column, axis=1), eval_df[label_column] + evals.append((xgboost.DMatrix(eval_X, label=eval_y), eval_name)) + + evals_result = {} + xgboost.train( + config, + dtrain=dtrain, + evals=evals, + evals_result=evals_result, + num_boost_round=remaining_iters, + xgb_model=starting_model, + **xgboost_train_kwargs, + ) + + +@PublicAPI(stability="beta") +class XGBoostTrainer(SimpleXGBoostTrainer): + """A Trainer for distributed data-parallel XGBoost training. + + Example + ------- + + .. testcode:: + + import xgboost + + import ray.data + import ray.train + from ray.train.xgboost import RayTrainReportCallback, XGBoostTrainer + + def train_fn_per_worker(config: dict): + # (Optional) Add logic to resume training state from a checkpoint. + # ray.train.get_checkpoint() + + # 1. Get the dataset shard for the worker and convert to a `xgboost.DMatrix` + train_ds_iter, eval_ds_iter = ( + ray.train.get_dataset_shard("train"), + ray.train.get_dataset_shard("validation"), + ) + train_ds, eval_ds = train_ds_iter.materialize(), eval_ds_iter.materialize() + + train_df, eval_df = train_ds.to_pandas(), eval_ds.to_pandas() + train_X, train_y = train_df.drop("y", axis=1), train_df["y"] + eval_X, eval_y = eval_df.drop("y", axis=1), eval_df["y"] + + dtrain = xgboost.DMatrix(train_X, label=train_y) + deval = xgboost.DMatrix(eval_X, label=eval_y) + + params = { + "tree_method": "approx", + "objective": "reg:squarederror", + "eta": 1e-4, + "subsample": 0.5, + "max_depth": 2, + } + + # 2. Do distributed data-parallel training. + # Ray Train sets up the necessary coordinator processes and + # environment variables for your workers to communicate with each other. + bst = xgboost.train( + params, + dtrain=dtrain, + evals=[(deval, "validation")], + num_boost_round=10, + callbacks=[RayTrainReportCallback()], + ) + + train_ds = ray.data.from_items([{"x": x, "y": x + 1} for x in range(32)]) + eval_ds = ray.data.from_items([{"x": x, "y": x + 1} for x in range(16)]) + trainer = XGBoostTrainer( + train_fn_per_worker, + datasets={"train": train_ds, "validation": eval_ds}, + scaling_config=ray.train.ScalingConfig(num_workers=4), + ) + result = trainer.fit() + booster = RayTrainReportCallback.get_model(result.checkpoint) + + .. testoutput:: + :hide: + + ... + + Args: + train_loop_per_worker: The training function to execute on each worker. + This function can either take in zero arguments or a single ``Dict`` + argument which is set by defining ``train_loop_config``. + Within this function you can use any of the + :ref:`Ray Train Loop utilities `. + train_loop_config: A configuration ``Dict`` to pass in as an argument to + ``train_loop_per_worker``. + This is typically used for specifying hyperparameters. + xgboost_config: The configuration for setting up the distributed xgboost + backend. Defaults to using the "rabit" backend. + See :class:`~ray.train.xgboost.XGBoostConfig` for more info. + datasets: The Ray Datasets to use for training and validation. + dataset_config: The configuration for ingesting the input ``datasets``. + By default, all the Ray Datasets are split equally across workers. + See :class:`~ray.train.DataConfig` for more details. + scaling_config: The configuration for how to scale data parallel training. + ``num_workers`` determines how many Python processes are used for training, + and ``use_gpu`` determines whether or not each process should use GPUs. + See :class:`~ray.train.ScalingConfig` for more info. + run_config: The configuration for the execution of the training run. + See :class:`~ray.train.RunConfig` for more info. + resume_from_checkpoint: A checkpoint to resume training from. + This checkpoint can be accessed from within ``train_loop_per_worker`` + by calling ``ray.train.get_checkpoint()``. + metadata: Dict that should be made available via + `ray.train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + label_column: [Deprecated] Name of the label column. A column with this name + must be present in the training dataset. + params: [Deprecated] XGBoost training parameters. + Refer to `XGBoost documentation `_ + for a list of possible parameters. + num_boost_round: [Deprecated] Target number of boosting iterations (trees in the model). + Note that unlike in ``xgboost.train``, this is the target number + of trees, meaning that if you set ``num_boost_round=10`` and pass a model + that has already been trained for 5 iterations, it will be trained for 5 + iterations more, instead of 10 more. + **train_kwargs: [Deprecated] Additional kwargs passed to ``xgboost.train()`` function. + """ + + _handles_checkpoint_freq = True + _handles_checkpoint_at_end = True + + def __init__( + self, + train_loop_per_worker: Optional[ + Union[Callable[[], None], Callable[[Dict], None]] + ] = None, + *, + train_loop_config: Optional[Dict] = None, + xgboost_config: Optional[XGBoostConfig] = None, + scaling_config: Optional[ray.train.ScalingConfig] = None, + run_config: Optional[ray.train.RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + dataset_config: Optional[ray.train.DataConfig] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + metadata: Optional[Dict[str, Any]] = None, + # TODO(justinvyu): [Deprecated] Legacy XGBoostTrainer API + label_column: Optional[str] = None, + params: Optional[Dict[str, Any]] = None, + num_boost_round: Optional[int] = None, + **train_kwargs, + ): + if Version(xgboost.__version__) < Version("1.7.0"): + raise ImportError( + "`XGBoostTrainer` requires the `xgboost` version to be >= 1.7.0. " + 'Upgrade with: `pip install -U "xgboost>=1.7"`' + ) + + # TODO(justinvyu): [Deprecated] Legacy XGBoostTrainer API + legacy_api = train_loop_per_worker is None + if legacy_api: + train_loop_per_worker = self._get_legacy_train_fn_per_worker( + xgboost_train_kwargs=train_kwargs, + run_config=run_config, + label_column=label_column, + num_boost_round=num_boost_round, + datasets=datasets, + ) + train_loop_config = params or {} + # TODO(justinvyu): [Deprecated] Legacy XGBoostTrainer API + # elif train_kwargs: + # _log_deprecation_warning( + # "Passing `xgboost.train` kwargs to `XGBoostTrainer` is deprecated. " + # "Please pass in a `train_loop_per_worker` function instead, " + # "which has full flexibility on the call to `xgboost.train(**kwargs)`. " + # f"{LEGACY_XGBOOST_TRAINER_DEPRECATION_MESSAGE}" + # ) + + super(XGBoostTrainer, self).__init__( + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + xgboost_config=xgboost_config, + scaling_config=scaling_config, + run_config=run_config, + datasets=datasets, + dataset_config=dataset_config, + resume_from_checkpoint=resume_from_checkpoint, + metadata=metadata, + ) + + def _get_legacy_train_fn_per_worker( + self, + xgboost_train_kwargs: Dict, + run_config: Optional[ray.train.RunConfig], + datasets: Optional[Dict[str, GenDataset]], + label_column: Optional[str], + num_boost_round: Optional[int], + ) -> Callable[[Dict], None]: + """Get the training function for the legacy XGBoostTrainer API.""" + + datasets = datasets or {} + if not datasets.get(TRAIN_DATASET_KEY): + raise ValueError( + "`datasets` must be provided for the XGBoostTrainer API " + "if `train_loop_per_worker` is not provided. " + "This dict must contain the training dataset under the " + f"key: '{TRAIN_DATASET_KEY}'. " + f"Got keys: {list(datasets.keys())}" + ) + if not label_column: + raise ValueError( + "`label_column` must be provided for the XGBoostTrainer API " + "if `train_loop_per_worker` is not provided. " + "This is the column name of the label in the dataset." + ) + + num_boost_round = num_boost_round or 10 + + # TODO(justinvyu): [Deprecated] Legacy XGBoostTrainer API + # _log_deprecation_warning(LEGACY_XGBOOST_TRAINER_DEPRECATION_MESSAGE) + + # Initialize a default Ray Train metrics/checkpoint reporting callback if needed + callbacks = xgboost_train_kwargs.get("callbacks", []) + user_supplied_callback = any( + isinstance(callback, RayTrainReportCallback) for callback in callbacks + ) + callback_kwargs = {} + if run_config: + checkpoint_frequency = run_config.checkpoint_config.checkpoint_frequency + checkpoint_at_end = run_config.checkpoint_config.checkpoint_at_end + + callback_kwargs["frequency"] = checkpoint_frequency + # Default `checkpoint_at_end=True` unless the user explicitly sets it. + callback_kwargs["checkpoint_at_end"] = ( + checkpoint_at_end if checkpoint_at_end is not None else True + ) + + if not user_supplied_callback: + callbacks.append(RayTrainReportCallback(**callback_kwargs)) + xgboost_train_kwargs["callbacks"] = callbacks + + train_fn_per_worker = partial( + _xgboost_train_fn_per_worker, + label_column=label_column, + num_boost_round=num_boost_round, + dataset_keys=set(datasets), + xgboost_train_kwargs=xgboost_train_kwargs, + ) + return train_fn_per_worker + + @classmethod + def get_model( + cls, + checkpoint: Checkpoint, + ) -> xgboost.Booster: + """Retrieve the XGBoost model stored in this checkpoint.""" + return RayTrainReportCallback.get_model(checkpoint) diff --git a/venv/lib/python3.10/site-packages/ray/tune/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7f49e6e41d0eeb22cb2161a55aab14802cf9b0e4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/__init__.py @@ -0,0 +1,114 @@ +# isort: off +# Try import ray[tune] core requirements (defined in setup.py) +try: + import fsspec # noqa: F401 + import pandas # noqa: F401 + import pyarrow # noqa: F401 + import requests # noqa: F401 +except ImportError as exc: + raise ImportError( + "Can't import ray.tune as some dependencies are missing. " + 'Run `pip install "ray[tune]"` to fix.' + ) from exc +# isort: on + +from ray.tune.trainable.trainable_fn_utils import Checkpoint, get_checkpoint, report +from ray.tune.impl.config import CheckpointConfig, FailureConfig, RunConfig +from ray.tune.syncer import SyncConfig +from ray.air.result import Result +from ray.tune.analysis import ExperimentAnalysis +from ray.tune.callback import Callback +from ray.tune.context import TuneContext, get_context +from ray.tune.error import TuneError +from ray.tune.execution.placement_groups import PlacementGroupFactory +from ray.tune.experiment import Experiment +from ray.tune.progress_reporter import ( + CLIReporter, + JupyterNotebookReporter, + ProgressReporter, +) +from ray.tune.registry import register_env, register_trainable +from ray.tune.result_grid import ResultGrid +from ray.tune.schedulers import create_scheduler +from ray.tune.search import create_searcher, grid_search +from ray.tune.search.sample import ( + choice, + lograndint, + loguniform, + qlograndint, + qloguniform, + qrandint, + qrandn, + quniform, + randint, + randn, + sample_from, + uniform, +) +from ray.tune.stopper import Stopper +from ray.tune.trainable import Trainable +from ray.tune.trainable.util import with_parameters, with_resources +from ray.tune.tune import run, run_experiments +from ray.tune.tune_config import ResumeConfig, TuneConfig +from ray.tune.tuner import Tuner + +__all__ = [ + "Trainable", + "Callback", + "TuneError", + "grid_search", + "register_env", + "register_trainable", + "run", + "run_experiments", + "with_parameters", + "with_resources", + "Stopper", + "Experiment", + "sample_from", + "uniform", + "quniform", + "choice", + "randint", + "lograndint", + "qrandint", + "qlograndint", + "randn", + "qrandn", + "loguniform", + "qloguniform", + "ExperimentAnalysis", + "CLIReporter", + "JupyterNotebookReporter", + "ProgressReporter", + "ResultGrid", + "create_searcher", + "create_scheduler", + "PlacementGroupFactory", + "Tuner", + "TuneConfig", + "ResumeConfig", + "RunConfig", + "CheckpointConfig", + "FailureConfig", + "Result", + "Checkpoint", + "get_checkpoint", + "report", + "get_context", + "TuneContext", + "SyncConfig", +] + +report.__module__ = "ray.tune" +get_checkpoint.__module__ = "ray.tune" +get_context.__module__ = "ray.tune" +TuneContext.__module__ = "ray.tune" +Checkpoint.__module__ = "ray.tune" +Result.__module__ = "ray.tune" +RunConfig.__module__ = "ray.tune" +CheckpointConfig.__module__ = "ray.tune" +FailureConfig.__module__ = "ray.tune" + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/venv/lib/python3.10/site-packages/ray/tune/analysis/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6dcbf77f1c566d0ec577a0eaffc7502284bedaf4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/analysis/__init__.py @@ -0,0 +1,3 @@ +from ray.tune.analysis.experiment_analysis import ExperimentAnalysis + +__all__ = ["ExperimentAnalysis"] diff --git a/venv/lib/python3.10/site-packages/ray/tune/analysis/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/analysis/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..717698e8273161f2709b90b3928054c5bab5d400 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/analysis/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/analysis/__pycache__/experiment_analysis.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/analysis/__pycache__/experiment_analysis.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b24334e95abb4ba59c67c56b3288c2e99ceaff2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/analysis/__pycache__/experiment_analysis.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/analysis/experiment_analysis.py b/venv/lib/python3.10/site-packages/ray/tune/analysis/experiment_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..f84b74ac72fc2fe339f446f9616be58d1dc2fdb0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/analysis/experiment_analysis.py @@ -0,0 +1,678 @@ +import copy +import io +import json +import logging +import os +from numbers import Number +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +import pyarrow.fs + +from ray.air.constants import EXPR_PROGRESS_FILE, EXPR_RESULT_FILE, TRAINING_ITERATION +from ray.train._internal.storage import _exists_at_fs_path, get_fs_and_path +from ray.tune import Checkpoint +from ray.tune.execution.experiment_state import _find_newest_experiment_checkpoint +from ray.tune.execution.tune_controller import TuneController +from ray.tune.experiment import Trial +from ray.tune.result import CONFIG_PREFIX, DEFAULT_METRIC +from ray.tune.utils import flatten_dict +from ray.tune.utils.serialization import TuneFunctionDecoder +from ray.tune.utils.util import is_nan, is_nan_or_inf, unflattened_lookup +from ray.util.annotations import PublicAPI + +try: + import pandas as pd + from pandas import DataFrame +except ImportError: + pd = None + DataFrame = None + + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="beta") +class ExperimentAnalysis: + """Analyze results from a Ray Train/Tune experiment. + + To use this class, the run must store the history of reported metrics + in log files (e.g., `result.json` and `progress.csv`). + This is the default behavior, unless default loggers are explicitly excluded + with the `TUNE_DISABLE_AUTO_CALLBACK_LOGGERS=1` environment variable. + + Parameters: + experiment_checkpoint_path: Path to an `experiment_state.json` file, + or a directory that contains an `experiment_state.json` file. + default_metric: Default metric for comparing results. Can be + overwritten with the ``metric`` parameter in the respective + functions. + default_mode: Default mode for comparing results. Has to be one + of [min, max]. Can be overwritten with the ``mode`` parameter + in the respective functions. + trials: List of trials that can be accessed via `analysis.trials`. + """ + + def __init__( + self, + experiment_checkpoint_path: Union[str, os.PathLike], + *, + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + trials: Optional[List[Trial]] = None, + default_metric: Optional[str] = None, + default_mode: Optional[str] = None, + ): + self.default_metric = default_metric + if default_mode and default_mode not in ["min", "max"]: + raise ValueError("`default_mode` has to be None or one of [min, max]") + self.default_mode = default_mode + if self.default_metric is None and self.default_mode is not None: + # If only a mode was passed, use anonymous metric + self.default_metric = DEFAULT_METRIC + + # Resolve the filesystem if not specified. + if storage_filesystem: + self._fs = storage_filesystem + else: + self._fs, experiment_checkpoint_path = get_fs_and_path( + experiment_checkpoint_path + ) + + # Find the json state file. + experiment_checkpoint_path = str(experiment_checkpoint_path) + if experiment_checkpoint_path.endswith(".json"): + self._experiment_fs_path = os.path.dirname(experiment_checkpoint_path) + self._experiment_json_fs_path = experiment_checkpoint_path + else: + self._experiment_fs_path = experiment_checkpoint_path + + experiment_json_fs_path = _find_newest_experiment_checkpoint( + experiment_path=self._experiment_fs_path, fs=self._fs + ) + if experiment_json_fs_path is None: + pattern = TuneController.CKPT_FILE_TMPL.format("*") + raise ValueError( + f"No experiment snapshot file of form '{pattern}' was found at: " + f"({self._fs.type_name}, {self._experiment_fs_path})\n" + "Please check if you specified the correct experiment path, " + "which should be a combination of the `storage_path` and `name` " + "specified in your run." + ) + + self._experiment_json_fs_path = experiment_json_fs_path + + self.trials = trials or self._load_trials() + self._trial_dataframes = self._fetch_trial_dataframes() + self._configs = self.get_all_configs() + + def _load_trials(self) -> List[Trial]: + with self._fs.open_input_stream(self._experiment_json_fs_path) as f: + experiment_state = json.loads(f.readall(), cls=TuneFunctionDecoder) + + experiment_fs_path = Path(self._experiment_fs_path) + + trials = [] + trial_states = experiment_state["trial_data"] + for trial_json_state, trial_runtime_metadata in trial_states: + trial = Trial.from_json_state(trial_json_state, stub=True) + trial.restore_run_metadata(trial_runtime_metadata) + + new_storage = copy.copy(trial.storage) + new_storage.storage_fs_path = experiment_fs_path.parent.as_posix() + new_storage.storage_filesystem = self._fs + new_storage.experiment_dir_name = experiment_fs_path.name + trial.set_storage(new_storage) + + trials.append(trial) + return trials + + def _fetch_trial_dataframe(self, trial: Trial) -> DataFrame: + force_dtype = {"trial_id": str} # Never convert trial_id to float. + + # If there were no reported results, there will be no files into a DataFrame + if trial.last_result is None: + return DataFrame() + + json_fs_path = Path(trial.storage.trial_fs_path, EXPR_RESULT_FILE).as_posix() + csv_fs_path = Path(trial.storage.trial_fs_path, EXPR_PROGRESS_FILE).as_posix() + # Prefer reading the JSON if it exists. + if _exists_at_fs_path(trial.storage.storage_filesystem, json_fs_path): + with trial.storage.storage_filesystem.open_input_stream(json_fs_path) as f: + content = f.readall().decode("utf-8").rstrip("\n") + if not content: + return DataFrame() + json_list = [json.loads(row) for row in content.split("\n")] + df = pd.json_normalize(json_list, sep="/") + # Fallback to reading the CSV. + elif _exists_at_fs_path(trial.storage.storage_filesystem, csv_fs_path): + with trial.storage.storage_filesystem.open_input_stream(csv_fs_path) as f: + csv_str = f.readall().decode("utf-8") + df = pd.read_csv(io.StringIO(csv_str), dtype=force_dtype) + else: + raise FileNotFoundError( + f"Could not fetch metrics for {trial}: both {EXPR_RESULT_FILE} and " + f"{EXPR_PROGRESS_FILE} were not found at {trial.storage.trial_fs_path}" + ) + + return df + + def _fetch_trial_dataframes(self) -> Dict[str, DataFrame]: + """Fetches trial dataframes from files. + + Returns: + A dictionary mapping trial_id -> pd.DataFrame + """ + failures = [] + + trial_dfs = {} + for trial in self.trials: + try: + trial_dfs[trial.trial_id] = self._fetch_trial_dataframe(trial) + except Exception as e: + failures.append((trial, e)) + trial_dfs[trial.trial_id] = DataFrame() + continue + + if failures: + fail_str = "\n".join( + [f"- {trial}: {repr(error)}" for trial, error in failures] + ) + logger.warning( + f"Failed to fetch metrics for {len(failures)} trial(s):\n{fail_str}" + ) + return trial_dfs + + def get_all_configs(self, prefix: bool = False) -> Dict[str, Dict]: + """Returns all trial hyperparameter configurations. + + Args: + prefix: If True, flattens the config dict + and prepends `config/`. + + Returns: + Dict[str, Dict]: Mapping trial_id -> config dict + """ + return { + trial.trial_id: ( + flatten_dict({CONFIG_PREFIX: trial.config}) if prefix else trial.config + ) + for trial in self.trials + } + + @property + def experiment_path(self) -> str: + """Path pointing to the experiment directory on persistent storage. + + This can point to a remote storage location (e.g. S3) or to a local + location (path on the head node).""" + return self._experiment_fs_path + + @property + def best_trial(self) -> Trial: + """Get the best trial of the experiment + + The best trial is determined by comparing the last trial results + using the `metric` and `mode` parameters passed to `tune.run()`. + + If you didn't pass these parameters, use + `get_best_trial(metric, mode, scope)` instead. + """ + if not self.default_metric or not self.default_mode: + raise ValueError( + "To fetch the `best_trial`, pass a `metric` and `mode` " + "parameter to `tune.run()`. Alternatively, use the " + "`get_best_trial(metric, mode)` method to set the metric " + "and mode explicitly." + ) + return self.get_best_trial(self.default_metric, self.default_mode) + + @property + def best_config(self) -> Dict: + """Get the config of the best trial of the experiment + + The best trial is determined by comparing the last trial results + using the `metric` and `mode` parameters passed to `tune.run()`. + + If you didn't pass these parameters, use + `get_best_config(metric, mode, scope)` instead. + """ + if not self.default_metric or not self.default_mode: + raise ValueError( + "To fetch the `best_config`, pass a `metric` and `mode` " + "parameter to `tune.run()`. Alternatively, use the " + "`get_best_config(metric, mode)` method to set the metric " + "and mode explicitly." + ) + return self.get_best_config(self.default_metric, self.default_mode) + + @property + def best_checkpoint(self) -> Checkpoint: + """Get the checkpoint path of the best trial of the experiment + + The best trial is determined by comparing the last trial results + using the `metric` and `mode` parameters passed to `tune.run()`. + + If you didn't pass these parameters, use + `get_best_checkpoint(trial, metric, mode)` instead. + + Returns: + :class:`Checkpoint ` object. + """ + if not self.default_metric or not self.default_mode: + raise ValueError( + "To fetch the `best_checkpoint`, pass a `metric` and `mode` " + "parameter to `tune.run()`. Alternatively, use the " + "`get_best_checkpoint(trial, metric, mode)` method to set the " + "metric and mode explicitly." + ) + best_trial = self.best_trial + if not best_trial: + raise ValueError( + f"No best trial found. Please check if you specified the " + f"correct default metric ({self.default_metric}) and mode " + f"({self.default_mode})." + ) + return self.get_best_checkpoint( + best_trial, self.default_metric, self.default_mode + ) + + @property + def best_dataframe(self) -> DataFrame: + """Get the full result dataframe of the best trial of the experiment + + The best trial is determined by comparing the last trial results + using the `metric` and `mode` parameters passed to `tune.run()`. + + If you didn't pass these parameters, use + `get_best_trial(metric, mode)` and use it to look for the dataframe + in the `self.trial_dataframes` dict. + """ + if not self.default_metric or not self.default_mode: + raise ValueError( + "To fetch the `best_result`, pass a `metric` and `mode` " + "parameter to `tune.run()`." + ) + return self.trial_dataframes[self.best_trial.trial_id] + + @property + def best_result(self) -> Dict: + """Get the last result of the best trial of the experiment + + The best trial is determined by comparing the last trial results + using the `metric` and `mode` parameters passed to `tune.run()`. + + If you didn't pass these parameters, use + `get_best_trial(metric, mode, scope).last_result` instead. + """ + if not self.default_metric or not self.default_mode: + raise ValueError( + "To fetch the `best_result`, pass a `metric` and `mode` " + "parameter to `tune.run()`. Alternatively, use " + "`get_best_trial(metric, mode).last_result` to set " + "the metric and mode explicitly and fetch the last result." + ) + return self.best_trial.last_result + + def _delimiter(self): + return os.environ.get("TUNE_RESULT_DELIM", "/") + + @property + def best_result_df(self) -> DataFrame: + """Get the best result of the experiment as a pandas dataframe. + + The best trial is determined by comparing the last trial results + using the `metric` and `mode` parameters passed to `tune.run()`. + + If you didn't pass these parameters, use + `get_best_trial(metric, mode, scope).last_result` instead. + """ + if not pd: + raise ValueError( + "`best_result_df` requires pandas. Install with " + "`pip install pandas`." + ) + + best_result = flatten_dict(self.best_result, delimiter=self._delimiter()) + return pd.DataFrame.from_records([best_result], index="trial_id") + + @property + def results(self) -> Dict[str, Dict]: + """Get the last result of the all trials of the experiment""" + return {trial.trial_id: trial.last_result for trial in self.trials} + + @property + def results_df(self) -> DataFrame: + """Get all the last results as a pandas dataframe.""" + if not pd: + raise ValueError( + "`results_df` requires pandas. Install with `pip install pandas`." + ) + return pd.DataFrame.from_records( + [ + flatten_dict(trial.last_result, delimiter=self._delimiter()) + for trial in self.trials + ], + index="trial_id", + ) + + @property + def trial_dataframes(self) -> Dict[str, DataFrame]: + """List of all dataframes of the trials. + + Each dataframe is indexed by iterations and contains reported + metrics. + """ + return self._trial_dataframes + + def dataframe( + self, metric: Optional[str] = None, mode: Optional[str] = None + ) -> DataFrame: + """Returns a pandas.DataFrame object constructed from the trials. + + This function will look through all observed results of each trial + and return the one corresponding to the passed ``metric`` and + ``mode``: If ``mode=min``, it returns the result with the lowest + *ever* observed ``metric`` for this trial (this is not necessarily + the last)! For ``mode=max``, it's the highest, respectively. If + ``metric=None`` or ``mode=None``, the last result will be returned. + + Args: + metric: Key for trial info to order on. If None, uses last result. + mode: One of [None, "min", "max"]. + + Returns: + pd.DataFrame: Constructed from a result dict of each trial. + """ + # Do not validate metric/mode here or set from default metric/mode! + # Otherwise we will get confusing results as the lowest ever observed + # result may not be the last result. + if mode and mode not in ["min", "max"]: + raise ValueError("If set, `mode` has to be one of [min, max]") + + if mode and not metric: + raise ValueError( + "If a `mode` is passed to `ExperimentAnalysis.dataframe()," + " you'll also have to pass a `metric`!" + ) + + rows = self._retrieve_rows(metric=metric, mode=mode) + all_configs = self.get_all_configs(prefix=True) + for path, config in all_configs.items(): + if path in rows: + rows[path].update(config) + rows[path].update(logdir=path) + return pd.DataFrame(list(rows.values())) + + def _get_trial_checkpoints_with_metric( + self, trial: Trial, metric: Optional[str] = None + ) -> List[Tuple[Checkpoint, Number]]: + """Get all checkpoints and a specified metric of a trial. + + Args: + trial: The log directory of a trial, or a trial instance. + metric: key for trial info to return, e.g. "mean_accuracy". + "training_iteration" is used by default if no value was + passed to ``self.default_metric``. + + Returns: + List of [Checkpoint, metric] for all checkpoints of the trial. + """ + metric = metric or self.default_metric or TRAINING_ITERATION + + best_checkpoint_results = ( + trial.run_metadata.checkpoint_manager.best_checkpoint_results + ) + best_checkpoints = [ + (checkpoint_result.checkpoint, checkpoint_result.metrics) + for checkpoint_result in best_checkpoint_results + ] + # Support nested metrics given as flattened strings, e.g. + # "info/learner/default_policy/policy_loss". + return [ + (checkpoint, unflattened_lookup(metric, metrics)) + for checkpoint, metrics in best_checkpoints + ] + + def get_best_checkpoint( + self, + trial: Trial, + metric: Optional[str] = None, + mode: Optional[str] = None, + ) -> Optional[Checkpoint]: + """Gets best persistent checkpoint path of provided trial. + + Any checkpoints with an associated metric value of ``nan`` will be filtered out. + + Args: + trial: The log directory of a trial, or a trial instance. + metric: key of trial info to return, e.g. "mean_accuracy". + "training_iteration" is used by default if no value was + passed to ``self.default_metric``. + mode: One of [min, max]. Defaults to ``self.default_mode``. + + Returns: + A :class:`Checkpoint ` object + """ + metric = metric or self.default_metric or TRAINING_ITERATION + mode = self._validate_mode(mode) + + checkpoints_and_metrics = self._get_trial_checkpoints_with_metric(trial, metric) + + # Filter out nan. Sorting nan values leads to undefined behavior. + checkpoints_and_metrics = list( + filter(lambda x: not is_nan(x[1]), checkpoints_and_metrics) + ) + + if not checkpoints_and_metrics: + logger.error(f"No checkpoints have been found for trial {trial}.") + return None + + score_order_factor = -1 if mode == "min" else 1 + best_checkpoint, _ = max( + checkpoints_and_metrics, key=lambda x: score_order_factor * x[1] + ) + return best_checkpoint + + def get_best_trial( + self, + metric: Optional[str] = None, + mode: Optional[str] = None, + scope: str = "last", + filter_nan_and_inf: bool = True, + ) -> Optional[Trial]: + """Retrieve the best trial object. + + Compares all trials' scores on ``metric``. + If ``metric`` is not specified, ``self.default_metric`` will be used. + If `mode` is not specified, ``self.default_mode`` will be used. + These values are usually initialized by passing the ``metric`` and + ``mode`` parameters to ``tune.run()``. + + Args: + metric: Key for trial info to order on. Defaults to + ``self.default_metric``. + mode: One of [min, max]. Defaults to ``self.default_mode``. + scope: One of [all, last, avg, last-5-avg, last-10-avg]. + If `scope=last`, only look at each trial's final step for + `metric`, and compare across trials based on `mode=[min,max]`. + If `scope=avg`, consider the simple average over all steps + for `metric` and compare across trials based on + `mode=[min,max]`. If `scope=last-5-avg` or `scope=last-10-avg`, + consider the simple average over the last 5 or 10 steps for + `metric` and compare across trials based on `mode=[min,max]`. + If `scope=all`, find each trial's min/max score for `metric` + based on `mode`, and compare trials based on `mode=[min,max]`. + filter_nan_and_inf: If True (default), NaN or infinite + values are disregarded and these trials are never selected as + the best trial. + + Returns: + The best trial for the provided metric. If no trials contain the provided + metric, or if the value for the metric is NaN for all trials, + then returns None. + """ + if len(self.trials) == 1: + return self.trials[0] + + metric = self._validate_metric(metric) + mode = self._validate_mode(mode) + + if scope not in ["all", "last", "avg", "last-5-avg", "last-10-avg"]: + raise ValueError( + "ExperimentAnalysis: attempting to get best trial for " + 'metric {} for scope {} not in ["all", "last", "avg", ' + '"last-5-avg", "last-10-avg"]. ' + "If you didn't pass a `metric` parameter to `tune.run()`, " + "you have to pass one when fetching the best trial.".format( + metric, scope + ) + ) + best_trial = None + best_metric_score = None + + for trial in self.trials: + if metric not in trial.metric_analysis: + continue + + if scope in ["last", "avg", "last-5-avg", "last-10-avg"]: + metric_score = trial.metric_analysis[metric][scope] + else: + metric_score = trial.metric_analysis[metric][mode] + + if filter_nan_and_inf and is_nan_or_inf(metric_score): + continue + + if best_metric_score is None: + best_metric_score = metric_score + best_trial = trial + continue + + if (mode == "max") and (best_metric_score < metric_score): + best_metric_score = metric_score + best_trial = trial + elif (mode == "min") and (best_metric_score > metric_score): + best_metric_score = metric_score + best_trial = trial + + if not best_trial: + logger.warning( + "Could not find best trial. Did you pass the correct `metric` " + "parameter?" + ) + return best_trial + + def get_best_config( + self, + metric: Optional[str] = None, + mode: Optional[str] = None, + scope: str = "last", + ) -> Optional[Dict]: + """Retrieve the best config corresponding to the trial. + + Compares all trials' scores on `metric`. + If ``metric`` is not specified, ``self.default_metric`` will be used. + If `mode` is not specified, ``self.default_mode`` will be used. + These values are usually initialized by passing the ``metric`` and + ``mode`` parameters to ``tune.run()``. + + Args: + metric: Key for trial info to order on. Defaults to + ``self.default_metric``. + mode: One of [min, max]. Defaults to ``self.default_mode``. + scope: One of [all, last, avg, last-5-avg, last-10-avg]. + If `scope=last`, only look at each trial's final step for + `metric`, and compare across trials based on `mode=[min,max]`. + If `scope=avg`, consider the simple average over all steps + for `metric` and compare across trials based on + `mode=[min,max]`. If `scope=last-5-avg` or `scope=last-10-avg`, + consider the simple average over the last 5 or 10 steps for + `metric` and compare across trials based on `mode=[min,max]`. + If `scope=all`, find each trial's min/max score for `metric` + based on `mode`, and compare trials based on `mode=[min,max]`. + """ + best_trial = self.get_best_trial(metric, mode, scope) + return best_trial.config if best_trial else None + + def get_last_checkpoint( + self, trial=None, metric="training_iteration", mode="max" + ) -> Optional[Checkpoint]: + """Gets the last checkpoint of the provided trial, + i.e., with the highest "training_iteration". + + If no trial is specified, it loads the best trial according to the + provided metric and mode (defaults to max. training iteration). + + Args: + trial: If None, load the best trial automatically. + metric: If no trial is specified, use this metric to identify + the best trial and load the last checkpoint from this trial. + mode: If no trial is specified, use the metric and this mode + to identify the best trial and load the last checkpoint from it. + + Returns: + Path for last checkpoint of trial + """ + trial = trial or self.get_best_trial(metric, mode) + return self.get_best_checkpoint(trial, TRAINING_ITERATION, "max") + + def _validate_metric(self, metric: str) -> str: + if not metric and not self.default_metric: + raise ValueError( + "No `metric` has been passed and `default_metric` has " + "not been set. Please specify the `metric` parameter." + ) + return metric or self.default_metric + + def _validate_mode(self, mode: str) -> str: + if not mode and not self.default_mode: + raise ValueError( + "No `mode` has been passed and `default_mode` has " + "not been set. Please specify the `mode` parameter." + ) + if mode and mode not in ["min", "max"]: + raise ValueError("If set, `mode` has to be one of [min, max]") + return mode or self.default_mode + + def _retrieve_rows( + self, metric: Optional[str] = None, mode: Optional[str] = None + ) -> Dict[str, Any]: + assert mode is None or mode in ["max", "min"] + assert not mode or metric + rows = {} + for path, df in self.trial_dataframes.items(): + if df.empty: + continue + if metric not in df: + idx = -1 + elif mode == "max": + idx = df[metric].idxmax() + elif mode == "min": + idx = df[metric].idxmin() + else: + idx = -1 + try: + rows[path] = df.iloc[idx].to_dict() + except TypeError: + # idx is nan + logger.warning( + "Warning: Non-numerical value(s) encountered for {}".format(path) + ) + + return rows + + def __getstate__(self) -> Dict[str, Any]: + """Ensure that trials are marked as stubs when pickling, + so that they can be loaded later without the trainable + being registered. + """ + state = self.__dict__.copy() + + def make_stub_if_needed(trial: Trial) -> Trial: + if trial.stub: + return trial + trial_copy = Trial(trial.trainable_name, stub=True) + trial_copy.__setstate__(trial.__getstate__()) + return trial_copy + + state["trials"] = [make_stub_if_needed(t) for t in state["trials"]] + return state diff --git a/venv/lib/python3.10/site-packages/ray/tune/automl/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/automl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..24a70c9ef10e6e09db27739525f15df94ce99dd5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/automl/__init__.py @@ -0,0 +1 @@ +raise DeprecationWarning("`ray.tune.automl` is deprecated in Ray 2.6.") diff --git a/venv/lib/python3.10/site-packages/ray/tune/automl/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/automl/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c286706009d2528f5d143ee9a36525baef1c5d2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/automl/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/callback.py b/venv/lib/python3.10/site-packages/ray/tune/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..666c6a592ecb3ec9121cb5a14c4db09b4706d05f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/callback.py @@ -0,0 +1,512 @@ +import glob +import warnings +from abc import ABCMeta +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple + +import ray.tune +from ray.tune.utils.util import _atomic_save, _load_newest_checkpoint +from ray.util.annotations import DeveloperAPI, PublicAPI + +if TYPE_CHECKING: + from ray.tune.experiment import Trial + from ray.tune.stopper import Stopper + + +class _CallbackMeta(ABCMeta): + """A helper metaclass to ensure container classes (e.g. CallbackList) have + implemented all the callback methods (e.g. `on_*`). + """ + + def __new__(mcs, name: str, bases: Tuple[type], attrs: Dict[str, Any]) -> type: + cls = super().__new__(mcs, name, bases, attrs) + + if mcs.need_check(cls, name, bases, attrs): + mcs.check(cls, name, bases, attrs) + + return cls + + @classmethod + def need_check( + mcs, cls: type, name: str, bases: Tuple[type], attrs: Dict[str, Any] + ) -> bool: + return attrs.get("IS_CALLBACK_CONTAINER", False) + + @classmethod + def check( + mcs, cls: type, name: str, bases: Tuple[type], attrs: Dict[str, Any] + ) -> None: + methods = set() + for base in bases: + methods.update( + attr_name + for attr_name, attr in vars(base).items() + if mcs.need_override_by_subclass(attr_name, attr) + ) + overridden = { + attr_name + for attr_name, attr in attrs.items() + if mcs.need_override_by_subclass(attr_name, attr) + } + missing = methods.difference(overridden) + if missing: + raise TypeError( + f"Found missing callback method: {missing} " + f"in class {cls.__module__}.{cls.__qualname__}." + ) + + @classmethod + def need_override_by_subclass(mcs, attr_name: str, attr: Any) -> bool: + return ( + ( + attr_name.startswith("on_") + and not attr_name.startswith("on_trainer_init") + ) + or attr_name == "setup" + ) and callable(attr) + + +@PublicAPI(stability="beta") +class Callback(metaclass=_CallbackMeta): + """Tune base callback that can be extended and passed to a ``TrialRunner`` + + Tune callbacks are called from within the ``TrialRunner`` class. There are + several hooks that can be used, all of which are found in the submethod + definitions of this base class. + + The parameters passed to the ``**info`` dict vary between hooks. The + parameters passed are described in the docstrings of the methods. + + This example will print a metric each time a result is received: + + .. testcode:: + + from ray import tune + from ray.tune import Callback + + + class MyCallback(Callback): + def on_trial_result(self, iteration, trials, trial, result, + **info): + print(f"Got result: {result['metric']}") + + + def train_func(config): + for i in range(10): + tune.report(metric=i) + + tuner = tune.Tuner( + train_func, + run_config=tune.RunConfig( + callbacks=[MyCallback()] + ) + ) + tuner.fit() + + .. testoutput:: + :hide: + + ... + """ + + # File templates for any artifacts written by this callback + # These files should live in the `trial.local_path` for each trial. + # TODO(ml-team): Make this more visible to users to override. Internal use for now. + _SAVED_FILE_TEMPLATES = [] + + # arguments here match Experiment.public_spec + def setup( + self, + stop: Optional["Stopper"] = None, + num_samples: Optional[int] = None, + total_num_samples: Optional[int] = None, + **info, + ): + """Called once at the very beginning of training. + + Any Callback setup should be added here (setting environment + variables, etc.) + + Arguments: + stop: Stopping criteria. + If ``time_budget_s`` was passed to ``tune.RunConfig``, a + ``TimeoutStopper`` will be passed here, either by itself + or as a part of a ``CombinedStopper``. + num_samples: Number of times to sample from the + hyperparameter space. Defaults to 1. If `grid_search` is + provided as an argument, the grid will be repeated + `num_samples` of times. If this is -1, (virtually) infinite + samples are generated until a stopping condition is met. + total_num_samples: Total number of samples factoring + in grid search samplers. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_step_begin(self, iteration: int, trials: List["Trial"], **info): + """Called at the start of each tuning loop step. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_step_end(self, iteration: int, trials: List["Trial"], **info): + """Called at the end of each tuning loop step. + + The iteration counter is increased before this hook is called. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_start( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after starting a trial instance. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has been started. + **info: Kwargs dict for forward compatibility. + + """ + pass + + def on_trial_restore( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after restoring a trial instance. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has been restored. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_save( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after receiving a checkpoint from a trial. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just saved a checkpoint. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_result( + self, + iteration: int, + trials: List["Trial"], + trial: "Trial", + result: Dict, + **info, + ): + """Called after receiving a result from a trial. + + The search algorithm and scheduler are notified before this + hook is called. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just sent a result. + result: Result that the trial sent. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_complete( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after a trial instance completed. + + The search algorithm and scheduler are notified before this + hook is called. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has been completed. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_recover( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after a trial instance failed (errored) but the trial is scheduled + for retry. + + The search algorithm and scheduler are not notified. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has errored. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_error( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after a trial instance failed (errored). + + The search algorithm and scheduler are notified before this + hook is called. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has errored. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_checkpoint( + self, + iteration: int, + trials: List["Trial"], + trial: "Trial", + checkpoint: "ray.tune.Checkpoint", + **info, + ): + """Called after a trial saved a checkpoint with Tune. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has errored. + checkpoint: Checkpoint object that has been saved + by the trial. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_experiment_end(self, trials: List["Trial"], **info): + """Called after experiment is over and all trials have concluded. + + Arguments: + trials: List of trials. + **info: Kwargs dict for forward compatibility. + """ + pass + + def get_state(self) -> Optional[Dict]: + """Get the state of the callback. + + This method should be implemented by subclasses to return a dictionary + representation of the object's current state. + + This is called automatically by Tune to periodically checkpoint callback state. + Upon :ref:`Tune experiment restoration `, + callback state will be restored via :meth:`~ray.tune.Callback.set_state`. + + .. testcode:: + + from typing import Dict, List, Optional + + from ray.tune import Callback + from ray.tune.experiment import Trial + + class MyCallback(Callback): + def __init__(self): + self._trial_ids = set() + + def on_trial_start( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + self._trial_ids.add(trial.trial_id) + + def get_state(self) -> Optional[Dict]: + return {"trial_ids": self._trial_ids.copy()} + + def set_state(self, state: Dict) -> Optional[Dict]: + self._trial_ids = state["trial_ids"] + + Returns: + dict: State of the callback. Should be `None` if the callback does not + have any state to save (this is the default). + """ + return None + + def set_state(self, state: Dict): + """Set the state of the callback. + + This method should be implemented by subclasses to restore the callback's + state based on the given dict state. + + This is used automatically by Tune to restore checkpoint callback state + on :ref:`Tune experiment restoration `. + + See :meth:`~ray.tune.Callback.get_state` for an example implementation. + + Args: + state: State of the callback. + """ + pass + + +@DeveloperAPI +class CallbackList(Callback): + """Call multiple callbacks at once.""" + + IS_CALLBACK_CONTAINER = True + CKPT_FILE_TMPL = "callback-states-{}.pkl" + + def __init__(self, callbacks: List[Callback]): + self._callbacks = callbacks + + def setup(self, **info): + for callback in self._callbacks: + try: + callback.setup(**info) + except TypeError as e: + if "argument" in str(e): + warnings.warn( + "Please update `setup` method in callback " + f"`{callback.__class__}` to match the method signature" + " in `ray.tune.callback.Callback`.", + FutureWarning, + ) + callback.setup() + else: + raise e + + def on_step_begin(self, **info): + for callback in self._callbacks: + callback.on_step_begin(**info) + + def on_step_end(self, **info): + for callback in self._callbacks: + callback.on_step_end(**info) + + def on_trial_start(self, **info): + for callback in self._callbacks: + callback.on_trial_start(**info) + + def on_trial_restore(self, **info): + for callback in self._callbacks: + callback.on_trial_restore(**info) + + def on_trial_save(self, **info): + for callback in self._callbacks: + callback.on_trial_save(**info) + + def on_trial_result(self, **info): + for callback in self._callbacks: + callback.on_trial_result(**info) + + def on_trial_complete(self, **info): + for callback in self._callbacks: + callback.on_trial_complete(**info) + + def on_trial_recover(self, **info): + for callback in self._callbacks: + callback.on_trial_recover(**info) + + def on_trial_error(self, **info): + for callback in self._callbacks: + callback.on_trial_error(**info) + + def on_checkpoint(self, **info): + for callback in self._callbacks: + callback.on_checkpoint(**info) + + def on_experiment_end(self, **info): + for callback in self._callbacks: + callback.on_experiment_end(**info) + + def get_state(self) -> Optional[Dict]: + """Gets the state of all callbacks contained within this list. + If there are no stateful callbacks, then None will be returned in order + to avoid saving an unnecessary callback checkpoint file.""" + state = {} + any_stateful_callbacks = False + for i, callback in enumerate(self._callbacks): + callback_state = callback.get_state() + if callback_state: + any_stateful_callbacks = True + state[i] = callback_state + if not any_stateful_callbacks: + return None + return state + + def set_state(self, state: Dict): + """Sets the state for all callbacks contained within this list. + Skips setting state for all stateless callbacks where `get_state` + returned None.""" + for i, callback in enumerate(self._callbacks): + callback_state = state.get(i, None) + if callback_state: + callback.set_state(callback_state) + + def save_to_dir(self, checkpoint_dir: str, session_str: str = "default"): + """Save the state of the callback list to the checkpoint_dir. + + Args: + checkpoint_dir: directory where the checkpoint is stored. + session_str: Unique identifier of the current run session (ex: timestamp). + """ + state_dict = self.get_state() + + if state_dict: + file_name = self.CKPT_FILE_TMPL.format(session_str) + tmp_file_name = f".tmp-{file_name}" + _atomic_save( + state=state_dict, + checkpoint_dir=checkpoint_dir, + file_name=file_name, + tmp_file_name=tmp_file_name, + ) + + def restore_from_dir(self, checkpoint_dir: str): + """Restore the state of the list of callbacks from the checkpoint_dir. + + You should check if it's possible to restore with `can_restore` + before calling this method. + + Args: + checkpoint_dir: directory where the checkpoint is stored. + + Raises: + RuntimeError: if unable to find checkpoint. + NotImplementedError: if the `set_state` method is not implemented. + """ + state_dict = _load_newest_checkpoint( + checkpoint_dir, self.CKPT_FILE_TMPL.format("*") + ) + if not state_dict: + raise RuntimeError( + "Unable to find checkpoint in {}.".format(checkpoint_dir) + ) + self.set_state(state_dict) + + def can_restore(self, checkpoint_dir: str) -> bool: + """Check if the checkpoint_dir contains the saved state for this callback list. + + Returns: + can_restore: True if the checkpoint_dir contains a file of the + format `CKPT_FILE_TMPL`. False otherwise. + """ + return any( + glob.iglob(Path(checkpoint_dir, self.CKPT_FILE_TMPL.format("*")).as_posix()) + ) + + def __len__(self) -> int: + return len(self._callbacks) + + def __getitem__(self, i: int) -> "Callback": + return self._callbacks[i] diff --git a/venv/lib/python3.10/site-packages/ray/tune/cli/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/tune/cli/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/cli/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8394c1e546d30f1484ffd35fdb28b22dabddc7d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/cli/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/cli/__pycache__/commands.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/cli/__pycache__/commands.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baaf81f1bbe88fa970ca3b844a19219754fc03b6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/cli/__pycache__/commands.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/cli/__pycache__/scripts.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/cli/__pycache__/scripts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25b9762a1e84715f6ab6f91deb76872d2f8e581e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/cli/__pycache__/scripts.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/cli/commands.py b/venv/lib/python3.10/site-packages/ray/tune/cli/commands.py new file mode 100644 index 0000000000000000000000000000000000000000..09070124124eaeb9a9e959dfc66e3c79d5fa7734 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/cli/commands.py @@ -0,0 +1,306 @@ +import logging +import operator +import os +import shutil +import subprocess +from datetime import datetime +from pathlib import Path +from typing import List, Optional + +import click +import pandas as pd +from pandas.api.types import is_numeric_dtype, is_string_dtype + +from ray._private.thirdparty.tabulate.tabulate import tabulate +from ray.air.constants import EXPR_RESULT_FILE +from ray.tune import TuneError +from ray.tune.analysis import ExperimentAnalysis +from ray.tune.result import ( + CONFIG_PREFIX, + DEFAULT_EXPERIMENT_INFO_KEYS, + DEFAULT_RESULT_KEYS, +) + +logger = logging.getLogger(__name__) + +EDITOR = os.getenv("EDITOR", "vim") + +TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S (%A)" + +DEFAULT_CLI_KEYS = DEFAULT_EXPERIMENT_INFO_KEYS + DEFAULT_RESULT_KEYS + +DEFAULT_PROJECT_INFO_KEYS = ( + "name", + "total_trials", + "last_updated", +) + +TERM_WIDTH, TERM_HEIGHT = shutil.get_terminal_size(fallback=(100, 100)) + +OPERATORS = { + "<": operator.lt, + "<=": operator.le, + "==": operator.eq, + "!=": operator.ne, + ">=": operator.ge, + ">": operator.gt, +} + + +def _check_tabulate(): + """Checks whether tabulate is installed.""" + if tabulate is None: + raise ImportError("Tabulate not installed. Please run `pip install tabulate`.") + + +def print_format_output(dataframe): + """Prints output of given dataframe to fit into terminal. + + Returns: + table: Final outputted dataframe. + dropped_cols: Columns dropped due to terminal size. + empty_cols: Empty columns (dropped on default). + """ + print_df = pd.DataFrame() + dropped_cols = [] + empty_cols = [] + # column display priority is based on the info_keys passed in + for i, col in enumerate(dataframe): + if dataframe[col].isnull().all(): + # Don't add col to print_df if is fully empty + empty_cols += [col] + continue + + print_df[col] = dataframe[col] + test_table = tabulate(print_df, headers="keys", tablefmt="psql") + if str(test_table).index("\n") > TERM_WIDTH: + # Drop all columns beyond terminal width + print_df.drop(col, axis=1, inplace=True) + dropped_cols += list(dataframe.columns)[i:] + break + + table = tabulate(print_df, headers="keys", tablefmt="psql", showindex="never") + + print(table) + if dropped_cols: + click.secho("Dropped columns: {}".format(dropped_cols), fg="yellow") + click.secho("Please increase your terminal size to view remaining columns.") + if empty_cols: + click.secho("Empty columns: {}".format(empty_cols), fg="yellow") + + return table, dropped_cols, empty_cols + + +def list_trials( + experiment_path: str, + sort: Optional[List[str]] = None, + output: Optional[str] = None, + filter_op: Optional[str] = None, + info_keys: Optional[List[str]] = None, + limit: int = None, + desc: bool = False, +): + """Lists trials in the directory subtree starting at the given path. + + Args: + experiment_path: Directory where trials are located. + Like Experiment.local_dir/Experiment.name/experiment*.json. + sort: Keys to sort by. + output: Name of file where output is saved. + filter_op: Filter operation in the format + " ". + info_keys: Keys that are displayed. + limit: Number of rows to display. + desc: Sort ascending vs. descending. + """ + _check_tabulate() + + try: + checkpoints_df = ExperimentAnalysis(experiment_path).dataframe() # last result + except TuneError as e: + raise click.ClickException("No trial data found!") from e + + config_prefix = CONFIG_PREFIX + "/" + + def key_filter(k): + return k in DEFAULT_CLI_KEYS or k.startswith(config_prefix) + + col_keys = [k for k in checkpoints_df.columns if key_filter(k)] + + if info_keys: + for k in info_keys: + if k not in checkpoints_df.columns: + raise click.ClickException( + "Provided key invalid: {}. " + "Available keys: {}.".format(k, checkpoints_df.columns) + ) + col_keys = [k for k in checkpoints_df.columns if k in info_keys] + + if not col_keys: + raise click.ClickException("No columns to output.") + + checkpoints_df = checkpoints_df[col_keys] + if "last_update_time" in checkpoints_df: + with pd.option_context("mode.use_inf_as_null", True): + datetime_series = checkpoints_df["last_update_time"].dropna() + + datetime_series = datetime_series.apply( + lambda t: datetime.fromtimestamp(t).strftime(TIMESTAMP_FORMAT) + ) + checkpoints_df["last_update_time"] = datetime_series + + if "logdir" in checkpoints_df: + # logdir often too long to view in table, so drop experiment_path + checkpoints_df["logdir"] = checkpoints_df["logdir"].str.replace( + experiment_path, "" + ) + + if filter_op: + col, op, val = filter_op.split(" ") + col_type = checkpoints_df[col].dtype + if is_numeric_dtype(col_type): + val = float(val) + elif is_string_dtype(col_type): + val = str(val) + # TODO(Andrew): add support for datetime and boolean + else: + raise click.ClickException( + "Unsupported dtype for {}: {}".format(val, col_type) + ) + op = OPERATORS[op] + filtered_index = op(checkpoints_df[col], val) + checkpoints_df = checkpoints_df[filtered_index] + + if sort: + for key in sort: + if key not in checkpoints_df: + raise click.ClickException( + "{} not in: {}".format(key, list(checkpoints_df)) + ) + ascending = not desc + checkpoints_df = checkpoints_df.sort_values(by=sort, ascending=ascending) + + if limit: + checkpoints_df = checkpoints_df[:limit] + + print_format_output(checkpoints_df) + + if output: + file_extension = os.path.splitext(output)[1].lower() + if file_extension in (".p", ".pkl", ".pickle"): + checkpoints_df.to_pickle(output) + elif file_extension == ".csv": + checkpoints_df.to_csv(output, index=False) + else: + raise click.ClickException("Unsupported filetype: {}".format(output)) + click.secho("Output saved at {}".format(output), fg="green") + + +def list_experiments( + project_path: str, + sort: Optional[List[str]] = None, + output: str = None, + filter_op: str = None, + info_keys: Optional[List[str]] = None, + limit: int = None, + desc: bool = False, +): + """Lists experiments in the directory subtree. + + Args: + project_path: Directory where experiments are located. + Corresponds to Experiment.local_dir. + sort: Keys to sort by. + output: Name of file where output is saved. + filter_op: Filter operation in the format + " ". + info_keys: Keys that are displayed. + limit: Number of rows to display. + desc: Sort ascending vs. descending. + """ + _check_tabulate() + base, experiment_folders, _ = next(os.walk(project_path)) + + experiment_data_collection = [] + + for experiment_dir in experiment_folders: + num_trials = sum( + EXPR_RESULT_FILE in files + for _, _, files in os.walk(os.path.join(base, experiment_dir)) + ) + + experiment_data = {"name": experiment_dir, "total_trials": num_trials} + experiment_data_collection.append(experiment_data) + + if not experiment_data_collection: + raise click.ClickException("No experiments found!") + + info_df = pd.DataFrame(experiment_data_collection) + if not info_keys: + info_keys = DEFAULT_PROJECT_INFO_KEYS + col_keys = [k for k in list(info_keys) if k in info_df] + if not col_keys: + raise click.ClickException( + "None of keys {} in experiment data!".format(info_keys) + ) + info_df = info_df[col_keys] + + if filter_op: + col, op, val = filter_op.split(" ") + col_type = info_df[col].dtype + if is_numeric_dtype(col_type): + val = float(val) + elif is_string_dtype(col_type): + val = str(val) + # TODO(Andrew): add support for datetime and boolean + else: + raise click.ClickException( + "Unsupported dtype for {}: {}".format(val, col_type) + ) + op = OPERATORS[op] + filtered_index = op(info_df[col], val) + info_df = info_df[filtered_index] + + if sort: + for key in sort: + if key not in info_df: + raise click.ClickException("{} not in: {}".format(key, list(info_df))) + ascending = not desc + info_df = info_df.sort_values(by=sort, ascending=ascending) + + if limit: + info_df = info_df[:limit] + + print_format_output(info_df) + + if output: + file_extension = os.path.splitext(output)[1].lower() + if file_extension in (".p", ".pkl", ".pickle"): + info_df.to_pickle(output) + elif file_extension == ".csv": + info_df.to_csv(output, index=False) + else: + raise click.ClickException("Unsupported filetype: {}".format(output)) + click.secho("Output saved at {}".format(output), fg="green") + + +def add_note(path: str, filename: str = "note.txt"): + """Opens a txt file at the given path where user can add and save notes. + + Args: + path: Directory where note will be saved. + filename: Name of note. Defaults to "note.txt" + """ + path = Path(path).expanduser() + assert path.is_dir(), "{} is not a valid directory.".format(path) + + filepath = path / filename + + try: + subprocess.call([EDITOR, filepath.as_posix()]) + except Exception as exc: + click.secho("Editing note failed: {}".format(str(exc)), fg="red") + if filepath.exists(): + print("Note updated at:", filepath.as_posix()) + else: + print("Note created at:", filepath.as_posix()) diff --git a/venv/lib/python3.10/site-packages/ray/tune/cli/scripts.py b/venv/lib/python3.10/site-packages/ray/tune/cli/scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..5401d091c3ba622e78532985e60a18307a2484d9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/cli/scripts.py @@ -0,0 +1,101 @@ +import click + +import ray.tune.cli.commands as commands + + +@click.group() +def cli(): + pass + + +@cli.command() +@click.argument("experiment_path", required=True, type=str) +@click.option("--sort", default=None, type=str, help="Select which column to sort on.") +@click.option( + "--output", + "-o", + default=None, + type=str, + help="Select file to output information to.", +) +@click.option( + "--filter", + "filter_op", + default=None, + type=str, + help="Select filter in the format ' '.", +) +@click.option( + "--columns", default=None, type=str, help="Select columns to be displayed." +) +@click.option( + "--limit", default=None, type=int, help="Select number of rows to display." +) +@click.option("--desc", default=False, type=bool, help="Sort ascending vs. descending.") +def list_trials(experiment_path, sort, output, filter_op, columns, limit, desc): + """Lists trials in the directory subtree starting at the given path.""" + if sort: + sort = sort.split(",") + if columns: + columns = columns.split(",") + commands.list_trials(experiment_path, sort, output, filter_op, columns, limit, desc) + + +@cli.command() +@click.argument("project_path", required=True, type=str) +@click.option("--sort", default=None, type=str, help="Select which column to sort on.") +@click.option( + "--output", + "-o", + default=None, + type=str, + help="Select file to output information to.", +) +@click.option( + "--filter", + "filter_op", + default=None, + type=str, + help="Select filter in the format ' '.", +) +@click.option( + "--columns", default=None, type=str, help="Select columns to be displayed." +) +@click.option( + "--limit", default=None, type=int, help="Select number of rows to display." +) +@click.option("--desc", default=False, type=bool, help="Sort ascending vs. descending.") +def list_experiments(project_path, sort, output, filter_op, columns, limit, desc): + """Lists experiments in the directory subtree.""" + if sort: + sort = sort.split(",") + if columns: + columns = columns.split(",") + commands.list_experiments( + project_path, sort, output, filter_op, columns, limit, desc + ) + + +@cli.command() +@click.argument("path", required=True, type=str) +@click.option( + "--filename", default="note.txt", type=str, help="Specify filename for note." +) +def add_note(path, filename): + """Adds user notes as a text file at the given path.""" + commands.add_note(path, filename) + + +cli.add_command(list_trials, name="ls") +cli.add_command(list_trials, name="list-trials") +cli.add_command(list_experiments, name="lsx") +cli.add_command(list_experiments, name="list-experiments") +cli.add_command(add_note, name="add-note") + + +def main(): + return cli() + + +if __name__ == "__main__": + main() diff --git a/venv/lib/python3.10/site-packages/ray/tune/constants.py b/venv/lib/python3.10/site-packages/ray/tune/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..a71580b342a2157b2946a8c1458a65b7833bb7c4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/constants.py @@ -0,0 +1,36 @@ +# ================================================== +# Environment Variables +# ================================================== + +# Environment variable for Tune execution callbacks +RAY_TUNE_CALLBACKS_ENV_VAR = "RAY_TUNE_CALLBACKS" + +# NOTE: When adding a new environment variable, please track it in this list. +TUNE_ENV_VARS = { + "RAY_AIR_LOCAL_CACHE_DIR", + "TUNE_DISABLE_AUTO_CALLBACK_LOGGERS", + "TUNE_DISABLE_AUTO_INIT", + "TUNE_DISABLE_DATED_SUBDIR", + "TUNE_DISABLE_STRICT_METRIC_CHECKING", + "TUNE_DISABLE_SIGINT_HANDLER", + "TUNE_FORCE_TRIAL_CLEANUP_S", + "TUNE_FUNCTION_THREAD_TIMEOUT_S", + "TUNE_GLOBAL_CHECKPOINT_S", + "TUNE_MAX_LEN_IDENTIFIER", + "TUNE_MAX_PENDING_TRIALS_PG", + "TUNE_PLACEMENT_GROUP_PREFIX", + "TUNE_PLACEMENT_GROUP_RECON_INTERVAL", + "TUNE_PRINT_ALL_TRIAL_ERRORS", + "TUNE_RESULT_DIR", + "TUNE_RESULT_BUFFER_LENGTH", + "TUNE_RESULT_DELIM", + "TUNE_RESULT_BUFFER_MAX_TIME_S", + "TUNE_RESULT_BUFFER_MIN_TIME_S", + "TUNE_WARN_THRESHOLD_S", + "TUNE_WARN_INSUFFICENT_RESOURCE_THRESHOLD_S", + "TUNE_WARN_INSUFFICENT_RESOURCE_THRESHOLD_S_AUTOSCALER", + "TUNE_WARN_EXCESSIVE_EXPERIMENT_CHECKPOINT_SYNC_THRESHOLD_S", + "TUNE_STATE_REFRESH_PERIOD", + "TUNE_RESTORE_RETRY_NUM", + RAY_TUNE_CALLBACKS_ENV_VAR, +} diff --git a/venv/lib/python3.10/site-packages/ray/tune/context.py b/venv/lib/python3.10/site-packages/ray/tune/context.py new file mode 100644 index 0000000000000000000000000000000000000000..ef1046885b8e33451a3e31b8a7afb4fa694574d8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/context.py @@ -0,0 +1,116 @@ +import threading +from typing import Any, Dict, Optional + +from ray.train._internal import session +from ray.train.constants import ( + V2_MIGRATION_GUIDE_MESSAGE, + _v2_migration_warnings_enabled, +) +from ray.train.context import TrainContext as TrainV1Context +from ray.train.utils import _copy_doc +from ray.tune.execution.placement_groups import PlacementGroupFactory +from ray.util.annotations import Deprecated, PublicAPI + +# The context singleton on this process. +_tune_context: Optional["TuneContext"] = None +_tune_context_lock = threading.Lock() + + +_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE = ( + "`{}` is deprecated for Ray Tune because there is no concept of worker ranks " + "for Ray Tune, so these methods only make sense to use in the context of " + f"a Ray Train worker. {V2_MIGRATION_GUIDE_MESSAGE}" +) + + +@PublicAPI(stability="beta") +class TuneContext(TrainV1Context): + """Context to access metadata within Ray Tune functions.""" + + # NOTE: These methods are deprecated on the TrainContext, but are still + # available on the TuneContext. Re-defining them here to avoid the + # deprecation warnings. + + @_copy_doc(session.get_trial_name) + def get_trial_name(self) -> str: + return session.get_trial_name() + + @_copy_doc(session.get_trial_id) + def get_trial_id(self) -> str: + return session.get_trial_id() + + @_copy_doc(session.get_trial_resources) + def get_trial_resources(self) -> PlacementGroupFactory: + return session.get_trial_resources() + + @_copy_doc(session.get_trial_dir) + def get_trial_dir(self) -> str: + return session.get_trial_dir() + + # Deprecated APIs + + @Deprecated + def get_metadata(self) -> Dict[str, Any]: + raise DeprecationWarning( + "`get_metadata` is deprecated for Ray Tune, as it has never been usable." + ) + + @Deprecated( + message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_world_size"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(TrainV1Context.get_world_size) + def get_world_size(self) -> int: + return session.get_world_size() + + @Deprecated( + message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_world_rank"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(TrainV1Context.get_world_rank) + def get_world_rank(self) -> int: + return session.get_world_rank() + + @Deprecated( + message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_local_rank"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(TrainV1Context.get_local_rank) + def get_local_rank(self) -> int: + return session.get_local_rank() + + @Deprecated( + message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format( + "get_local_world_size" + ), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(TrainV1Context.get_local_world_size) + def get_local_world_size(self) -> int: + return session.get_local_world_size() + + @Deprecated( + message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_node_rank"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(TrainV1Context.get_node_rank) + def get_node_rank(self) -> int: + return session.get_node_rank() + + +@PublicAPI(stability="beta") +def get_context() -> TuneContext: + """Get or create a singleton Ray Tune context. + + The context is only available in a tune function passed to the `ray.tune.Tuner`. + + See the :class:`~ray.tune.TuneContext` API reference to see available methods. + """ + global _tune_context + + with _tune_context_lock: + if _tune_context is None: + # TODO(justinvyu): This default should be a dummy context + # that is only used for testing / running outside of Tune. + _tune_context = TuneContext() + return _tune_context diff --git a/venv/lib/python3.10/site-packages/ray/tune/error.py b/venv/lib/python3.10/site-packages/ray/tune/error.py new file mode 100644 index 0000000000000000000000000000000000000000..9f2b427a2788e09a4c5bf5bc2d208dce31ae2dfd --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/error.py @@ -0,0 +1,48 @@ +from ray.util.annotations import PublicAPI + + +@PublicAPI +class TuneError(Exception): + """General error class raised by ray.tune.""" + + pass + + +class _AbortTrialExecution(TuneError): + """Error that indicates a trial should not be retried.""" + + pass + + +class _SubCategoryTuneError(TuneError): + """The more specific TuneError that happens for a certain Tune + subroutine. For example starting/stopping a trial. + """ + + def __init__(self, traceback_str: str): + self.traceback_str = traceback_str + + def __str__(self): + return self.traceback_str + + +class _TuneStopTrialError(_SubCategoryTuneError): + """Error that happens when stopping a tune trial.""" + + pass + + +class _TuneStartTrialError(_SubCategoryTuneError): + """Error that happens when starting a tune trial.""" + + pass + + +class _TuneNoNextExecutorEventError(_SubCategoryTuneError): + """Error that happens when waiting to get the next event to + handle from RayTrialExecutor. + + Note: RayTaskError will be raised by itself and will not be using + this category. This category is for everything else.""" + + pass diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cae1ce7ccc3413c60afb0161785012b846f68e1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/async_hyperband_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/async_hyperband_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee4667e1b4f1e75ebae827de487ea79f224c2057 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/async_hyperband_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/ax_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/ax_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86cb6eee0f05ce70e999b5086acfa385b1b8119b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/ax_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/bayesopt_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/bayesopt_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84d660310ad1e93d0bc6ee70e90151de6601b21d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/bayesopt_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/bohb_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/bohb_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b537edc02f5a348af5448e250bc44923bcad6b12 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/bohb_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/cifar10_pytorch.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/cifar10_pytorch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1121f1148a00c5cce1ba631cf6cace188dd4cc3c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/cifar10_pytorch.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/custom_func_checkpointing.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/custom_func_checkpointing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec024ecb77fc2ea614c56e40853000f59f0cb31f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/custom_func_checkpointing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/hyperband_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/hyperband_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24a8340e56d872861fea304c1dd2297670d29e59 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/hyperband_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/hyperband_function_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/hyperband_function_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..229d2261e1b7428d40c929c71c456b68c487ad79 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/hyperband_function_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/hyperopt_conditional_search_space_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/hyperopt_conditional_search_space_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7af7daeb0fdeef2c7ca6b2f44f693ce8b448e35e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/hyperopt_conditional_search_space_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/lightgbm_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/lightgbm_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4045d317462b7adcadee1885a8b7c10b3bd0f841 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/lightgbm_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/logging_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/logging_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..153369be39e22d5ba0c30c3ea7fd59711ba4d063 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/logging_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mlflow_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mlflow_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2ab61e99f309113cf1aeb20b5ce719cd09f227b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mlflow_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mlflow_ptl.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mlflow_ptl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73f9e63c21009485bcac19616ed604db2ffecd68 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mlflow_ptl.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mnist_ptl_mini.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mnist_ptl_mini.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1c53f5a86201096c4b57815a7aed33dafa810a3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mnist_ptl_mini.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mnist_pytorch.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mnist_pytorch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fcdfe832b4048b75d157c6b654ea89f4f712bfe Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mnist_pytorch.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mnist_pytorch_trainable.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mnist_pytorch_trainable.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..983fd5af8c1d0676d063dc6d0809b30c12172dcb Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/mnist_pytorch_trainable.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/nevergrad_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/nevergrad_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9bebde6ecb97d3123af6b13c4d5cc05c1fb8631 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/nevergrad_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/optuna_define_by_run_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/optuna_define_by_run_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3dda4d3d1f2363250f9007a6de6280cc41b7f034 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/optuna_define_by_run_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/optuna_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/optuna_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b973b39918906297317f21a726b4e7440d0661e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/optuna_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/optuna_multiobjective_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/optuna_multiobjective_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1903bf8d828a05147d04c330710a918dfc4bd961 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/optuna_multiobjective_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pb2_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pb2_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a743bc42717a37c47566fbd5964d2cb6e1f8e62 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pb2_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pb2_ppo_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pb2_ppo_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a4d6dd936eda232843383d185cb534d92133434 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pb2_ppo_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_convnet_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_convnet_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7a735bdc6db1e069e5440cdd4439a5398f3664d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_convnet_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_convnet_function_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_convnet_function_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9c41700bc62382676ecd9eebbf473a3bb4e5e01 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_convnet_function_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b76792f41e6ff161cf4fab5d2f8512ea5e564587 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_function.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_function.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41d2043c94127b3d51257e588be04c3b43cbf423 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_function.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_memnn_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_memnn_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d758ec8438d90ab17f0a55705b6e27030652d409 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_memnn_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_ppo_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_ppo_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..644b6e4694ba0521c17fed7aae497737cf27e536 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_ppo_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_tune_cifar10_with_keras.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_tune_cifar10_with_keras.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9aa6deb87849eaaf9ca8843556a9e26098699b6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/pbt_tune_cifar10_with_keras.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/tf_mnist_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/tf_mnist_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c76670a3202596611e07672e5bac097b34de946a Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/tf_mnist_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/tune_basic_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/tune_basic_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3abd7000a759b9b32f8127886636fa689f87834c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/tune_basic_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/tune_mnist_keras.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/tune_mnist_keras.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71a9661ad6470c843f449cb6a27ef30bff20cf7e Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/tune_mnist_keras.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..884a6f8510a8cf318016a90fa343cc1007278f19 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/xgboost_dynamic_resources_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/xgboost_dynamic_resources_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c75b6e553b0343b4842e62232e0f086adc02cf0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/xgboost_dynamic_resources_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/xgboost_example.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/xgboost_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2094f29fbf046807f6a7a2a4a2fc1765abb14536 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/__pycache__/xgboost_example.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/async_hyperband_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/async_hyperband_example.py new file mode 100644 index 0000000000000000000000000000000000000000..bd372e2062d8e2623f35c8a92aff78ef7c990204 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/async_hyperband_example.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python + +import argparse +import time +from typing import Any, Dict + +from ray import tune +from ray.tune.schedulers import AsyncHyperBandScheduler + + +def evaluation_fn(step, width, height) -> float: + # simulate model evaluation + time.sleep(0.1) + return (0.1 + width * step / 100) ** (-1) + height * 0.1 + + +def easy_objective(config: Dict[str, Any]) -> None: + # Config contains the hyperparameters to tune + width, height = config["width"], config["height"] + + for step in range(config["steps"]): + # Iterative training function - can be an arbitrary training procedure + intermediate_score = evaluation_fn(step, width, height) + # Feed the score back back to Tune. + tune.report({"iterations": step, "mean_loss": intermediate_score}) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="AsyncHyperBand optimization example") + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + # AsyncHyperBand enables aggressive early stopping of poorly performing trials + scheduler = AsyncHyperBandScheduler( + grace_period=5, # Minimum training iterations before stopping + max_t=100, # Maximum training iterations + ) + + tuner = tune.Tuner( + tune.with_resources(easy_objective, {"cpu": 1, "gpu": 0}), + run_config=tune.RunConfig( + name="asynchyperband_test", + stop={"training_iteration": 1 if args.smoke_test else 9999}, + verbose=1, + ), + tune_config=tune.TuneConfig( + metric="mean_loss", + mode="min", + scheduler=scheduler, + num_samples=20, # Number of trials to run + ), + param_space={ + "steps": 100, + "width": tune.uniform(10, 100), + "height": tune.uniform(0, 100), + }, + ) + + # Run the hyperparameter optimization + results = tuner.fit() + print(f"Best hyperparameters found: {results.get_best_result().config}") diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/ax_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/ax_example.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef83d935696303ea271ca12a04ada96ebd7acb9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/ax_example.py @@ -0,0 +1,97 @@ +"""This example demonstrates the usage of AxSearch with Ray Tune. + +It also checks that it is usable with a separate scheduler. + +Requires the Ax library to be installed (`pip install ax-platform`). +""" + +import time + +import numpy as np + +from ray import tune +from ray.tune.schedulers import AsyncHyperBandScheduler +from ray.tune.search.ax import AxSearch + + +def hartmann6(x): + alpha = np.array([1.0, 1.2, 3.0, 3.2]) + A = np.array( + [ + [10, 3, 17, 3.5, 1.7, 8], + [0.05, 10, 17, 0.1, 8, 14], + [3, 3.5, 1.7, 10, 17, 8], + [17, 8, 0.05, 10, 0.1, 14], + ] + ) + P = 10 ** (-4) * np.array( + [ + [1312, 1696, 5569, 124, 8283, 5886], + [2329, 4135, 8307, 3736, 1004, 9991], + [2348, 1451, 3522, 2883, 3047, 6650], + [4047, 8828, 8732, 5743, 1091, 381], + ] + ) + y = 0.0 + for j, alpha_j in enumerate(alpha): + t = 0 + for k in range(6): + t += A[j, k] * ((x[k] - P[j, k]) ** 2) + y -= alpha_j * np.exp(-t) + return y + + +def easy_objective(config): + for i in range(config["iterations"]): + x = np.array([config.get("x{}".format(i + 1)) for i in range(6)]) + tune.report( + { + "timesteps_total": i, + "hartmann6": hartmann6(x), + "l2norm": np.sqrt((x**2).sum()), + } + ) + time.sleep(0.02) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + algo = AxSearch( + parameter_constraints=["x1 + x2 <= 2.0"], # Optional. + outcome_constraints=["l2norm <= 1.25"], # Optional. + ) + # Limit to 4 concurrent trials + algo = tune.search.ConcurrencyLimiter(algo, max_concurrent=4) + scheduler = AsyncHyperBandScheduler() + tuner = tune.Tuner( + easy_objective, + run_config=tune.RunConfig( + name="ax", + stop={"timesteps_total": 100}, + ), + tune_config=tune.TuneConfig( + metric="hartmann6", # provided in the 'easy_objective' function + mode="min", + search_alg=algo, + scheduler=scheduler, + num_samples=10 if args.smoke_test else 50, + ), + param_space={ + "iterations": 100, + "x1": tune.uniform(0.0, 1.0), + "x2": tune.uniform(0.0, 1.0), + "x3": tune.uniform(0.0, 1.0), + "x4": tune.uniform(0.0, 1.0), + "x5": tune.uniform(0.0, 1.0), + "x6": tune.uniform(0.0, 1.0), + }, + ) + results = tuner.fit() + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/bayesopt_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/bayesopt_example.py new file mode 100644 index 0000000000000000000000000000000000000000..1260461ff5fa4f76dcbbfdcf05e72f52daaec52f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/bayesopt_example.py @@ -0,0 +1,61 @@ +"""This example demonstrates the usage of BayesOpt with Ray Tune. + +It also checks that it is usable with a separate scheduler. + +Requires the BayesOpt library to be installed (`pip install bayesian-optimization`). +""" +import time + +from ray import tune +from ray.tune.schedulers import AsyncHyperBandScheduler +from ray.tune.search import ConcurrencyLimiter +from ray.tune.search.bayesopt import BayesOptSearch + + +def evaluation_fn(step, width, height): + return (0.1 + width * step / 100) ** (-1) + height * 0.1 + + +def easy_objective(config): + # Hyperparameters + width, height = config["width"], config["height"] + + for step in range(config["steps"]): + # Iterative training function - can be any arbitrary training procedure + intermediate_score = evaluation_fn(step, width, height) + # Feed the score back back to Tune. + tune.report({"iterations": step, "mean_loss": intermediate_score}) + time.sleep(0.1) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + algo = BayesOptSearch(utility_kwargs={"kind": "ucb", "kappa": 2.5, "xi": 0.0}) + algo = ConcurrencyLimiter(algo, max_concurrent=4) + scheduler = AsyncHyperBandScheduler() + tuner = tune.Tuner( + easy_objective, + tune_config=tune.TuneConfig( + metric="mean_loss", + mode="min", + search_alg=algo, + scheduler=scheduler, + num_samples=10 if args.smoke_test else 1000, + ), + run_config=tune.RunConfig(name="my_exp"), + param_space={ + "steps": 100, + "width": tune.uniform(0, 20), + "height": tune.uniform(-100, 100), + }, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/bohb_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/bohb_example.py new file mode 100644 index 0000000000000000000000000000000000000000..13595c08f61be51f6de7a8bf88f4f7770c4acba2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/bohb_example.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python + +"""This example demonstrates the usage of BOHB with Ray Tune. + +Requires the HpBandSter and ConfigSpace libraries to be installed +(`pip install hpbandster ConfigSpace`). +""" + +import json +import os +import time + +import numpy as np + +import ray +from ray import tune +from ray.tune import Trainable +from ray.tune.schedulers.hb_bohb import HyperBandForBOHB +from ray.tune.search.bohb import TuneBOHB + + +class MyTrainableClass(Trainable): + """Example agent whose learning curve is a random sigmoid. + + The dummy hyperparameters "width" and "height" determine the slope and + maximum reward value reached. + """ + + def setup(self, config): + self.timestep = 0 + + def step(self): + self.timestep += 1 + v = np.tanh(float(self.timestep) / self.config.get("width", 1)) + v *= self.config.get("height", 1) + time.sleep(0.1) + # Here we use `episode_reward_mean`, but you can also report other + # objectives such as loss or accuracy. + return {"episode_reward_mean": v} + + def save_checkpoint(self, checkpoint_dir): + path = os.path.join(checkpoint_dir, "checkpoint") + with open(path, "w") as f: + f.write(json.dumps({"timestep": self.timestep})) + + def load_checkpoint(self, checkpoint_dir): + path = os.path.join(checkpoint_dir, "checkpoint") + with open(path, "r") as f: + self.timestep = json.loads(f.read())["timestep"] + + +if __name__ == "__main__": + import sys + + if sys.version_info >= (3, 12): + # TuneBOHB is not compatible with Python 3.12 + sys.exit(0) + + ray.init(num_cpus=8) + + config = { + "iterations": 100, + "width": tune.uniform(0, 20), + "height": tune.uniform(-100, 100), + "activation": tune.choice(["relu", "tanh"]), + } + + # Optional: Pass the parameter space yourself + # import ConfigSpace as CS + # config_space = CS.ConfigurationSpace() + # config_space.add_hyperparameter( + # CS.UniformFloatHyperparameter("width", lower=0, upper=20)) + # config_space.add_hyperparameter( + # CS.UniformFloatHyperparameter("height", lower=-100, upper=100)) + # config_space.add_hyperparameter( + # CS.CategoricalHyperparameter( + # "activation", choices=["relu", "tanh"])) + + max_iterations = 10 + bohb_hyperband = HyperBandForBOHB( + time_attr="training_iteration", + max_t=max_iterations, + reduction_factor=2, + stop_last_trials=False, + ) + + bohb_search = TuneBOHB( + # space=config_space, # If you want to set the space manually + ) + bohb_search = tune.search.ConcurrencyLimiter(bohb_search, max_concurrent=4) + + tuner = tune.Tuner( + MyTrainableClass, + run_config=tune.RunConfig( + name="bohb_test", stop={"training_iteration": max_iterations} + ), + tune_config=tune.TuneConfig( + metric="episode_reward_mean", + mode="max", + scheduler=bohb_hyperband, + search_alg=bohb_search, + num_samples=32, + ), + param_space=config, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/cifar10_pytorch.py b/venv/lib/python3.10/site-packages/ray/tune/examples/cifar10_pytorch.py new file mode 100644 index 0000000000000000000000000000000000000000..e82803949b48a463abd4341df68318ac26fe59ff --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/cifar10_pytorch.py @@ -0,0 +1,285 @@ +# ruff: noqa +# fmt: off + +# __import_begin__ +import os +import tempfile +from typing import Dict + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.optim as optim +import torchvision +import torchvision.transforms as transforms +from filelock import FileLock +from torch.utils.data import random_split + +import ray +from ray import tune +from ray.tune import Checkpoint +from ray.tune.schedulers import ASHAScheduler + +# __import_end__ + + +# __load_data_begin__ +DATA_DIR = tempfile.mkdtemp() + +def load_data(data_dir): + transform = transforms.Compose([ + transforms.ToTensor(), + transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), + ]) + + # We add FileLock here because multiple workers will want to + # download data, and this may cause overwrites since + # DataLoader is not threadsafe. + with FileLock(os.path.expanduser("~/.data.lock")): + trainset = torchvision.datasets.CIFAR10( + root=data_dir, train=True, download=True, transform=transform) + + testset = torchvision.datasets.CIFAR10( + root=data_dir, train=False, download=True, transform=transform) + + return trainset, testset +# __load_data_end__ + +def load_test_data(): + # Loads a fake dataset for testing so it doesn't rely on external download. + trainset = torchvision.datasets.FakeData( + 128, (3, 32, 32), num_classes=10, transform=transforms.ToTensor() + ) + testset = torchvision.datasets.FakeData( + 16, (3, 32, 32), num_classes=10, transform=transforms.ToTensor() + ) + return trainset, testset + + +# __net_begin__ +class Net(nn.Module): + def __init__(self, l1=120, l2=84): + super(Net, self).__init__() + self.conv1 = nn.Conv2d(3, 6, 5) + self.pool = nn.MaxPool2d(2, 2) + self.conv2 = nn.Conv2d(6, 16, 5) + self.fc1 = nn.Linear(16 * 5 * 5, l1) + self.fc2 = nn.Linear(l1, l2) + self.fc3 = nn.Linear(l2, 10) + + def forward(self, x): + x = self.pool(F.relu(self.conv1(x))) + x = self.pool(F.relu(self.conv2(x))) + x = x.view(-1, 16 * 5 * 5) + x = F.relu(self.fc1(x)) + x = F.relu(self.fc2(x)) + x = self.fc3(x) + return x +# __net_end__ + + +# __train_begin__ +def train_cifar(config): + net = Net(config["l1"], config["l2"]) + + device = "cpu" + if torch.cuda.is_available(): + device = "cuda:0" + if torch.cuda.device_count() > 1: + net = nn.DataParallel(net) + net.to(device) + + criterion = nn.CrossEntropyLoss() + optimizer = optim.SGD(net.parameters(), lr=config["lr"], momentum=0.9) + + # Load existing checkpoint through `get_checkpoint()` API. + if tune.get_checkpoint(): + loaded_checkpoint = tune.get_checkpoint() + with loaded_checkpoint.as_directory() as loaded_checkpoint_dir: + model_state, optimizer_state = torch.load( + os.path.join(loaded_checkpoint_dir, "checkpoint.pt") + ) + net.load_state_dict(model_state) + optimizer.load_state_dict(optimizer_state) + + if config["smoke_test"]: + trainset, testset = load_test_data() + else: + trainset, testset = load_data(DATA_DIR) + + test_abs = int(len(trainset) * 0.8) + train_subset, val_subset = random_split( + trainset, [test_abs, len(trainset) - test_abs]) + + trainloader = torch.utils.data.DataLoader( + train_subset, + batch_size=int(config["batch_size"]), + shuffle=True, + num_workers=0 if config["smoke_test"] else 8, + ) + valloader = torch.utils.data.DataLoader( + val_subset, + batch_size=int(config["batch_size"]), + shuffle=True, + num_workers=0 if config["smoke_test"] else 8, + ) + + for epoch in range(10): # loop over the dataset multiple times + running_loss = 0.0 + epoch_steps = 0 + for i, data in enumerate(trainloader): + # get the inputs; data is a list of [inputs, labels] + inputs, labels = data + inputs, labels = inputs.to(device), labels.to(device) + + # zero the parameter gradients + optimizer.zero_grad() + + # forward + backward + optimize + outputs = net(inputs) + loss = criterion(outputs, labels) + loss.backward() + optimizer.step() + + # print statistics + running_loss += loss.item() + epoch_steps += 1 + if i % 2000 == 1999: # print every 2000 mini-batches + print("[%d, %5d] loss: %.3f" % (epoch + 1, i + 1, + running_loss / epoch_steps)) + running_loss = 0.0 + + # Validation loss + val_loss = 0.0 + val_steps = 0 + total = 0 + correct = 0 + for i, data in enumerate(valloader, 0): + with torch.no_grad(): + inputs, labels = data + inputs, labels = inputs.to(device), labels.to(device) + + outputs = net(inputs) + _, predicted = torch.max(outputs.data, 1) + total += labels.size(0) + correct += (predicted == labels).sum().item() + + loss = criterion(outputs, labels) + val_loss += loss.cpu().numpy() + val_steps += 1 + + # Here we save a checkpoint. It is automatically registered with + # Ray Tune and will potentially be accessed through in ``get_checkpoint()`` + # in future iterations. + # Note to save a file like checkpoint, you still need to put it under a directory + # to construct a checkpoint. + with tempfile.TemporaryDirectory() as temp_checkpoint_dir: + path = os.path.join(temp_checkpoint_dir, "checkpoint.pt") + torch.save( + (net.state_dict(), optimizer.state_dict()), path + ) + checkpoint = Checkpoint.from_directory(temp_checkpoint_dir) + tune.report( + {"loss": (val_loss / val_steps), "accuracy": correct / total}, + checkpoint=checkpoint, + ) + print("Finished Training") +# __train_end__ + + +# __test_acc_begin__ +def test_best_model(config: Dict, checkpoint: "Checkpoint", smoke_test=False): + best_trained_model = Net(config["l1"], config["l2"]) + device = "cuda:0" if torch.cuda.is_available() else "cpu" + best_trained_model.to(device) + + with checkpoint.as_directory() as checkpoint_dir: + checkpoint_path = os.path.join(checkpoint_dir, "checkpoint.pt") + model_state, optimizer_state = torch.load(checkpoint_path) + best_trained_model.load_state_dict(model_state) + + if smoke_test: + _, testset = load_test_data() + else: + _, testset = load_data(DATA_DIR) + + testloader = torch.utils.data.DataLoader( + testset, batch_size=4, shuffle=False, num_workers=2) + + correct = 0 + total = 0 + with torch.no_grad(): + for data in testloader: + images, labels = data + images, labels = images.to(device), labels.to(device) + outputs = best_trained_model(images) + _, predicted = torch.max(outputs.data, 1) + total += labels.size(0) + correct += (predicted == labels).sum().item() + + + print("Best trial test set accuracy: {}".format(correct / total)) + +# __test_acc_end__ + +# __main_begin__ +def main(num_samples=10, max_num_epochs=10, gpus_per_trial=2, smoke_test=False): + config = { + "l1": tune.sample_from(lambda _: 2 ** np.random.randint(2, 9)), + "l2": tune.sample_from(lambda _: 2 ** np.random.randint(2, 9)), + "lr": tune.loguniform(1e-4, 1e-1), + "batch_size": tune.choice([2, 4, 8, 16]), + "smoke_test": smoke_test, + } + scheduler = ASHAScheduler( + max_t=max_num_epochs, + grace_period=1, + reduction_factor=2) + + tuner = tune.Tuner( + tune.with_resources( + tune.with_parameters(train_cifar), + resources={"cpu": 2, "gpu": gpus_per_trial}, + ), + tune_config=tune.TuneConfig( + metric="loss", + mode="min", + num_samples=num_samples, + scheduler=scheduler + ), + param_space=config, + ) + results = tuner.fit() + best_result = results.get_best_result("loss", "min") + print("Best trial config: {}".format(best_result.config)) + print("Best trial final validation loss: {}".format( + best_result.metrics["loss"])) + print("Best trial final validation accuracy: {}".format( + best_result.metrics["accuracy"])) + + test_best_model(best_result.config, best_result.checkpoint, smoke_test=smoke_test) + + +# __main_end__ + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing") + parser.add_argument( + "--ray-address", + help="Address of Ray cluster for seamless distributed execution.", + required=False) + args, _ = parser.parse_known_args() + + if args.smoke_test: + ray.init(num_cpus=2) + main(num_samples=1, max_num_epochs=1, gpus_per_trial=0, smoke_test=True) + else: + ray.init(args.ray_address) + # Change this to activate training on GPUs + main(num_samples=10, max_num_epochs=10, gpus_per_trial=0) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/custom_func_checkpointing.py b/venv/lib/python3.10/site-packages/ray/tune/examples/custom_func_checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..0078a9463705b58e6868bf3e679e47765112be7d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/custom_func_checkpointing.py @@ -0,0 +1,70 @@ +# If want to use checkpointing with a custom training function (not a Ray +# integration like PyTorch or Tensorflow), your function can read/write +# checkpoint through the ``ray.tune.report(metrics, checkpoint=...)`` API. +import argparse +import json +import os +import tempfile +import time + +from ray import tune +from ray.tune import Checkpoint + + +def evaluation_fn(step, width, height): + time.sleep(0.1) + return (0.1 + width * step / 100) ** (-1) + height * 0.1 + + +def train_func(config): + step = 0 + width, height = config["width"], config["height"] + + checkpoint = tune.get_checkpoint() + if checkpoint: + with checkpoint.as_directory() as checkpoint_dir: + with open(os.path.join(checkpoint_dir, "checkpoint.json")) as f: + state = json.load(f) + step = state["step"] + 1 + + for current_step in range(step, 100): + intermediate_score = evaluation_fn(current_step, width, height) + + with tempfile.TemporaryDirectory() as temp_checkpoint_dir: + with open(os.path.join(temp_checkpoint_dir, "checkpoint.json"), "w") as f: + json.dump({"step": current_step}, f) + tune.report( + {"iterations": current_step, "mean_loss": intermediate_score}, + checkpoint=Checkpoint.from_directory(temp_checkpoint_dir), + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + tuner = tune.Tuner( + train_func, + run_config=tune.RunConfig( + name="hyperband_test", + stop={"training_iteration": 1 if args.smoke_test else 10}, + ), + tune_config=tune.TuneConfig( + metric="mean_loss", + mode="min", + num_samples=5, + ), + param_space={ + "steps": 10, + "width": tune.randint(10, 100), + "height": tune.loguniform(10, 100), + }, + ) + results = tuner.fit() + best_result = results.get_best_result() + print("Best hyperparameters: ", best_result.config) + best_checkpoint = best_result.checkpoint + print("Best checkpoint: ", best_checkpoint) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/hyperband_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/hyperband_example.py new file mode 100644 index 0000000000000000000000000000000000000000..86e2ede8d76343b7a3d875a1e077d9de61bd3da4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/hyperband_example.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python + +import argparse + +import ray +from ray import tune +from ray.tune.schedulers import HyperBandScheduler +from ray.tune.utils.mock_trainable import MyTrainableClass + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + ray.init(num_cpus=4 if args.smoke_test else None) + + # Hyperband early stopping, configured with `episode_reward_mean` as the + # objective and `training_iteration` as the time unit, + # which is automatically filled by Tune. + hyperband = HyperBandScheduler(time_attr="training_iteration", max_t=200) + + tuner = tune.Tuner( + MyTrainableClass, + run_config=tune.RunConfig( + name="hyperband_test", + stop={"training_iteration": 1 if args.smoke_test else 200}, + verbose=1, + failure_config=tune.FailureConfig( + fail_fast=True, + ), + ), + tune_config=tune.TuneConfig( + num_samples=20 if args.smoke_test else 200, + metric="episode_reward_mean", + mode="max", + scheduler=hyperband, + ), + param_space={"width": tune.randint(10, 90), "height": tune.randint(0, 100)}, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/hyperband_function_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/hyperband_function_example.py new file mode 100644 index 0000000000000000000000000000000000000000..44c158bb8ccd81480154d3addeb458bba14e3c54 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/hyperband_function_example.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python + +import argparse +import json +import os +import tempfile + +import numpy as np + +import ray +from ray import tune +from ray.tune import Checkpoint +from ray.tune.schedulers import HyperBandScheduler + + +def train_func(config): + step = 0 + checkpoint = tune.get_checkpoint() + if checkpoint: + with checkpoint.as_directory() as checkpoint_dir: + with open(os.path.join(checkpoint_dir, "checkpoint.json")) as f: + step = json.load(f)["timestep"] + 1 + + for timestep in range(step, 100): + v = np.tanh(float(timestep) / config.get("width", 1)) + v *= config.get("height", 1) + + # Checkpoint the state of the training every 3 steps + # Note that this is only required for certain schedulers + with tempfile.TemporaryDirectory() as temp_checkpoint_dir: + checkpoint = None + if timestep % 3 == 0: + with open( + os.path.join(temp_checkpoint_dir, "checkpoint.json"), "w" + ) as f: + json.dump({"timestep": timestep}, f) + checkpoint = Checkpoint.from_directory(temp_checkpoint_dir) + + # Here we use `episode_reward_mean`, but you can also report other + # objectives such as loss or accuracy. + tune.report({"episode_reward_mean": v}, checkpoint=checkpoint) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + ray.init(num_cpus=4 if args.smoke_test else None) + + # Hyperband early stopping, configured with `episode_reward_mean` as the + # objective and `training_iteration` as the time unit, + # which is automatically filled by Tune. + hyperband = HyperBandScheduler(max_t=200) + + tuner = tune.Tuner( + train_func, + run_config=tune.RunConfig( + name="hyperband_test", + stop={"training_iteration": 10 if args.smoke_test else 99999}, + failure_config=tune.FailureConfig( + fail_fast=True, + ), + ), + tune_config=tune.TuneConfig( + num_samples=20, + metric="episode_reward_mean", + mode="max", + scheduler=hyperband, + ), + param_space={"height": tune.uniform(0, 100)}, + ) + results = tuner.fit() + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/hyperopt_conditional_search_space_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/hyperopt_conditional_search_space_example.py new file mode 100644 index 0000000000000000000000000000000000000000..2541d83c9c1ba88bccba0bc94272b26adba12d67 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/hyperopt_conditional_search_space_example.py @@ -0,0 +1,107 @@ +"""This example demonstrates the usage of conditional search spaces with Tune. + +It also checks that it is usable with a separate scheduler. + +Requires the HyperOpt library to be installed (`pip install hyperopt`). + +For an example of using a Tune search space, see +:doc:`/tune/examples/hyperopt_example`. +""" + +import time + +from hyperopt import hp + +import ray +from ray import tune +from ray.tune.schedulers import AsyncHyperBandScheduler +from ray.tune.search import ConcurrencyLimiter +from ray.tune.search.hyperopt import HyperOptSearch + + +def f_unpack_dict(dct): + """Unpacks all sub-dictionaries in given dictionary recursively. + There should be no duplicated keys across all nested + subdictionaries, or some instances will be lost without warning + + Source: https://www.kaggle.com/fanvacoolt/tutorial-on-hyperopt + + Args: + dct: dictionary to unpack + + Returns: + dict: unpacked dictionary + """ + + res = {} + for k, v in dct.items(): + if isinstance(v, dict): + res = {**res, **f_unpack_dict(v)} + else: + res[k] = v + + return res + + +def evaluation_fn(step, width, height, mult=1): + return (0.1 + width * step / 100) ** (-1) + height * 0.1 * mult + + +def easy_objective(config_in): + # Hyperparameters + config = f_unpack_dict(config_in) + width, height, mult = config["width"], config["height"], config.get("mult", 1) + print(config) + + for step in range(config["steps"]): + # Iterative training function - can be any arbitrary training procedure + intermediate_score = evaluation_fn(step, width, height, mult) + # Feed the score back back to Tune. + tune.report({"iterations": step, "mean_loss": intermediate_score}) + time.sleep(0.1) + + +config_space = { + "activation": hp.choice( + "activation", + [ + {"activation": "relu", "mult": hp.uniform("mult", 1, 2)}, + {"activation": "tanh"}, + ], + ), + "width": hp.uniform("width", 0, 20), + "height": hp.uniform("heright", -100, 100), + "steps": 100, +} + + +def run_hyperopt_tune(config_dict=config_space, smoke_test=False): + algo = HyperOptSearch(space=config_dict, metric="mean_loss", mode="min") + algo = ConcurrencyLimiter(algo, max_concurrent=4) + scheduler = AsyncHyperBandScheduler() + tuner = tune.Tuner( + easy_objective, + tune_config=tune.TuneConfig( + metric="mean_loss", + mode="min", + search_alg=algo, + scheduler=scheduler, + num_samples=10 if smoke_test else 100, + ), + ) + results = tuner.fit() + print("Best hyperparameters found were: ", results.get_best_result().config) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + ray.init(configure_logging=False) + + run_hyperopt_tune(smoke_test=args.smoke_test) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/lightgbm_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/lightgbm_example.py new file mode 100644 index 0000000000000000000000000000000000000000..94bdb29aba25500dea7678287ea9b983b73b81ed --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/lightgbm_example.py @@ -0,0 +1,103 @@ +import lightgbm as lgb +import sklearn.datasets +import sklearn.metrics +from sklearn.model_selection import train_test_split + +from ray import tune +from ray.tune.integration.lightgbm import TuneReportCheckpointCallback +from ray.tune.schedulers import ASHAScheduler + + +def train_breast_cancer(config: dict): + # This is a simple training function to be passed into Tune + + # Load dataset + data, target = sklearn.datasets.load_breast_cancer(return_X_y=True) + + # Split into train and test set + train_x, test_x, train_y, test_y = train_test_split(data, target, test_size=0.25) + + # Build input Datasets for LightGBM + train_set = lgb.Dataset(train_x, label=train_y) + test_set = lgb.Dataset(test_x, label=test_y) + + # Train the classifier, using the Tune callback + lgb.train( + config, + train_set, + valid_sets=[test_set], + valid_names=["eval"], + callbacks=[ + TuneReportCheckpointCallback( + { + "binary_error": "eval-binary_error", + "binary_logloss": "eval-binary_logloss", + } + ) + ], + ) + + +def train_breast_cancer_cv(config: dict): + # This is a simple training function to be passed into Tune, using + # lightgbm's cross validation functionality + + # Load dataset + data, target = sklearn.datasets.load_breast_cancer(return_X_y=True) + + train_set = lgb.Dataset(data, label=target) + + # Run CV, using the Tune callback + lgb.cv( + config, + train_set, + stratified=True, + # Checkpointing is not supported for CV + # LightGBM aggregates metrics over folds automatically + # with the cv_agg key. Both mean and standard deviation + # are provided. + callbacks=[ + TuneReportCheckpointCallback( + { + "binary_error": "valid-binary_error-mean", + "binary_logloss": "valid-binary_logloss-mean", + "binary_error_stdv": "valid-binary_error-stdv", + "binary_logloss_stdv": "valid-binary_logloss-stdv", + }, + frequency=0, + ) + ], + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--use-cv", action="store_true", help="Use `lgb.cv` instead of `lgb.train`." + ) + args, _ = parser.parse_known_args() + + config = { + "objective": "binary", + "metric": ["binary_error", "binary_logloss"], + "verbose": -1, + "boosting_type": tune.grid_search(["gbdt", "dart"]), + "num_leaves": tune.randint(10, 1000), + "learning_rate": tune.loguniform(1e-8, 1e-1), + } + + tuner = tune.Tuner( + train_breast_cancer if not args.use_cv else train_breast_cancer_cv, + tune_config=tune.TuneConfig( + metric="binary_error", + mode="min", + num_samples=2, + scheduler=ASHAScheduler(), + ), + param_space=config, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/logging_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/logging_example.py new file mode 100644 index 0000000000000000000000000000000000000000..2f09365e7255eca77a540dd657d0119e9ff61a09 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/logging_example.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python + +import argparse +import time + +from ray import tune +from ray.tune.logger import LoggerCallback + + +class TestLoggerCallback(LoggerCallback): + def on_trial_result(self, iteration, trials, trial, result, **info): + print(f"TestLogger for trial {trial}: {result}") + + +def trial_str_creator(trial): + return "{}_{}_123".format(trial.trainable_name, trial.trial_id) + + +def evaluation_fn(step, width, height): + time.sleep(0.1) + return (0.1 + width * step / 100) ** (-1) + height * 0.1 + + +def easy_objective(config): + # Hyperparameters + width, height = config["width"], config["height"] + + for step in range(config["steps"]): + # Iterative training function - can be any arbitrary training procedure + intermediate_score = evaluation_fn(step, width, height) + # Feed the score back back to Tune. + tune.report({"iterations": step, "mean_loss": intermediate_score}) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + tuner = tune.Tuner( + easy_objective, + run_config=tune.RunConfig( + name="hyperband_test", + callbacks=[TestLoggerCallback()], + stop={"training_iteration": 1 if args.smoke_test else 100}, + ), + tune_config=tune.TuneConfig( + metric="mean_loss", + mode="min", + num_samples=5, + trial_name_creator=trial_str_creator, + trial_dirname_creator=trial_str_creator, + ), + param_space={ + "steps": 100, + "width": tune.randint(10, 100), + "height": tune.loguniform(10, 100), + }, + ) + results = tuner.fit() + + print("Best hyperparameters: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/mlflow_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/mlflow_example.py new file mode 100644 index 0000000000000000000000000000000000000000..2b5d1671b456c258a6dc266427f66805ef0f5c4d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/mlflow_example.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +"""Examples using MLfowLoggerCallback and setup_mlflow. +""" +import os +import tempfile +import time + +import mlflow + +from ray import tune +from ray.air.integrations.mlflow import MLflowLoggerCallback, setup_mlflow + + +def evaluation_fn(step, width, height): + return (0.1 + width * step / 100) ** (-1) + height * 0.1 + + +def train_function(config): + # Hyperparameters + width, height = config["width"], config["height"] + + for step in range(config.get("steps", 100)): + # Iterative training function - can be any arbitrary training procedure + intermediate_score = evaluation_fn(step, width, height) + # Feed the score back to Tune. + tune.report({"iterations": step, "mean_loss": intermediate_score}) + time.sleep(0.1) + + +def tune_with_callback(mlflow_tracking_uri, finish_fast=False): + + tuner = tune.Tuner( + train_function, + run_config=tune.RunConfig( + name="mlflow", + callbacks=[ + MLflowLoggerCallback( + tracking_uri=mlflow_tracking_uri, + experiment_name="example", + save_artifact=True, + ) + ], + ), + tune_config=tune.TuneConfig( + num_samples=5, + ), + param_space={ + "width": tune.randint(10, 100), + "height": tune.randint(0, 100), + "steps": 5 if finish_fast else 100, + }, + ) + tuner.fit() + + +def train_function_mlflow(config): + setup_mlflow(config) + + # Hyperparameters + width, height = config["width"], config["height"] + + for step in range(config.get("steps", 100)): + # Iterative training function - can be any arbitrary training procedure + intermediate_score = evaluation_fn(step, width, height) + # Log the metrics to mlflow + mlflow.log_metrics(dict(mean_loss=intermediate_score), step=step) + # Feed the score back to Tune. + tune.report({"iterations": step, "mean_loss": intermediate_score}) + time.sleep(0.1) + + +def tune_with_setup(mlflow_tracking_uri, finish_fast=False): + # Set the experiment, or create a new one if does not exist yet. + mlflow.set_tracking_uri(mlflow_tracking_uri) + mlflow.set_experiment(experiment_name="mixin_example") + tuner = tune.Tuner( + train_function_mlflow, + run_config=tune.RunConfig( + name="mlflow", + ), + tune_config=tune.TuneConfig( + num_samples=5, + ), + param_space={ + "width": tune.randint(10, 100), + "height": tune.randint(0, 100), + "steps": 5 if finish_fast else 100, + "mlflow": { + "experiment_name": "mixin_example", + "tracking_uri": mlflow.get_tracking_uri(), + }, + }, + ) + tuner.fit() + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + parser.add_argument( + "--tracking-uri", + type=str, + help="The tracking URI for the MLflow tracking server.", + ) + args, _ = parser.parse_known_args() + + if args.smoke_test: + mlflow_tracking_uri = os.path.join(tempfile.gettempdir(), "mlruns") + else: + mlflow_tracking_uri = args.tracking_uri + + tune_with_callback(mlflow_tracking_uri, finish_fast=args.smoke_test) + if not args.smoke_test: + df = mlflow.search_runs( + [mlflow.get_experiment_by_name("example").experiment_id] + ) + print(df) + + tune_with_setup(mlflow_tracking_uri, finish_fast=args.smoke_test) + if not args.smoke_test: + df = mlflow.search_runs( + [mlflow.get_experiment_by_name("mixin_example").experiment_id] + ) + print(df) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/mlflow_ptl.py b/venv/lib/python3.10/site-packages/ray/tune/examples/mlflow_ptl.py new file mode 100644 index 0000000000000000000000000000000000000000..1591d023f17f15c3bfbfc603bb34c5bf615934d5 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/mlflow_ptl.py @@ -0,0 +1,105 @@ +"""An example showing how to use Pytorch Lightning training, Ray Tune +HPO, and MLflow autologging all together.""" + +import os +import tempfile + +import mlflow +import pytorch_lightning as pl + +from ray import tune +from ray.air.integrations.mlflow import setup_mlflow +from ray.tune.examples.mnist_ptl_mini import LightningMNISTClassifier, MNISTDataModule +from ray.tune.integration.pytorch_lightning import TuneReportCallback + + +def train_mnist_tune(config, data_dir=None, num_epochs=10, num_gpus=0): + setup_mlflow( + config, + experiment_name=config.get("experiment_name", None), + tracking_uri=config.get("tracking_uri", None), + ) + + model = LightningMNISTClassifier(config, data_dir) + dm = MNISTDataModule( + data_dir=data_dir, num_workers=1, batch_size=config["batch_size"] + ) + metrics = {"loss": "ptl/val_loss", "acc": "ptl/val_accuracy"} + mlflow.pytorch.autolog() + trainer = pl.Trainer( + max_epochs=num_epochs, + gpus=num_gpus, + progress_bar_refresh_rate=0, + callbacks=[TuneReportCallback(metrics, on="validation_end")], + ) + trainer.fit(model, dm) + + +def tune_mnist( + num_samples=10, + num_epochs=10, + gpus_per_trial=0, + tracking_uri=None, + experiment_name="ptl_autologging_example", +): + data_dir = os.path.join(tempfile.gettempdir(), "mnist_data_") + # Download data + MNISTDataModule(data_dir=data_dir, batch_size=32).prepare_data() + + # Set the MLflow experiment, or create it if it does not exist. + mlflow.set_tracking_uri(tracking_uri) + mlflow.set_experiment(experiment_name) + + config = { + "layer_1": tune.choice([32, 64, 128]), + "layer_2": tune.choice([64, 128, 256]), + "lr": tune.loguniform(1e-4, 1e-1), + "batch_size": tune.choice([32, 64, 128]), + "experiment_name": experiment_name, + "tracking_uri": mlflow.get_tracking_uri(), + "data_dir": os.path.join(tempfile.gettempdir(), "mnist_data_"), + "num_epochs": num_epochs, + } + + trainable = tune.with_parameters( + train_mnist_tune, + data_dir=data_dir, + num_epochs=num_epochs, + num_gpus=gpus_per_trial, + ) + + tuner = tune.Tuner( + tune.with_resources(trainable, resources={"cpu": 1, "gpu": gpus_per_trial}), + tune_config=tune.TuneConfig( + metric="loss", + mode="min", + num_samples=num_samples, + ), + run_config=tune.RunConfig( + name="tune_mnist", + ), + param_space=config, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + if args.smoke_test: + tune_mnist( + num_samples=1, + num_epochs=1, + gpus_per_trial=0, + tracking_uri=os.path.join(tempfile.gettempdir(), "mlruns"), + ) + else: + tune_mnist(num_samples=10, num_epochs=10, gpus_per_trial=0) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/mnist_ptl_mini.py b/venv/lib/python3.10/site-packages/ray/tune/examples/mnist_ptl_mini.py new file mode 100644 index 0000000000000000000000000000000000000000..4937a40d5fcac3f5e63470202174428d25130e2f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/mnist_ptl_mini.py @@ -0,0 +1,166 @@ +import math +import os + +import pytorch_lightning as pl +import torch +from datasets import load_dataset +from filelock import FileLock +from torch.nn import functional as F +from torch.utils.data import DataLoader +from torchmetrics import Accuracy +from torchvision import transforms + +from ray import tune +from ray.tune.integration.pytorch_lightning import TuneReportCheckpointCallback + +PATH_DATASETS = os.environ.get("PATH_DATASETS", ".") + + +class MNISTDataModule(pl.LightningDataModule): + def __init__(self, batch_size: int, data_dir: str = PATH_DATASETS): + super().__init__() + self.data_dir = data_dir + self.transform = transforms.Compose( + [ + transforms.ToTensor(), + transforms.Normalize((0.1307,), (0.3081,)), + ] + ) + self.batch_size = batch_size + self.dims = (1, 28, 28) + self.num_classes = 10 + + def prepare_data(self): + # download + with FileLock(os.path.expanduser("~/.data.lock")): + load_dataset("ylecun/mnist", cache_dir=self.data_dir) + + def setup(self, stage=None): + dataset = load_dataset("ylecun/mnist", cache_dir=self.data_dir) + + def transform_fn(sample): + return (self.transform(sample["image"]), sample["label"]) + + self.mnist_train = [transform_fn(sample) for sample in dataset["train"]] + self.mnist_val = [transform_fn(sample) for sample in dataset["test"]] + + def train_dataloader(self): + return DataLoader(self.mnist_train, batch_size=self.batch_size) + + def val_dataloader(self): + return DataLoader(self.mnist_val, batch_size=self.batch_size) + + +class LightningMNISTClassifier(pl.LightningModule): + def __init__(self, config, data_dir=None): + super(LightningMNISTClassifier, self).__init__() + + self.data_dir = data_dir or os.getcwd() + self.lr = config["lr"] + layer_1, layer_2 = config["layer_1"], config["layer_2"] + self.batch_size = config["batch_size"] + + # mnist images are (1, 28, 28) (channels, width, height) + self.layer_1 = torch.nn.Linear(28 * 28, layer_1) + self.layer_2 = torch.nn.Linear(layer_1, layer_2) + self.layer_3 = torch.nn.Linear(layer_2, 10) + self.accuracy = Accuracy(task="multiclass", num_classes=10, top_k=1) + + def forward(self, x): + batch_size, channels, width, height = x.size() + x = x.view(batch_size, -1) + x = self.layer_1(x) + x = torch.relu(x) + x = self.layer_2(x) + x = torch.relu(x) + x = self.layer_3(x) + x = torch.log_softmax(x, dim=1) + return x + + def configure_optimizers(self): + return torch.optim.Adam(self.parameters(), lr=self.lr) + + def training_step(self, train_batch, batch_idx): + x, y = train_batch + logits = self.forward(x) + loss = F.nll_loss(logits, y) + acc = self.accuracy(logits, y) + self.log("ptl/train_loss", loss) + self.log("ptl/train_accuracy", acc) + return loss + + def validation_step(self, val_batch, batch_idx): + x, y = val_batch + logits = self.forward(x) + loss = F.nll_loss(logits, y) + acc = self.accuracy(logits, y) + return {"val_loss": loss, "val_accuracy": acc} + + def validation_epoch_end(self, outputs): + avg_loss = torch.stack([x["val_loss"] for x in outputs]).mean() + avg_acc = torch.stack([x["val_accuracy"] for x in outputs]).mean() + self.log("ptl/val_loss", avg_loss) + self.log("ptl/val_accuracy", avg_acc) + + +def train_mnist_tune(config, num_epochs=10, num_gpus=0): + data_dir = os.path.abspath("./data") + model = LightningMNISTClassifier(config, data_dir) + with FileLock(os.path.expanduser("~/.data.lock")): + dm = MNISTDataModule(data_dir=data_dir, batch_size=config["batch_size"]) + metrics = {"loss": "ptl/val_loss", "acc": "ptl/val_accuracy"} + trainer = pl.Trainer( + max_epochs=num_epochs, + # If fractional GPUs passed in, convert to int. + gpus=math.ceil(num_gpus), + enable_progress_bar=False, + callbacks=[ + TuneReportCheckpointCallback( + metrics, on="validation_end", save_checkpoints=False + ) + ], + ) + trainer.fit(model, dm) + + +def tune_mnist(num_samples=10, num_epochs=10, gpus_per_trial=0): + config = { + "layer_1": tune.choice([32, 64, 128]), + "layer_2": tune.choice([64, 128, 256]), + "lr": tune.loguniform(1e-4, 1e-1), + "batch_size": tune.choice([32, 64, 128]), + } + + trainable = tune.with_parameters( + train_mnist_tune, num_epochs=num_epochs, num_gpus=gpus_per_trial + ) + tuner = tune.Tuner( + tune.with_resources(trainable, resources={"cpu": 1, "gpu": gpus_per_trial}), + tune_config=tune.TuneConfig( + metric="loss", + mode="min", + num_samples=num_samples, + ), + run_config=tune.RunConfig( + name="tune_mnist", + ), + param_space=config, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + if args.smoke_test: + tune_mnist(num_samples=1, num_epochs=1, gpus_per_trial=0) + else: + tune_mnist(num_samples=10, num_epochs=10, gpus_per_trial=0) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/mnist_pytorch.py b/venv/lib/python3.10/site-packages/ray/tune/examples/mnist_pytorch.py new file mode 100644 index 0000000000000000000000000000000000000000..96a8f136b9d584d2f5a7f5b6d11e619a0096b503 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/mnist_pytorch.py @@ -0,0 +1,161 @@ +# Original Code here: +# https://github.com/pytorch/examples/blob/master/mnist/main.py + +import argparse +import os +import tempfile + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.optim as optim +from filelock import FileLock +from torchvision import datasets, transforms + +import ray +from ray import tune +from ray.tune import Checkpoint +from ray.tune.schedulers import AsyncHyperBandScheduler + +# Change these values if you want the training to run quicker or slower. +EPOCH_SIZE = 512 +TEST_SIZE = 256 + + +class ConvNet(nn.Module): + def __init__(self): + super(ConvNet, self).__init__() + self.conv1 = nn.Conv2d(1, 3, kernel_size=3) + self.fc = nn.Linear(192, 10) + + def forward(self, x): + x = F.relu(F.max_pool2d(self.conv1(x), 3)) + x = x.view(-1, 192) + x = self.fc(x) + return F.log_softmax(x, dim=1) + + +def train_func(model, optimizer, train_loader, device=None): + device = device or torch.device("cpu") + model.train() + for batch_idx, (data, target) in enumerate(train_loader): + if batch_idx * len(data) > EPOCH_SIZE: + return + data, target = data.to(device), target.to(device) + optimizer.zero_grad() + output = model(data) + loss = F.nll_loss(output, target) + loss.backward() + optimizer.step() + + +def test_func(model, data_loader, device=None): + device = device or torch.device("cpu") + model.eval() + correct = 0 + total = 0 + with torch.no_grad(): + for batch_idx, (data, target) in enumerate(data_loader): + if batch_idx * len(data) > TEST_SIZE: + break + data, target = data.to(device), target.to(device) + outputs = model(data) + _, predicted = torch.max(outputs.data, 1) + total += target.size(0) + correct += (predicted == target).sum().item() + + return correct / total + + +def get_data_loaders(batch_size=64): + mnist_transforms = transforms.Compose( + [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))] + ) + + # We add FileLock here because multiple workers will want to + # download data, and this may cause overwrites since + # DataLoader is not threadsafe. + with FileLock(os.path.expanduser("~/data.lock")): + train_loader = torch.utils.data.DataLoader( + datasets.MNIST( + "~/data", train=True, download=True, transform=mnist_transforms + ), + batch_size=batch_size, + shuffle=True, + ) + test_loader = torch.utils.data.DataLoader( + datasets.MNIST( + "~/data", train=False, download=True, transform=mnist_transforms + ), + batch_size=batch_size, + shuffle=True, + ) + return train_loader, test_loader + + +def train_mnist(config): + should_checkpoint = config.get("should_checkpoint", False) + use_cuda = torch.cuda.is_available() + device = torch.device("cuda" if use_cuda else "cpu") + train_loader, test_loader = get_data_loaders() + model = ConvNet().to(device) + + optimizer = optim.SGD( + model.parameters(), lr=config["lr"], momentum=config["momentum"] + ) + + while True: + train_func(model, optimizer, train_loader, device) + acc = test_func(model, test_loader, device) + metrics = {"mean_accuracy": acc} + + # Report metrics (and possibly a checkpoint) + if should_checkpoint: + with tempfile.TemporaryDirectory() as tempdir: + torch.save(model.state_dict(), os.path.join(tempdir, "model.pt")) + tune.report(metrics, checkpoint=Checkpoint.from_directory(tempdir)) + else: + tune.report(metrics) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="PyTorch MNIST Example") + parser.add_argument( + "--cuda", action="store_true", default=False, help="Enables GPU training" + ) + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + ray.init(num_cpus=2 if args.smoke_test else None) + + # for early stopping + sched = AsyncHyperBandScheduler() + + resources_per_trial = {"cpu": 2, "gpu": int(args.cuda)} # set this for GPUs + tuner = tune.Tuner( + tune.with_resources(train_mnist, resources=resources_per_trial), + tune_config=tune.TuneConfig( + metric="mean_accuracy", + mode="max", + scheduler=sched, + num_samples=1 if args.smoke_test else 50, + ), + run_config=tune.RunConfig( + name="exp", + stop={ + "mean_accuracy": 0.98, + "training_iteration": 5 if args.smoke_test else 100, + }, + ), + param_space={ + "lr": tune.loguniform(1e-4, 1e-2), + "momentum": tune.uniform(0.1, 0.9), + }, + ) + results = tuner.fit() + + print("Best config is:", results.get_best_result().config) + + assert not results.errors diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/mnist_pytorch_trainable.py b/venv/lib/python3.10/site-packages/ray/tune/examples/mnist_pytorch_trainable.py new file mode 100644 index 0000000000000000000000000000000000000000..ff58a4d99730d1cc3657453fe074171e9d9e4d42 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/mnist_pytorch_trainable.py @@ -0,0 +1,98 @@ +# Original Code here: +# https://github.com/pytorch/examples/blob/master/mnist/main.py +from __future__ import print_function + +import argparse +import os + +import torch +import torch.optim as optim + +import ray +from ray import tune +from ray.tune.examples.mnist_pytorch import ( + ConvNet, + get_data_loaders, + test_func, + train_func, +) +from ray.tune.schedulers import ASHAScheduler + +# Change these values if you want the training to run quicker or slower. +EPOCH_SIZE = 512 +TEST_SIZE = 256 + +# Training settings +parser = argparse.ArgumentParser(description="PyTorch MNIST Example") +parser.add_argument( + "--use-gpu", action="store_true", default=False, help="enables CUDA training" +) +parser.add_argument("--ray-address", type=str, help="The Redis address of the cluster.") +parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" +) + + +# Below comments are for documentation purposes only. +# fmt: off +# __trainable_example_begin__ +class TrainMNIST(tune.Trainable): + def setup(self, config): + use_cuda = config.get("use_gpu") and torch.cuda.is_available() + self.device = torch.device("cuda" if use_cuda else "cpu") + self.train_loader, self.test_loader = get_data_loaders() + self.model = ConvNet().to(self.device) + self.optimizer = optim.SGD( + self.model.parameters(), + lr=config.get("lr", 0.01), + momentum=config.get("momentum", 0.9)) + + def step(self): + train_func( + self.model, self.optimizer, self.train_loader, device=self.device) + acc = test_func(self.model, self.test_loader, self.device) + return {"mean_accuracy": acc} + + def save_checkpoint(self, checkpoint_dir): + checkpoint_path = os.path.join(checkpoint_dir, "model.pth") + torch.save(self.model.state_dict(), checkpoint_path) + + def load_checkpoint(self, checkpoint_dir): + checkpoint_path = os.path.join(checkpoint_dir, "model.pth") + self.model.load_state_dict(torch.load(checkpoint_path)) + + +# __trainable_example_end__ +# fmt: on + +if __name__ == "__main__": + args = parser.parse_args() + ray.init(address=args.ray_address, num_cpus=6 if args.smoke_test else None) + sched = ASHAScheduler() + + tuner = tune.Tuner( + tune.with_resources(TrainMNIST, resources={"cpu": 3, "gpu": int(args.use_gpu)}), + run_config=tune.RunConfig( + stop={ + "mean_accuracy": 0.95, + "training_iteration": 3 if args.smoke_test else 20, + }, + checkpoint_config=tune.CheckpointConfig( + checkpoint_at_end=True, checkpoint_frequency=3 + ), + ), + tune_config=tune.TuneConfig( + metric="mean_accuracy", + mode="max", + scheduler=sched, + num_samples=1 if args.smoke_test else 20, + ), + param_space={ + "args": args, + "lr": tune.uniform(0.001, 0.1), + "momentum": tune.uniform(0.1, 0.9), + }, + ) + results = tuner.fit() + + print("Best config is:", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/nevergrad_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/nevergrad_example.py new file mode 100644 index 0000000000000000000000000000000000000000..5414f10e5501f6159973ff17400f31623c4f3c97 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/nevergrad_example.py @@ -0,0 +1,77 @@ +"""This example demonstrates the usage of Nevergrad with Ray Tune. + +It also checks that it is usable with a separate scheduler. + +Requires the Nevergrad library to be installed (`pip install nevergrad`). +""" + +import time + +from ray import tune +from ray.tune.schedulers import AsyncHyperBandScheduler +from ray.tune.search import ConcurrencyLimiter +from ray.tune.search.nevergrad import NevergradSearch + + +def evaluation_fn(step, width, height): + return (0.1 + width * step / 100) ** (-1) + height * 0.1 + + +def easy_objective(config): + # Hyperparameters + width, height = config["width"], config["height"] + + for step in range(config["steps"]): + # Iterative training function - can be any arbitrary training procedure + intermediate_score = evaluation_fn(step, width, height) + # Feed the score back back to Tune. + tune.report({"iterations": step, "mean_loss": intermediate_score}) + time.sleep(0.1) + + +if __name__ == "__main__": + import argparse + + import nevergrad as ng + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + # Optional: Pass the parameter space yourself + # space = ng.p.Dict( + # width=ng.p.Scalar(lower=0, upper=20), + # height=ng.p.Scalar(lower=-100, upper=100), + # activation=ng.p.Choice(choices=["relu", "tanh"]) + # ) + + algo = NevergradSearch( + optimizer=ng.optimizers.OnePlusOne, + # space=space, # If you want to set the space manually + ) + algo = ConcurrencyLimiter(algo, max_concurrent=4) + + scheduler = AsyncHyperBandScheduler() + + tuner = tune.Tuner( + easy_objective, + tune_config=tune.TuneConfig( + metric="mean_loss", + mode="min", + search_alg=algo, + scheduler=scheduler, + num_samples=10 if args.smoke_test else 50, + ), + run_config=tune.RunConfig(name="nevergrad"), + param_space={ + "steps": 100, + "width": tune.uniform(0, 20), + "height": tune.uniform(-100, 100), + "activation": tune.choice(["relu", "tanh"]), + }, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/optuna_define_by_run_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/optuna_define_by_run_example.py new file mode 100644 index 0000000000000000000000000000000000000000..04e08a5ef92c608c16a7a3cf27c07ff3771ea466 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/optuna_define_by_run_example.py @@ -0,0 +1,93 @@ +"""This example demonstrates the usage of Optuna define-by-run with Ray Tune. + +It also checks that it is usable with a separate scheduler. + +Requires the Optuna library to be installed (`pip install optuna`). + +For an example of using a Tune search space, see +:doc:`/tune/examples/optuna_example`. +""" + +import time +from typing import Any, Dict, Optional + +import ray +from ray import tune +from ray.tune.schedulers import AsyncHyperBandScheduler +from ray.tune.search import ConcurrencyLimiter +from ray.tune.search.optuna import OptunaSearch + + +def evaluation_fn(step, width, height, mult=1): + return (0.1 + width * step / 100) ** (-1) + height * 0.1 * mult + + +def easy_objective(config): + # Hyperparameters + width, height, mult = config["width"], config["height"], config.get("mult", 1) + print(config) + + for step in range(config["steps"]): + # Iterative training function - can be any arbitrary training procedure + intermediate_score = evaluation_fn(step, width, height, mult) + # Feed the score back back to Tune. + tune.report({"iterations": step, "mean_loss": intermediate_score}) + time.sleep(0.1) + + +def define_by_run_func(trial) -> Optional[Dict[str, Any]]: + """Define-by-run function to create the search space. + + Ensure no actual computation takes place here. That should go into + the trainable passed to ``Tuner`` (in this example, that's + ``easy_objective``). + + For more information, see https://optuna.readthedocs.io/en/stable\ +/tutorial/10_key_features/002_configurations.html + + This function should either return None or a dict with constant values. + """ + # This param is not used in the objective function. + activation = trial.suggest_categorical("activation", ["relu", "tanh"]) + trial.suggest_float("width", 0, 20) + trial.suggest_float("height", -100, 100) + + # Define-by-run allows for conditional search spaces. + if activation == "relu": + trial.suggest_float("mult", 1, 2) + + # Return all constants in a dictionary. + return {"steps": 100} + + +def run_optuna_tune(smoke_test=False): + algo = OptunaSearch(space=define_by_run_func, metric="mean_loss", mode="min") + algo = ConcurrencyLimiter(algo, max_concurrent=4) + scheduler = AsyncHyperBandScheduler() + tuner = tune.Tuner( + easy_objective, + tune_config=tune.TuneConfig( + metric="mean_loss", + mode="min", + search_alg=algo, + scheduler=scheduler, + num_samples=10 if smoke_test else 100, + ), + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + ray.init(configure_logging=False) + + run_optuna_tune(smoke_test=args.smoke_test) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/optuna_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/optuna_example.py new file mode 100644 index 0000000000000000000000000000000000000000..5c4bb7c809fa56b4358231f4e6332a674151b29d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/optuna_example.py @@ -0,0 +1,73 @@ +"""This example demonstrates the usage of Optuna with Ray Tune. + +It also checks that it is usable with a separate scheduler. + +Requires the Optuna library to be installed (`pip install optuna`). + +For an example of using an Optuna define-by-run function, see +:doc:`/tune/examples/optuna_define_by_run_example`. +""" + +import time + +import ray +from ray import tune +from ray.tune.schedulers import AsyncHyperBandScheduler +from ray.tune.search import ConcurrencyLimiter +from ray.tune.search.optuna import OptunaSearch + + +def evaluation_fn(step, width, height): + return (0.1 + width * step / 100) ** (-1) + height * 0.1 + + +def easy_objective(config): + # Hyperparameters + width, height = config["width"], config["height"] + + for step in range(config["steps"]): + # Iterative training function - can be any arbitrary training procedure + intermediate_score = evaluation_fn(step, width, height) + # Feed the score back back to Tune. + tune.report({"iterations": step, "mean_loss": intermediate_score}) + time.sleep(0.1) + + +def run_optuna_tune(smoke_test=False): + algo = OptunaSearch() + algo = ConcurrencyLimiter(algo, max_concurrent=4) + scheduler = AsyncHyperBandScheduler() + tuner = tune.Tuner( + easy_objective, + tune_config=tune.TuneConfig( + metric="mean_loss", + mode="min", + search_alg=algo, + scheduler=scheduler, + num_samples=10 if smoke_test else 100, + ), + param_space={ + "steps": 100, + "width": tune.uniform(0, 20), + "height": tune.uniform(-100, 100), + # This is an ignored parameter. + "activation": tune.choice(["relu", "tanh"]), + }, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + ray.init(configure_logging=False) + + run_optuna_tune(smoke_test=args.smoke_test) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/optuna_multiobjective_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/optuna_multiobjective_example.py new file mode 100644 index 0000000000000000000000000000000000000000..947c9dfdc2b09b13e7bc711f4952f38c703f87cb --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/optuna_multiobjective_example.py @@ -0,0 +1,79 @@ +"""This example demonstrates the usage of Optuna with Ray Tune for +multi-objective optimization. + +Please note that schedulers may not work correctly with multi-objective +optimization. + +Requires the Optuna library to be installed (`pip install optuna`). +""" +import time + +import ray +from ray import tune +from ray.tune.search import ConcurrencyLimiter +from ray.tune.search.optuna import OptunaSearch + + +def evaluation_fn(step, width, height): + return (0.1 + width * step / 100) ** (-1) + height * 0.1 + + +def easy_objective(config): + # Hyperparameters + width, height = config["width"], config["height"] + + for step in range(config["steps"]): + # Iterative training function - can be any arbitrary training procedure + intermediate_score = evaluation_fn(step, width, height) + # Feed the score back back to Tune. + tune.report( + { + "iterations": step, + "loss": intermediate_score, + "gain": intermediate_score * width, + } + ) + time.sleep(0.1) + + +def run_optuna_tune(smoke_test=False): + algo = OptunaSearch(metric=["loss", "gain"], mode=["min", "max"]) + algo = ConcurrencyLimiter(algo, max_concurrent=4) + tuner = tune.Tuner( + easy_objective, + tune_config=tune.TuneConfig( + search_alg=algo, + num_samples=10 if smoke_test else 100, + ), + param_space={ + "steps": 100, + "width": tune.uniform(0, 20), + "height": tune.uniform(-100, 100), + # This is an ignored parameter. + "activation": tune.choice(["relu", "tanh"]), + }, + ) + results = tuner.fit() + + print( + "Best hyperparameters for loss found were: ", + results.get_best_result("loss", "min").config, + ) + print( + "Best hyperparameters for gain found were: ", + results.get_best_result("gain", "max").config, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + ray.init(configure_logging=False) + + run_optuna_tune(smoke_test=args.smoke_test) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pb2_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pb2_example.py new file mode 100644 index 0000000000000000000000000000000000000000..5bb56f8b2016b9967dc69bb21da05cddad3c230e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pb2_example.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python + +import argparse + +import ray +from ray import tune +from ray.tune.examples.pbt_function import pbt_function +from ray.tune.schedulers.pb2 import PB2 + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + if args.smoke_test: + ray.init(num_cpus=2) # force pausing to happen for test + + perturbation_interval = 5 + pbt = PB2( + time_attr="training_iteration", + perturbation_interval=perturbation_interval, + hyperparam_bounds={ + # hyperparameter bounds. + "lr": [0.0001, 0.02], + }, + ) + + tuner = tune.Tuner( + pbt_function, + run_config=tune.RunConfig( + name="pbt_test", + verbose=False, + stop={ + "training_iteration": 30, + }, + failure_config=tune.FailureConfig( + fail_fast=True, + ), + ), + tune_config=tune.TuneConfig( + scheduler=pbt, + metric="mean_accuracy", + mode="max", + num_samples=8, + reuse_actors=True, + ), + param_space={ + "lr": 0.0001, + # note: this parameter is perturbed but has no effect on + # the model training in this example + "some_other_factor": 1, + # This parameter is not perturbed and is used to determine + # checkpoint frequency. We set checkpoints and perturbations + # to happen at the same frequency. + "checkpoint_interval": perturbation_interval, + }, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pb2_ppo_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pb2_ppo_example.py new file mode 100644 index 0000000000000000000000000000000000000000..75d184beefdedf412bb48d48dd628164ac8518c1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pb2_ppo_example.py @@ -0,0 +1,157 @@ +import argparse +import os +import random +from datetime import datetime + +import pandas as pd + +from ray.tune import run, sample_from +from ray.tune.schedulers import PopulationBasedTraining +from ray.tune.schedulers.pb2 import PB2 + + +# Postprocess the perturbed config to ensure it's still valid used if PBT. +def explore(config): + # Ensure we collect enough timesteps to do sgd. + if config["train_batch_size"] < config["sgd_minibatch_size"] * 2: + config["train_batch_size"] = config["sgd_minibatch_size"] * 2 + # Ensure we run at least one sgd iter. + if config["lambda"] > 1: + config["lambda"] = 1 + config["train_batch_size"] = int(config["train_batch_size"]) + return config + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--max", type=int, default=1000000) + parser.add_argument("--algo", type=str, default="PPO") + parser.add_argument("--num_workers", type=int, default=4) + parser.add_argument("--num_samples", type=int, default=4) + parser.add_argument("--t_ready", type=int, default=50000) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument( + "--horizon", type=int, default=1600 + ) # make this 1000 for other envs + parser.add_argument("--perturb", type=float, default=0.25) # if using PBT + parser.add_argument("--env_name", type=str, default="BipedalWalker-v2") + parser.add_argument( + "--criteria", type=str, default="timesteps_total" + ) # "training_iteration", "time_total_s" + parser.add_argument( + "--net", type=str, default="32_32" + ) # May be important to use a larger network for bigger tasks. + parser.add_argument("--filename", type=str, default="") + parser.add_argument("--method", type=str, default="pb2") # ['pbt', 'pb2'] + parser.add_argument("--save_csv", type=bool, default=False) + + args = parser.parse_args() + + # bipedalwalker needs 1600 + if args.env_name in ["BipedalWalker-v2", "BipedalWalker-v3"]: + horizon = 1600 + else: + horizon = 1000 + + pbt = PopulationBasedTraining( + time_attr=args.criteria, + metric="episode_reward_mean", + mode="max", + perturbation_interval=args.t_ready, + resample_probability=args.perturb, + quantile_fraction=args.perturb, # copy bottom % with top % + # Specifies the search space for these hyperparams + hyperparam_mutations={ + "lambda": lambda: random.uniform(0.9, 1.0), + "clip_param": lambda: random.uniform(0.1, 0.5), + "lr": lambda: random.uniform(1e-3, 1e-5), + "train_batch_size": lambda: random.randint(1000, 60000), + }, + custom_explore_fn=explore, + ) + + pb2 = PB2( + time_attr=args.criteria, + metric="episode_reward_mean", + mode="max", + perturbation_interval=args.t_ready, + quantile_fraction=args.perturb, # copy bottom % with top % + # Specifies the hyperparam search space + hyperparam_bounds={ + "lambda": [0.9, 1.0], + "clip_param": [0.1, 0.5], + "lr": [1e-5, 1e-3], + "train_batch_size": [1000, 60000], + }, + ) + + methods = {"pbt": pbt, "pb2": pb2} + + timelog = ( + str(datetime.date(datetime.now())) + "_" + str(datetime.time(datetime.now())) + ) + + args.dir = "{}_{}_{}_Size{}_{}_{}".format( + args.algo, + args.filename, + args.method, + str(args.num_samples), + args.env_name, + args.criteria, + ) + + analysis = run( + args.algo, + name="{}_{}_{}_seed{}_{}".format( + timelog, args.method, args.env_name, str(args.seed), args.filename + ), + scheduler=methods[args.method], + verbose=1, + num_samples=args.num_samples, + reuse_actors=True, + stop={args.criteria: args.max}, + config={ + "env": args.env_name, + "log_level": "INFO", + "seed": args.seed, + "kl_coeff": 1.0, + "num_gpus": 0, + "horizon": horizon, + "observation_filter": "MeanStdFilter", + "model": { + "fcnet_hiddens": [ + int(args.net.split("_")[0]), + int(args.net.split("_")[1]), + ], + "free_log_std": True, + }, + "num_sgd_iter": 10, + "sgd_minibatch_size": 128, + "lambda": sample_from(lambda spec: random.uniform(0.9, 1.0)), + "clip_param": sample_from(lambda spec: random.uniform(0.1, 0.5)), + "lr": sample_from(lambda spec: random.uniform(1e-3, 1e-5)), + "train_batch_size": sample_from(lambda spec: random.randint(1000, 60000)), + }, + ) + + all_dfs = list(analysis.trial_dataframes.values()) + + results = pd.DataFrame() + for i in range(args.num_samples): + df = all_dfs[i] + df = df[ + [ + "timesteps_total", + "episodes_total", + "episode_reward_mean", + "info/learner/default_policy/cur_kl_coeff", + ] + ] + df["Agent"] = i + results = pd.concat([results, df]).reset_index(drop=True) + + if args.save_csv: + if not (os.path.exists("data/" + args.dir)): + os.makedirs("data/" + args.dir) + + results.to_csv("data/{}/seed{}.csv".format(args.dir, str(args.seed))) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_convnet_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_convnet_example.py new file mode 100644 index 0000000000000000000000000000000000000000..9365ad73ebcfdc60084c15c15b2ce2854a21d0cb --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_convnet_example.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python + +# ruff: noqa +# fmt: off + +# __tutorial_imports_begin__ +import argparse +import os + +import numpy as np +import torch +import torch.optim as optim +from torchvision import datasets + +import ray +from ray import tune +from ray.tune.examples.mnist_pytorch import ( + ConvNet, + get_data_loaders, + test_func, + train_func, +) +from ray.tune.schedulers import PopulationBasedTraining +from ray.tune.utils import validate_save_restore + +# __tutorial_imports_end__ + + +# __trainable_begin__ +class PytorchTrainable(tune.Trainable): + """Train a Pytorch ConvNet with Trainable and PopulationBasedTraining + scheduler. The example reuse some of the functions in mnist_pytorch, + and is a good demo for how to add the tuning function without + changing the original training code. + """ + + def setup(self, config): + self.train_loader, self.test_loader = get_data_loaders() + self.model = ConvNet() + self.optimizer = optim.SGD( + self.model.parameters(), + lr=config.get("lr", 0.01), + momentum=config.get("momentum", 0.9)) + + def step(self): + train_func(self.model, self.optimizer, self.train_loader) + acc = test_func(self.model, self.test_loader) + return {"mean_accuracy": acc} + + def save_checkpoint(self, checkpoint_dir): + checkpoint_path = os.path.join(checkpoint_dir, "model.pth") + torch.save(self.model.state_dict(), checkpoint_path) + + def load_checkpoint(self, checkpoint_dir): + checkpoint_path = os.path.join(checkpoint_dir, "model.pth") + self.model.load_state_dict(torch.load(checkpoint_path)) + + def reset_config(self, new_config): + for param_group in self.optimizer.param_groups: + if "lr" in new_config: + param_group["lr"] = new_config["lr"] + if "momentum" in new_config: + param_group["momentum"] = new_config["momentum"] + + self.config = new_config + return True +# __trainable_end__ + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing") + args, _ = parser.parse_known_args() + + ray.init(num_cpus=2) + datasets.MNIST("~/data", train=True, download=True) + + # check if PytorchTrainble will save/restore correctly before execution + validate_save_restore(PytorchTrainable) + + # __pbt_begin__ + scheduler = PopulationBasedTraining( + time_attr="training_iteration", + perturbation_interval=5, + hyperparam_mutations={ + # distribution for resampling + "lr": lambda: np.random.uniform(0.0001, 1), + # allow perturbations within this set of categorical values + "momentum": [0.8, 0.9, 0.99], + }) + # __pbt_end__ + + # __tune_begin__ + class CustomStopper(tune.Stopper): + def __init__(self): + self.should_stop = False + + def __call__(self, trial_id, result): + max_iter = 5 if args.smoke_test else 100 + if not self.should_stop and result["mean_accuracy"] > 0.96: + self.should_stop = True + return self.should_stop or result["training_iteration"] >= max_iter + + def stop_all(self): + return self.should_stop + + stopper = CustomStopper() + + tuner = tune.Tuner( + PytorchTrainable, + run_config=tune.RunConfig( + name="pbt_test", + stop=stopper, + verbose=1, + checkpoint_config=tune.CheckpointConfig( + checkpoint_score_attribute="mean_accuracy", + checkpoint_frequency=5, + num_to_keep=4, + ), + ), + tune_config=tune.TuneConfig( + scheduler=scheduler, + metric="mean_accuracy", + mode="max", + num_samples=4, + reuse_actors=True, + ), + param_space={ + "lr": tune.uniform(0.001, 1), + "momentum": tune.uniform(0.001, 1), + }, + ) + results = tuner.fit() + # __tune_end__ + + best_result = results.get_best_result() + best_checkpoint = best_result.checkpoint diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_convnet_function_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_convnet_function_example.py new file mode 100644 index 0000000000000000000000000000000000000000..82cfb040a6adae176037f27b802635dfbd6d7275 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_convnet_function_example.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python + +# __tutorial_imports_begin__ +import argparse +import os + +import numpy as np +import torch +import torch.optim as optim + +import ray +from ray import tune +from ray.tune import Checkpoint +from ray.tune.examples.mnist_pytorch import ConvNet, get_data_loaders, test_func +from ray.tune.schedulers import PopulationBasedTraining + +# __tutorial_imports_end__ + + +# __train_begin__ +def train_convnet(config): + # Create our data loaders, model, and optmizer. + step = 0 + train_loader, test_loader = get_data_loaders() + model = ConvNet() + optimizer = optim.SGD( + model.parameters(), + lr=config.get("lr", 0.01), + momentum=config.get("momentum", 0.9), + ) + + # If `get_checkpoint()` is not None, then we are resuming from a checkpoint. + # Load model state and iteration step from checkpoint. + if tune.get_checkpoint(): + print("Loading from checkpoint.") + loaded_checkpoint = tune.get_checkpoint() + with loaded_checkpoint.as_directory() as loaded_checkpoint_dir: + path = os.path.join(loaded_checkpoint_dir, "checkpoint.pt") + checkpoint = torch.load(path) + model.load_state_dict(checkpoint["model"]) + step = checkpoint["step"] + + while True: + ray.tune.examples.mnist_pytorch.train_func(model, optimizer, train_loader) + acc = test_func(model, test_loader) + checkpoint = None + if step % 5 == 0: + # Every 5 steps, checkpoint our current state. + # First get the checkpoint directory from tune. + # Need to create a directory under current working directory + # to construct checkpoint object from. + os.makedirs("my_model", exist_ok=True) + torch.save( + { + "step": step, + "model": model.state_dict(), + }, + "my_model/checkpoint.pt", + ) + checkpoint = Checkpoint.from_directory("my_model") + + step += 1 + tune.report({"mean_accuracy": acc}, checkpoint=checkpoint) + + +# __train_end__ + + +def eval_best_model(results: tune.ResultGrid): + """Test the best model given output of tuner.fit().""" + with results.get_best_result().checkpoint.as_directory() as best_checkpoint_path: + best_model = ConvNet() + best_checkpoint = torch.load( + os.path.join(best_checkpoint_path, "checkpoint.pt") + ) + best_model.load_state_dict(best_checkpoint["model"]) + # Note that test only runs on a small random set of the test data, thus the + # accuracy may be different from metrics shown in tuning process. + test_acc = test_func(best_model, get_data_loaders()[1]) + print("best model accuracy: ", test_acc) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + # __pbt_begin__ + scheduler = PopulationBasedTraining( + time_attr="training_iteration", + perturbation_interval=5, + hyperparam_mutations={ + # distribution for resampling + "lr": lambda: np.random.uniform(0.0001, 1), + # allow perturbations within this set of categorical values + "momentum": [0.8, 0.9, 0.99], + }, + ) + + # __pbt_end__ + + # __tune_begin__ + class CustomStopper(tune.Stopper): + def __init__(self): + self.should_stop = False + + def __call__(self, trial_id, result): + max_iter = 5 if args.smoke_test else 100 + if not self.should_stop and result["mean_accuracy"] > 0.96: + self.should_stop = True + return self.should_stop or result["training_iteration"] >= max_iter + + def stop_all(self): + return self.should_stop + + stopper = CustomStopper() + + tuner = tune.Tuner( + train_convnet, + run_config=tune.RunConfig( + name="pbt_test", + stop=stopper, + verbose=1, + checkpoint_config=tune.CheckpointConfig( + checkpoint_score_attribute="mean_accuracy", + num_to_keep=4, + ), + ), + tune_config=tune.TuneConfig( + scheduler=scheduler, + metric="mean_accuracy", + mode="max", + num_samples=4, + reuse_actors=True, + ), + param_space={ + "lr": tune.uniform(0.001, 1), + "momentum": tune.uniform(0.001, 1), + }, + ) + results = tuner.fit() + # __tune_end__ + + eval_best_model(results) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ced62d56ec7934577fbb1da6326f292f766ca84 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/common.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..159c3a4a187a25077b1d8487cb7375f5366da354 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/common.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/pbt_dcgan_mnist_func.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/pbt_dcgan_mnist_func.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8b0e561652edeea70e65b92cdb468f6903ed215 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/pbt_dcgan_mnist_func.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/pbt_dcgan_mnist_trainable.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/pbt_dcgan_mnist_trainable.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5092327d45605b4c8c6fb2fc80a42aa095014eb Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/__pycache__/pbt_dcgan_mnist_trainable.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/common.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/common.py new file mode 100644 index 0000000000000000000000000000000000000000..c8ee8ad8ff621d5c63db7060909ea18421ca044b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/common.py @@ -0,0 +1,285 @@ +import os + +import matplotlib.animation as animation +import matplotlib.pyplot as plt +import numpy as np +import torch +import torch.nn as nn +import torch.nn.parallel +import torch.utils.data +import torchvision.datasets as dset +import torchvision.transforms as transforms +import torchvision.utils as vutils +from scipy.stats import entropy +from torch.autograd import Variable +from torch.nn import functional as F + +import ray + +# Training parameters +workers = 2 +batch_size = 64 +image_size = 32 + +# Number of channels in the training images. For color images this is 3 +nc = 1 + +# Size of z latent vector (i.e. size of generator input) +nz = 100 + +# Size of feature maps in generator +ngf = 32 + +# Size of feature maps in discriminator +ndf = 32 + +# Beta1 hyperparam for Adam optimizers +beta1 = 0.5 + +# iterations of actual training in each Trainable _train +train_iterations_per_step = 5 + +MODEL_PATH = os.path.expanduser("~/.ray/models/mnist_cnn.pt") + + +def get_data_loader(data_dir="~/data"): + dataset = dset.MNIST( + root=data_dir, + download=True, + transform=transforms.Compose( + [ + transforms.Resize(image_size), + transforms.ToTensor(), + transforms.Normalize((0.13066,), (0.30131,)), + ] + ), + ) + + # Create the dataloader + dataloader = torch.utils.data.DataLoader( + dataset, batch_size=batch_size, shuffle=True, num_workers=workers + ) + + return dataloader + + +# __GANmodel_begin__ +# custom weights initialization called on netG and netD +def weights_init(m): + classname = m.__class__.__name__ + if classname.find("Conv") != -1: + nn.init.normal_(m.weight.data, 0.0, 0.02) + elif classname.find("BatchNorm") != -1: + nn.init.normal_(m.weight.data, 1.0, 0.02) + nn.init.constant_(m.bias.data, 0) + + +# Generator Code +class Generator(nn.Module): + def __init__(self): + super(Generator, self).__init__() + self.main = nn.Sequential( + # input is Z, going into a convolution + nn.ConvTranspose2d(nz, ngf * 4, 4, 1, 0, bias=False), + nn.BatchNorm2d(ngf * 4), + nn.ReLU(True), + nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False), + nn.BatchNorm2d(ngf * 2), + nn.ReLU(True), + nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False), + nn.BatchNorm2d(ngf), + nn.ReLU(True), + nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False), + nn.Tanh(), + ) + + def forward(self, input): + return self.main(input) + + +class Discriminator(nn.Module): + def __init__(self): + super(Discriminator, self).__init__() + self.main = nn.Sequential( + nn.Conv2d(nc, ndf, 4, 2, 1, bias=False), + nn.LeakyReLU(0.2, inplace=True), + nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False), + nn.BatchNorm2d(ndf * 2), + nn.LeakyReLU(0.2, inplace=True), + nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False), + nn.BatchNorm2d(ndf * 4), + nn.LeakyReLU(0.2, inplace=True), + nn.Conv2d(ndf * 4, 1, 4, 1, 0, bias=False), + nn.Sigmoid(), + ) + + def forward(self, input): + return self.main(input) + + +# __GANmodel_end__ + + +# __INCEPTION_SCORE_begin__ +class Net(nn.Module): + """ + LeNet for MNist classification, used for inception_score + """ + + def __init__(self): + super(Net, self).__init__() + self.conv1 = nn.Conv2d(1, 10, kernel_size=5) + self.conv2 = nn.Conv2d(10, 20, kernel_size=5) + self.conv2_drop = nn.Dropout2d() + self.fc1 = nn.Linear(320, 50) + self.fc2 = nn.Linear(50, 10) + + def forward(self, x): + x = F.relu(F.max_pool2d(self.conv1(x), 2)) + x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) + x = x.view(-1, 320) + x = F.relu(self.fc1(x)) + x = F.dropout(x, training=self.training) + x = self.fc2(x) + return F.log_softmax(x, dim=1) + + +def inception_score(imgs, mnist_model_ref, batch_size=32, splits=1): + N = len(imgs) + dtype = torch.FloatTensor + dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size) + cm = ray.get(mnist_model_ref) # Get the mnist model from Ray object store. + up = nn.Upsample(size=(28, 28), mode="bilinear").type(dtype) + + def get_pred(x): + x = up(x) + x = cm(x) + return F.softmax(x).data.cpu().numpy() + + preds = np.zeros((N, 10)) + for i, batch in enumerate(dataloader, 0): + batch = batch.type(dtype) + batchv = Variable(batch) + batch_size_i = batch.size()[0] + preds[i * batch_size : i * batch_size + batch_size_i] = get_pred(batchv) + + # Now compute the mean kl-div + split_scores = [] + for k in range(splits): + part = preds[k * (N // splits) : (k + 1) * (N // splits), :] + py = np.mean(part, axis=0) + scores = [] + for i in range(part.shape[0]): + pyx = part[i, :] + scores.append(entropy(pyx, py)) + split_scores.append(np.exp(np.mean(scores))) + + return np.mean(split_scores), np.std(split_scores) + + +# __INCEPTION_SCORE_end__ + + +def train_func( + netD, + netG, + optimG, + optimD, + criterion, + dataloader, + iteration, + device, + mnist_model_ref, +): + real_label = 1 + fake_label = 0 + + for i, data in enumerate(dataloader, 0): + if i >= train_iterations_per_step: + break + + netD.zero_grad() + real_cpu = data[0].to(device) + b_size = real_cpu.size(0) + label = torch.full((b_size,), real_label, dtype=torch.float, device=device) + output = netD(real_cpu).view(-1) + errD_real = criterion(output, label) + errD_real.backward() + D_x = output.mean().item() + + noise = torch.randn(b_size, nz, 1, 1, device=device) + fake = netG(noise) + label.fill_(fake_label) + output = netD(fake.detach()).view(-1) + errD_fake = criterion(output, label) + errD_fake.backward() + D_G_z1 = output.mean().item() + errD = errD_real + errD_fake + optimD.step() + + netG.zero_grad() + label.fill_(real_label) + output = netD(fake).view(-1) + errG = criterion(output, label) + errG.backward() + D_G_z2 = output.mean().item() + optimG.step() + + is_score, is_std = inception_score(fake, mnist_model_ref) + + # Output training stats + if iteration % 10 == 0: + print( + "[%d/%d]\tLoss_D: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z))" + ": %.4f / %.4f \tInception score: %.4f" + % ( + iteration, + len(dataloader), + errD.item(), + errG.item(), + D_x, + D_G_z1, + D_G_z2, + is_score, + ) + ) + + return errG.item(), errD.item(), is_score + + +def plot_images(dataloader): + # Plot some training images + real_batch = next(iter(dataloader)) + plt.figure(figsize=(8, 8)) + plt.axis("off") + plt.title("Original Images") + plt.imshow( + np.transpose( + vutils.make_grid(real_batch[0][:64], padding=2, normalize=True).cpu(), + (1, 2, 0), + ) + ) + + plt.show() + + +def demo_gan(checkpoint_paths): + img_list = [] + fixed_noise = torch.randn(64, nz, 1, 1) + for path in checkpoint_paths: + checkpoint_dict = torch.load(os.path.join(path, "checkpoint.pt")) + + loadedG = Generator() + loadedG.load_state_dict(checkpoint_dict["netGmodel"]) + with torch.no_grad(): + fake = loadedG(fixed_noise).detach().cpu() + img_list.append(vutils.make_grid(fake, padding=2, normalize=True)) + + fig = plt.figure(figsize=(8, 8)) + plt.axis("off") + ims = [[plt.imshow(np.transpose(i, (1, 2, 0)), animated=True)] for i in img_list] + ani = animation.ArtistAnimation( + fig, ims, interval=1000, repeat_delay=1000, blit=True + ) + ani.save("./generated.gif", writer="imagemagick", dpi=72) + plt.show() diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/pbt_dcgan_mnist_func.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/pbt_dcgan_mnist_func.py new file mode 100644 index 0000000000000000000000000000000000000000..57d28cb41f5e7fdb35a2c6a86a0cd5c5ec8dd673 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/pbt_dcgan_mnist_func.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python +""" +Example of training DCGAN on MNIST using PBT with Tune's function API. +""" +import argparse +import os +import tempfile + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.parallel +import torch.optim as optim +import torch.utils.data +from filelock import FileLock + +import ray +from ray import tune +from ray.tune import Checkpoint +from ray.tune.examples.pbt_dcgan_mnist.common import ( + MODEL_PATH, + Discriminator, + Generator, + Net, + beta1, + demo_gan, + get_data_loader, + plot_images, + train_func, + weights_init, +) +from ray.tune.schedulers import PopulationBasedTraining + + +# __Train_begin__ +def dcgan_train(config): + use_cuda = config.get("use_gpu") and torch.cuda.is_available() + device = torch.device("cuda" if use_cuda else "cpu") + netD = Discriminator().to(device) + netD.apply(weights_init) + netG = Generator().to(device) + netG.apply(weights_init) + criterion = nn.BCELoss() + optimizerD = optim.Adam( + netD.parameters(), lr=config.get("lr", 0.01), betas=(beta1, 0.999) + ) + optimizerG = optim.Adam( + netG.parameters(), lr=config.get("lr", 0.01), betas=(beta1, 0.999) + ) + with FileLock(os.path.expanduser("~/ray_results/.data.lock")): + dataloader = get_data_loader() + + step = 1 + checkpoint = tune.get_checkpoint() + if checkpoint: + with checkpoint.as_directory() as checkpoint_dir: + checkpoint_dict = torch.load(os.path.join(checkpoint_dir, "checkpoint.pt")) + netD.load_state_dict(checkpoint_dict["netDmodel"]) + netG.load_state_dict(checkpoint_dict["netGmodel"]) + optimizerD.load_state_dict(checkpoint_dict["optimD"]) + optimizerG.load_state_dict(checkpoint_dict["optimG"]) + # Note: Make sure to increment the loaded step by 1 to get the + # current step. + last_step = checkpoint_dict["step"] + step = last_step + 1 + + # NOTE: It's important to set the optimizer learning rates + # again, since we want to explore the parameters passed in by PBT. + # Without this, we would continue using the exact same + # configuration as the trial whose checkpoint we are exploiting. + if "netD_lr" in config: + for param_group in optimizerD.param_groups: + param_group["lr"] = config["netD_lr"] + if "netG_lr" in config: + for param_group in optimizerG.param_groups: + param_group["lr"] = config["netG_lr"] + + while True: + lossG, lossD, is_score = train_func( + netD, + netG, + optimizerG, + optimizerD, + criterion, + dataloader, + step, + device, + config["mnist_model_ref"], + ) + metrics = {"lossg": lossG, "lossd": lossD, "is_score": is_score} + + if step % config["checkpoint_interval"] == 0: + with tempfile.TemporaryDirectory() as tmpdir: + torch.save( + { + "netDmodel": netD.state_dict(), + "netGmodel": netG.state_dict(), + "optimD": optimizerD.state_dict(), + "optimG": optimizerG.state_dict(), + "step": step, + }, + os.path.join(tmpdir, "checkpoint.pt"), + ) + tune.report(metrics, checkpoint=Checkpoint.from_directory(tmpdir)) + else: + tune.report(metrics) + + step += 1 + + +# __Train_end__ + + +def download_mnist_cnn(): + import urllib.request + + # Download a pre-trained MNIST model for inception score calculation. + # This is a tiny model (<100kb). + if not os.path.exists(MODEL_PATH): + print("downloading model") + os.makedirs(os.path.dirname(MODEL_PATH), exist_ok=True) + urllib.request.urlretrieve( + "https://github.com/ray-project/ray/raw/master/python/ray/tune/" + "examples/pbt_dcgan_mnist/mnist_cnn.pt", + MODEL_PATH, + ) + return MODEL_PATH + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + parser.add_argument( + "--data-dir", type=str, default="~/data/", help="Set the path of the dataset." + ) + args, _ = parser.parse_known_args() + ray.init() + + download_mnist_cnn() + + dataloader = get_data_loader(args.data_dir) + if not args.smoke_test: + plot_images(dataloader) + + # __tune_begin__ + + # load the pretrained mnist classification model for inception_score + mnist_cnn = Net() + mnist_cnn.load_state_dict(torch.load(MODEL_PATH)) + mnist_cnn.eval() + # Put the model in Ray object store. + mnist_model_ref = ray.put(mnist_cnn) + + scheduler = PopulationBasedTraining( + perturbation_interval=5, + hyperparam_mutations={ + # distribution for resampling + "netG_lr": lambda: np.random.uniform(1e-2, 1e-5), + "netD_lr": lambda: np.random.uniform(1e-2, 1e-5), + }, + ) + + tune_iter = 5 if args.smoke_test else 300 + tuner = tune.Tuner( + dcgan_train, + run_config=tune.RunConfig( + name="pbt_dcgan_mnist", + stop={"training_iteration": tune_iter}, + verbose=1, + ), + tune_config=tune.TuneConfig( + metric="is_score", + mode="max", + num_samples=8, + scheduler=scheduler, + ), + param_space={ + "netG_lr": tune.choice([0.0001, 0.0002, 0.0005]), + "netD_lr": tune.choice([0.0001, 0.0002, 0.0005]), + "mnist_model_ref": mnist_model_ref, + }, + ) + results = tuner.fit() + # __tune_end__ + + # demo of the trained Generators + if not args.smoke_test: + checkpoint_paths = [result.checkpoint.to_directory() for result in results] + demo_gan(checkpoint_paths) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/pbt_dcgan_mnist_trainable.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/pbt_dcgan_mnist_trainable.py new file mode 100644 index 0000000000000000000000000000000000000000..51909033f658f83ad5c08610e730efdd5b413520 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_dcgan_mnist/pbt_dcgan_mnist_trainable.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python +""" +Example of training DCGAN on MNIST using PBT with Tune's Trainable Class +API. +""" +import argparse +import os +import random + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.parallel +import torch.optim as optim +import torch.utils.data +from filelock import FileLock + +import ray +from ray import tune +from ray.tune.examples.pbt_dcgan_mnist.common import ( + MODEL_PATH, + Discriminator, + Generator, + Net, + beta1, + demo_gan, + get_data_loader, + plot_images, + train_func, + weights_init, +) +from ray.tune.schedulers import PopulationBasedTraining + + +# __Trainable_begin__ +class PytorchTrainable(tune.Trainable): + def setup(self, config): + use_cuda = config.get("use_gpu") and torch.cuda.is_available() + self.device = torch.device("cuda" if use_cuda else "cpu") + self.netD = Discriminator().to(self.device) + self.netD.apply(weights_init) + self.netG = Generator().to(self.device) + self.netG.apply(weights_init) + self.criterion = nn.BCELoss() + self.optimizerD = optim.Adam( + self.netD.parameters(), lr=config.get("lr", 0.01), betas=(beta1, 0.999) + ) + self.optimizerG = optim.Adam( + self.netG.parameters(), lr=config.get("lr", 0.01), betas=(beta1, 0.999) + ) + with FileLock(os.path.expanduser("~/.data.lock")): + self.dataloader = get_data_loader(config.get("data_dir", "~/data")) + self.mnist_model_ref = config["mnist_model_ref"] + + def step(self): + lossG, lossD, is_score = train_func( + self.netD, + self.netG, + self.optimizerG, + self.optimizerD, + self.criterion, + self.dataloader, + self._iteration, + self.device, + self.mnist_model_ref, + ) + return {"lossg": lossG, "lossd": lossD, "is_score": is_score} + + def save_checkpoint(self, checkpoint_dir): + path = os.path.join(checkpoint_dir, "checkpoint.pt") + torch.save( + { + "netDmodel": self.netD.state_dict(), + "netGmodel": self.netG.state_dict(), + "optimD": self.optimizerD.state_dict(), + "optimG": self.optimizerG.state_dict(), + }, + path, + ) + + return checkpoint_dir + + def load_checkpoint(self, checkpoint_dir): + path = os.path.join(checkpoint_dir, "checkpoint.pt") + checkpoint = torch.load(path) + self.netD.load_state_dict(checkpoint["netDmodel"]) + self.netG.load_state_dict(checkpoint["netGmodel"]) + self.optimizerD.load_state_dict(checkpoint["optimD"]) + self.optimizerG.load_state_dict(checkpoint["optimG"]) + + def reset_config(self, new_config): + if "netD_lr" in new_config: + for param_group in self.optimizerD.param_groups: + param_group["lr"] = new_config["netD_lr"] + if "netG_lr" in new_config: + for param_group in self.optimizerG.param_groups: + param_group["lr"] = new_config["netG_lr"] + + self.config = new_config + return True + + +# __Trainable_end__ + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + parser.add_argument( + "--data-dir", type=str, default="~/data/", help="Set the path of the dataset." + ) + args, _ = parser.parse_known_args() + ray.init() + + import urllib.request + + # Download a pre-trained MNIST model for inception score calculation. + # This is a tiny model (<100kb). + if not os.path.exists(MODEL_PATH): + print("downloading model") + os.makedirs(os.path.dirname(MODEL_PATH), exist_ok=True) + urllib.request.urlretrieve( + "https://github.com/ray-project/ray/raw/master/python/ray/tune/" + "examples/pbt_dcgan_mnist/mnist_cnn.pt", + MODEL_PATH, + ) + + dataloader = get_data_loader() + if not args.smoke_test: + plot_images(dataloader) + + # load the pretrained mnist classification model for inception_score + mnist_cnn = Net() + mnist_cnn.load_state_dict(torch.load(MODEL_PATH)) + mnist_cnn.eval() + mnist_model_ref = ray.put(mnist_cnn) + + # __tune_begin__ + scheduler = PopulationBasedTraining( + time_attr="training_iteration", + perturbation_interval=5, + hyperparam_mutations={ + # distribution for resampling + "netG_lr": lambda: np.random.uniform(1e-2, 1e-5), + "netD_lr": lambda: np.random.uniform(1e-2, 1e-5), + }, + ) + + tune_iter = 10 if args.smoke_test else 300 + tuner = tune.Tuner( + PytorchTrainable, + run_config=tune.RunConfig( + name="pbt_dcgan_mnist", + stop={"training_iteration": tune_iter}, + verbose=1, + checkpoint_config=tune.CheckpointConfig(checkpoint_at_end=True), + ), + tune_config=tune.TuneConfig( + metric="is_score", + mode="max", + num_samples=8, + scheduler=scheduler, + reuse_actors=True, + ), + param_space={ + "netG_lr": tune.sample_from( + lambda spec: random.choice([0.0001, 0.0002, 0.0005]) + ), + "netD_lr": tune.sample_from( + lambda spec: random.choice([0.0001, 0.0002, 0.0005]) + ), + "mnist_model_ref": mnist_model_ref, + "data_dir": args.data_dir, + }, + ) + results = tuner.fit() + + # export_formats=[ExportFormat.MODEL] + # __tune_end__ + + # demo of the trained Generators + if not args.smoke_test: + checkpoint_paths = [result.checkpoint.to_directory() for result in results] + demo_gan(checkpoint_paths) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_example.py new file mode 100644 index 0000000000000000000000000000000000000000..c8d3208069574757a415b03be3a09697f03500ad --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_example.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python + +import argparse +import random + +import numpy as np + +import ray +from ray import tune +from ray.tune.schedulers import PopulationBasedTraining + + +class PBTBenchmarkExample(tune.Trainable): + """Toy PBT problem for benchmarking adaptive learning rate. + + The goal is to optimize this trainable's accuracy. The accuracy increases + fastest at the optimal lr, which is a function of the current accuracy. + + The optimal lr schedule for this problem is the triangle wave as follows. + Note that many lr schedules for real models also follow this shape: + + best lr + ^ + | /\ + | / \ + | / \ + | / \ + ------------> accuracy + + In this problem, using PBT with a population of 2-4 is sufficient to + roughly approximate this lr schedule. Higher population sizes will yield + faster convergence. Training will not converge without PBT. + """ + + def setup(self, config): + self.lr = config["lr"] + self.accuracy = 0.0 # end = 1000 + + def step(self): + midpoint = 100 # lr starts decreasing after acc > midpoint + q_tolerance = 3 # penalize exceeding lr by more than this multiple + noise_level = 2 # add gaussian noise to the acc increase + # triangle wave: + # - start at 0.001 @ t=0, + # - peak at 0.01 @ t=midpoint, + # - end at 0.001 @ t=midpoint * 2, + if self.accuracy < midpoint: + optimal_lr = 0.01 * self.accuracy / midpoint + else: + optimal_lr = 0.01 - 0.01 * (self.accuracy - midpoint) / midpoint + optimal_lr = min(0.01, max(0.001, optimal_lr)) + + # compute accuracy increase + q_err = max(self.lr, optimal_lr) / min(self.lr, optimal_lr) + if q_err < q_tolerance: + self.accuracy += (1.0 / q_err) * random.random() + elif self.lr > optimal_lr: + self.accuracy -= (q_err - q_tolerance) * random.random() + self.accuracy += noise_level * np.random.normal() + self.accuracy = max(0, self.accuracy) + + return { + "mean_accuracy": self.accuracy, + "cur_lr": self.lr, + "optimal_lr": optimal_lr, # for debugging + "q_err": q_err, # for debugging + "done": self.accuracy > midpoint * 2, + } + + def save_checkpoint(self, checkpoint_dir): + return { + "accuracy": self.accuracy, + "lr": self.lr, + } + + def load_checkpoint(self, checkpoint): + self.accuracy = checkpoint["accuracy"] + + def reset_config(self, new_config): + self.lr = new_config["lr"] + self.config = new_config + return True + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + if args.smoke_test: + ray.init(num_cpus=2) # force pausing to happen for test + + perturbation_interval = 5 + pbt = PopulationBasedTraining( + time_attr="training_iteration", + perturbation_interval=perturbation_interval, + hyperparam_mutations={ + # distribution for resampling + "lr": lambda: random.uniform(0.0001, 0.02), + # allow perturbations within this set of categorical values + "some_other_factor": [1, 2], + }, + ) + + tuner = tune.Tuner( + PBTBenchmarkExample, + run_config=tune.RunConfig( + name="pbt_class_api_example", + # Stop when done = True or at some # of train steps (whichever comes first) + stop={ + "done": True, + "training_iteration": 10 if args.smoke_test else 1000, + }, + verbose=0, + # We recommend matching `perturbation_interval` and `checkpoint_interval` + # (e.g. checkpoint every 4 steps, and perturb on those same steps) + # or making `perturbation_interval` a multiple of `checkpoint_interval` + # (e.g. checkpoint every 2 steps, and perturb every 4 steps). + # This is to ensure that the lastest checkpoints are being used by PBT + # when trials decide to exploit. If checkpointing and perturbing are not + # aligned, then PBT may use a stale checkpoint to resume from. + checkpoint_config=tune.CheckpointConfig( + checkpoint_frequency=perturbation_interval, + checkpoint_score_attribute="mean_accuracy", + num_to_keep=4, + ), + ), + tune_config=tune.TuneConfig( + scheduler=pbt, + metric="mean_accuracy", + mode="max", + reuse_actors=True, + num_samples=8, + ), + param_space={ + "lr": 0.0001, + # note: this parameter is perturbed but has no effect on + # the model training in this example + "some_other_factor": 1, + }, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_function.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_function.py new file mode 100644 index 0000000000000000000000000000000000000000..665c5110409733cb272f7b5985adbc62ef605567 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_function.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python + +import argparse +import json +import os +import random +import tempfile + +import numpy as np + +import ray +from ray import tune +from ray.tune import Checkpoint +from ray.tune.schedulers import PopulationBasedTraining + + +def pbt_function(config): + """Toy PBT problem for benchmarking adaptive learning rate. + + The goal is to optimize this trainable's accuracy. The accuracy increases + fastest at the optimal lr, which is a function of the current accuracy. + + The optimal lr schedule for this problem is the triangle wave as follows. + Note that many lr schedules for real models also follow this shape: + + best lr + ^ + | /\ + | / \ + | / \ + | / \ + ------------> accuracy + + In this problem, using PBT with a population of 2-4 is sufficient to + roughly approximate this lr schedule. Higher population sizes will yield + faster convergence. Training will not converge without PBT. + """ + lr = config["lr"] + checkpoint_interval = config.get("checkpoint_interval", 1) + + accuracy = 0.0 # end = 1000 + + # NOTE: See below why step is initialized to 1 + step = 1 + checkpoint = tune.get_checkpoint() + if checkpoint: + with checkpoint.as_directory() as checkpoint_dir: + with open(os.path.join(checkpoint_dir, "checkpoint.json"), "r") as f: + checkpoint_dict = json.load(f) + + accuracy = checkpoint_dict["acc"] + last_step = checkpoint_dict["step"] + # Current step should be 1 more than the last checkpoint step + step = last_step + 1 + + # triangle wave: + # - start at 0.001 @ t=0, + # - peak at 0.01 @ t=midpoint, + # - end at 0.001 @ t=midpoint * 2, + midpoint = 100 # lr starts decreasing after acc > midpoint + q_tolerance = 3 # penalize exceeding lr by more than this multiple + noise_level = 2 # add gaussian noise to the acc increase + + # Let `stop={"done": True}` in the configs below handle trial stopping + while True: + if accuracy < midpoint: + optimal_lr = 0.01 * accuracy / midpoint + else: + optimal_lr = 0.01 - 0.01 * (accuracy - midpoint) / midpoint + optimal_lr = min(0.01, max(0.001, optimal_lr)) + + # compute accuracy increase + q_err = max(lr, optimal_lr) / min(lr, optimal_lr) + if q_err < q_tolerance: + accuracy += (1.0 / q_err) * random.random() + elif lr > optimal_lr: + accuracy -= (q_err - q_tolerance) * random.random() + accuracy += noise_level * np.random.normal() + accuracy = max(0, accuracy) + + metrics = { + "mean_accuracy": accuracy, + "cur_lr": lr, + "optimal_lr": optimal_lr, # for debugging + "q_err": q_err, # for debugging + "done": accuracy > midpoint * 2, # this stops the training process + } + + if step % checkpoint_interval == 0: + # Checkpoint every `checkpoint_interval` steps + # NOTE: if we initialized `step=0` above, our checkpointing and perturbing + # would be out of sync by 1 step. + # Ex: if `checkpoint_interval` = `perturbation_interval` = 3 + # step: 0 (checkpoint) 1 2 3 (checkpoint) + # training_iteration: 1 2 3 (perturb) 4 + with tempfile.TemporaryDirectory() as tempdir: + with open(os.path.join(tempdir, "checkpoint.json"), "w") as f: + checkpoint_dict = {"acc": accuracy, "step": step} + json.dump(checkpoint_dict, f) + tune.report(metrics, checkpoint=Checkpoint.from_directory(tempdir)) + else: + tune.report(metrics) + step += 1 + + +def run_tune_pbt(smoke_test=False): + perturbation_interval = 5 + pbt = PopulationBasedTraining( + time_attr="training_iteration", + perturbation_interval=perturbation_interval, + hyperparam_mutations={ + # distribution for resampling + "lr": tune.uniform(0.0001, 0.02), + # allow perturbations within this set of categorical values + "some_other_factor": [1, 2], + }, + ) + + tuner = tune.Tuner( + pbt_function, + run_config=tune.RunConfig( + name="pbt_function_api_example", + verbose=False, + stop={ + # Stop when done = True or at some # of train steps + # (whichever comes first) + "done": True, + "training_iteration": 10 if smoke_test else 1000, + }, + failure_config=tune.FailureConfig( + fail_fast=True, + ), + checkpoint_config=tune.CheckpointConfig( + checkpoint_score_attribute="mean_accuracy", + num_to_keep=2, + ), + ), + tune_config=tune.TuneConfig( + scheduler=pbt, + metric="mean_accuracy", + mode="max", + num_samples=8, + reuse_actors=True, + ), + param_space={ + "lr": 0.0001, + # Note: `some_other_factor` is perturbed because it is specified under + # the PBT scheduler's `hyperparam_mutations` argument, but has no effect on + # the model training in this example + "some_other_factor": 1, + # Note: `checkpoint_interval` will not be perturbed (since it's not + # included above), and it will be used to determine how many steps to take + # between each checkpoint. + # We recommend matching `perturbation_interval` and `checkpoint_interval` + # (e.g. checkpoint every 4 steps, and perturb on those same steps) + # or making `perturbation_interval` a multiple of `checkpoint_interval` + # (e.g. checkpoint every 2 steps, and perturb every 4 steps). + # This is to ensure that the lastest checkpoints are being used by PBT + # when trials decide to exploit. If checkpointing and perturbing are not + # aligned, then PBT may use a stale checkpoint to resume from. + "checkpoint_interval": perturbation_interval, + }, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", + action="store_true", + default=False, + help="Finish quickly for testing", + ) + args, _ = parser.parse_known_args() + if args.smoke_test: + ray.init(num_cpus=2) # force pausing to happen for test + + run_tune_pbt(smoke_test=args.smoke_test) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_memnn_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_memnn_example.py new file mode 100644 index 0000000000000000000000000000000000000000..2129f5a6cebd1424c86de58520328ef765e3e43e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_memnn_example.py @@ -0,0 +1,325 @@ +"""Example training a memory neural net on the bAbI dataset. + +References Keras and is based off of https://keras.io/examples/babi_memnn/. +""" + +from __future__ import print_function + +import argparse +import os +import re +import sys +import tarfile + +import numpy as np +from filelock import FileLock + +from ray import tune + +if sys.version_info >= (3, 12): + # Skip this test in Python 3.12+ because TensorFlow is not supported. + sys.exit(0) +else: + from tensorflow.keras.layers import ( + LSTM, + Activation, + Dense, + Dropout, + Embedding, + Input, + Permute, + add, + concatenate, + dot, + ) + from tensorflow.keras.models import Model, Sequential, load_model + from tensorflow.keras.optimizers import RMSprop + from tensorflow.keras.preprocessing.sequence import pad_sequences + from tensorflow.keras.utils import get_file + + +def tokenize(sent): + """Return the tokens of a sentence including punctuation. + + >>> tokenize("Bob dropped the apple. Where is the apple?") + ["Bob", "dropped", "the", "apple", ".", "Where", "is", "the", "apple", "?"] + """ + return [x.strip() for x in re.split(r"(\W+)?", sent) if x and x.strip()] + + +def parse_stories(lines, only_supporting=False): + """Parse stories provided in the bAbi tasks format + + If only_supporting is true, only the sentences + that support the answer are kept. + """ + data = [] + story = [] + for line in lines: + line = line.decode("utf-8").strip() + nid, line = line.split(" ", 1) + nid = int(nid) + if nid == 1: + story = [] + if "\t" in line: + q, a, supporting = line.split("\t") + q = tokenize(q) + if only_supporting: + # Only select the related substory + supporting = map(int, supporting.split()) + substory = [story[i - 1] for i in supporting] + else: + # Provide all the substories + substory = [x for x in story if x] + data.append((substory, q, a)) + story.append("") + else: + sent = tokenize(line) + story.append(sent) + return data + + +def get_stories(f, only_supporting=False, max_length=None): + """Given a file name, read the file, + retrieve the stories, + and then convert the sentences into a single story. + + If max_length is supplied, + any stories longer than max_length tokens will be discarded. + """ + + def flatten(data): + return sum(data, []) + + data = parse_stories(f.readlines(), only_supporting=only_supporting) + data = [ + (flatten(story), q, answer) + for story, q, answer in data + if not max_length or len(flatten(story)) < max_length + ] + return data + + +def vectorize_stories(word_idx, story_maxlen, query_maxlen, data): + inputs, queries, answers = [], [], [] + for story, query, answer in data: + inputs.append([word_idx[w] for w in story]) + queries.append([word_idx[w] for w in query]) + answers.append(word_idx[answer]) + return ( + pad_sequences(inputs, maxlen=story_maxlen), + pad_sequences(queries, maxlen=query_maxlen), + np.array(answers), + ) + + +def read_data(finish_fast=False): + # Get the file + try: + path = get_file( + "babi-tasks-v1-2.tar.gz", + origin="https://s3.amazonaws.com/text-datasets/" + "babi_tasks_1-20_v1-2.tar.gz", + ) + except Exception: + print( + "Error downloading dataset, please download it manually:\n" + "$ wget http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2" # noqa: E501 + ".tar.gz\n" + "$ mv tasks_1-20_v1-2.tar.gz ~/.keras/datasets/babi-tasks-v1-2.tar.gz" # noqa: E501 + ) + raise + + # Choose challenge + challenges = { + # QA1 with 10,000 samples + "single_supporting_fact_10k": "tasks_1-20_v1-2/en-10k/qa1_" + "single-supporting-fact_{}.txt", + # QA2 with 10,000 samples + "two_supporting_facts_10k": "tasks_1-20_v1-2/en-10k/qa2_" + "two-supporting-facts_{}.txt", + } + challenge_type = "single_supporting_fact_10k" + challenge = challenges[challenge_type] + + with tarfile.open(path) as tar: + train_stories = get_stories(tar.extractfile(challenge.format("train"))) + test_stories = get_stories(tar.extractfile(challenge.format("test"))) + if finish_fast: + train_stories = train_stories[:64] + test_stories = test_stories[:64] + return train_stories, test_stories + + +class MemNNModel(tune.Trainable): + def build_model(self): + """Helper method for creating the model""" + vocab = set() + for story, q, answer in self.train_stories + self.test_stories: + vocab |= set(story + q + [answer]) + vocab = sorted(vocab) + + # Reserve 0 for masking via pad_sequences + vocab_size = len(vocab) + 1 + story_maxlen = max(len(x) for x, _, _ in self.train_stories + self.test_stories) + query_maxlen = max(len(x) for _, x, _ in self.train_stories + self.test_stories) + + word_idx = {c: i + 1 for i, c in enumerate(vocab)} + self.inputs_train, self.queries_train, self.answers_train = vectorize_stories( + word_idx, story_maxlen, query_maxlen, self.train_stories + ) + self.inputs_test, self.queries_test, self.answers_test = vectorize_stories( + word_idx, story_maxlen, query_maxlen, self.test_stories + ) + + # placeholders + input_sequence = Input((story_maxlen,)) + question = Input((query_maxlen,)) + + # encoders + # embed the input sequence into a sequence of vectors + input_encoder_m = Sequential() + input_encoder_m.add(Embedding(input_dim=vocab_size, output_dim=64)) + input_encoder_m.add(Dropout(self.config.get("dropout", 0.3))) + # output: (samples, story_maxlen, embedding_dim) + + # embed the input into a sequence of vectors of size query_maxlen + input_encoder_c = Sequential() + input_encoder_c.add(Embedding(input_dim=vocab_size, output_dim=query_maxlen)) + input_encoder_c.add(Dropout(self.config.get("dropout", 0.3))) + # output: (samples, story_maxlen, query_maxlen) + + # embed the question into a sequence of vectors + question_encoder = Sequential() + question_encoder.add( + Embedding(input_dim=vocab_size, output_dim=64, input_length=query_maxlen) + ) + question_encoder.add(Dropout(self.config.get("dropout", 0.3))) + # output: (samples, query_maxlen, embedding_dim) + + # encode input sequence and questions (which are indices) + # to sequences of dense vectors + input_encoded_m = input_encoder_m(input_sequence) + input_encoded_c = input_encoder_c(input_sequence) + question_encoded = question_encoder(question) + + # compute a "match" between the first input vector sequence + # and the question vector sequence + # shape: `(samples, story_maxlen, query_maxlen)` + match = dot([input_encoded_m, question_encoded], axes=(2, 2)) + match = Activation("softmax")(match) + + # add the match matrix with the second input vector sequence + response = add( + [match, input_encoded_c] + ) # (samples, story_maxlen, query_maxlen) + response = Permute((2, 1))(response) # (samples, query_maxlen, story_maxlen) + + # concatenate the match matrix with the question vector sequence + answer = concatenate([response, question_encoded]) + + # the original paper uses a matrix multiplication. + # we choose to use a RNN instead. + answer = LSTM(32)(answer) # (samples, 32) + + # one regularization layer -- more would probably be needed. + answer = Dropout(self.config.get("dropout", 0.3))(answer) + answer = Dense(vocab_size)(answer) # (samples, vocab_size) + # we output a probability distribution over the vocabulary + answer = Activation("softmax")(answer) + + # build the final model + model = Model([input_sequence, question], answer) + return model + + def setup(self, config): + with FileLock(os.path.expanduser("~/.tune.lock")): + self.train_stories, self.test_stories = read_data(config["finish_fast"]) + model = self.build_model() + rmsprop = RMSprop( + lr=self.config.get("lr", 1e-3), rho=self.config.get("rho", 0.9) + ) + model.compile( + optimizer=rmsprop, + loss="sparse_categorical_crossentropy", + metrics=["accuracy"], + ) + self.model = model + + def step(self): + # train + self.model.fit( + [self.inputs_train, self.queries_train], + self.answers_train, + batch_size=self.config.get("batch_size", 32), + epochs=self.config.get("epochs", 1), + validation_data=([self.inputs_test, self.queries_test], self.answers_test), + verbose=0, + ) + _, accuracy = self.model.evaluate( + [self.inputs_train, self.queries_train], self.answers_train, verbose=0 + ) + return {"mean_accuracy": accuracy} + + def save_checkpoint(self, checkpoint_dir): + file_path = checkpoint_dir + "/model" + self.model.save(file_path) + + def load_checkpoint(self, checkpoint_dir): + # See https://stackoverflow.com/a/42763323 + del self.model + file_path = checkpoint_dir + "/model" + self.model = load_model(file_path) + + +if __name__ == "__main__": + import ray + from ray.tune.schedulers import PopulationBasedTraining + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + if args.smoke_test: + ray.init(num_cpus=2) + + perturbation_interval = 2 + pbt = PopulationBasedTraining( + perturbation_interval=perturbation_interval, + hyperparam_mutations={ + "dropout": lambda: np.random.uniform(0, 1), + "lr": lambda: 10 ** np.random.randint(-10, 0), + "rho": lambda: np.random.uniform(0, 1), + }, + ) + + tuner = tune.Tuner( + MemNNModel, + run_config=tune.RunConfig( + name="pbt_babi_memnn", + stop={"training_iteration": 4 if args.smoke_test else 100}, + checkpoint_config=tune.CheckpointConfig( + checkpoint_frequency=perturbation_interval, + checkpoint_score_attribute="mean_accuracy", + num_to_keep=2, + ), + ), + tune_config=tune.TuneConfig( + scheduler=pbt, + metric="mean_accuracy", + mode="max", + num_samples=2, + reuse_actors=True, + ), + param_space={ + "finish_fast": args.smoke_test, + "batch_size": 32, + "epochs": 1, + "dropout": 0.3, + "lr": 0.01, + "rho": 0.9, + }, + ) + tuner.fit() diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_ppo_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_ppo_example.py new file mode 100644 index 0000000000000000000000000000000000000000..5e3f4216f47a3f01023b9cc456c7f78b542fd524 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_ppo_example.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python +"""Example of using PBT with RLlib. + +Note that this requires a cluster with at least 8 GPUs in order for all trials +to run concurrently, otherwise PBT will round-robin train the trials which +is less efficient (or you can set {"gpu": 0} to use CPUs for SGD instead). + +Note that Tune in general does not need 8 GPUs, and this is just a more +computationally demanding example. +""" + +import random + +from ray import tune +from ray.rllib.algorithms.ppo import PPO +from ray.tune.schedulers import PopulationBasedTraining + +if __name__ == "__main__": + # Postprocess the perturbed config to ensure it's still valid + def explore(config): + # ensure we collect enough timesteps to do sgd + if config["train_batch_size"] < config["sgd_minibatch_size"] * 2: + config["train_batch_size"] = config["sgd_minibatch_size"] * 2 + # ensure we run at least one sgd iter + if config["num_sgd_iter"] < 1: + config["num_sgd_iter"] = 1 + return config + + pbt = PopulationBasedTraining( + time_attr="time_total_s", + perturbation_interval=120, + resample_probability=0.25, + # Specifies the mutations of these hyperparams + hyperparam_mutations={ + "lambda": lambda: random.uniform(0.9, 1.0), + "clip_param": lambda: random.uniform(0.01, 0.5), + "lr": [1e-3, 5e-4, 1e-4, 5e-5, 1e-5], + "num_sgd_iter": lambda: random.randint(1, 30), + "sgd_minibatch_size": lambda: random.randint(128, 16384), + "train_batch_size": lambda: random.randint(2000, 160000), + }, + custom_explore_fn=explore, + ) + + tuner = tune.Tuner( + PPO, + run_config=tune.RunConfig( + name="pbt_humanoid_test", + ), + tune_config=tune.TuneConfig( + scheduler=pbt, + num_samples=8, + metric="episode_reward_mean", + mode="max", + reuse_actors=True, + ), + param_space={ + "env": "Humanoid-v1", + "kl_coeff": 1.0, + "num_workers": 8, + "num_gpus": 1, + "model": {"free_log_std": True}, + # These params are tuned from a fixed starting value. + "lambda": 0.95, + "clip_param": 0.2, + "lr": 1e-4, + # These params start off randomly drawn from a set. + "num_sgd_iter": tune.choice([10, 20, 30]), + "sgd_minibatch_size": tune.choice([128, 512, 2048]), + "train_batch_size": tune.choice([10000, 20000, 40000]), + }, + ) + results = tuner.fit() + + print("best hyperparameters: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b606bef4584e44b7dfee91022b12df2aaee2bbc Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/__pycache__/pbt_transformers.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/__pycache__/pbt_transformers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a21416fa81442d9aa64b50b36af728d078dbd24 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/__pycache__/pbt_transformers.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/__pycache__/utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2d70c3b4e349e985306657d3bcb8231df14d71c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/__pycache__/utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/pbt_transformers.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/pbt_transformers.py new file mode 100644 index 0000000000000000000000000000000000000000..2688c057cd6e2ae3974eee0ac7fabde1f31275ae --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/pbt_transformers.py @@ -0,0 +1,165 @@ +""" +This example is uses the official +huggingface transformers `hyperparameter_search` API. +""" + +import os + +from transformers import ( + AutoConfig, + AutoModelForSequenceClassification, + AutoTokenizer, + GlueDataset, + GlueDataTrainingArguments, + Trainer, + TrainingArguments, + glue_tasks_num_labels, +) + +from ray import tune +from ray.tune import CheckpointConfig, CLIReporter +from ray.tune.examples.pbt_transformers.utils import ( + build_compute_metrics_fn, + download_data, +) +from ray.tune.schedulers import PopulationBasedTraining + + +def tune_transformer(num_samples=8, gpus_per_trial=0, smoke_test=False): + data_dir_name = "./data" if not smoke_test else "./test_data" + data_dir = os.path.abspath(os.path.join(os.getcwd(), data_dir_name)) + if not os.path.exists(data_dir): + os.mkdir(data_dir, 0o755) + + # Change these as needed. + model_name = ( + "bert-base-uncased" if not smoke_test else "sshleifer/tiny-distilroberta-base" + ) + task_name = "rte" + + task_data_dir = os.path.join(data_dir, task_name.upper()) + + num_labels = glue_tasks_num_labels[task_name] + + config = AutoConfig.from_pretrained( + model_name, num_labels=num_labels, finetuning_task=task_name + ) + + # Download and cache tokenizer, model, and features + print("Downloading and caching Tokenizer") + tokenizer = AutoTokenizer.from_pretrained(model_name) + + # Triggers tokenizer download to cache + print("Downloading and caching pre-trained model") + AutoModelForSequenceClassification.from_pretrained( + model_name, + config=config, + ) + + def get_model(): + return AutoModelForSequenceClassification.from_pretrained( + model_name, + config=config, + ) + + # Download data. + download_data(task_name, data_dir) + + data_args = GlueDataTrainingArguments(task_name=task_name, data_dir=task_data_dir) + + train_dataset = GlueDataset( + data_args, tokenizer=tokenizer, mode="train", cache_dir=task_data_dir + ) + eval_dataset = GlueDataset( + data_args, tokenizer=tokenizer, mode="dev", cache_dir=task_data_dir + ) + + training_args = TrainingArguments( + output_dir=".", + learning_rate=1e-5, # config + do_train=True, + do_eval=True, + no_cuda=gpus_per_trial <= 0, + evaluation_strategy="epoch", + save_strategy="epoch", + load_best_model_at_end=True, + num_train_epochs=2, # config + max_steps=-1, + per_device_train_batch_size=16, # config + per_device_eval_batch_size=16, # config + warmup_steps=0, + weight_decay=0.1, # config + logging_dir="./logs", + skip_memory_metrics=True, + report_to="none", + ) + + trainer = Trainer( + model_init=get_model, + args=training_args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + compute_metrics=build_compute_metrics_fn(task_name), + ) + + tune_config = { + "per_device_train_batch_size": 32, + "per_device_eval_batch_size": 32, + "num_train_epochs": tune.choice([2, 3, 4, 5]), + "max_steps": 1 if smoke_test else -1, # Used for smoke test. + } + + scheduler = PopulationBasedTraining( + time_attr="training_iteration", + metric="eval_acc", + mode="max", + perturbation_interval=1, + hyperparam_mutations={ + "weight_decay": tune.uniform(0.0, 0.3), + "learning_rate": tune.uniform(1e-5, 5e-5), + "per_device_train_batch_size": [16, 32, 64], + }, + ) + + reporter = CLIReporter( + parameter_columns={ + "weight_decay": "w_decay", + "learning_rate": "lr", + "per_device_train_batch_size": "train_bs/gpu", + "num_train_epochs": "num_epochs", + }, + metric_columns=["eval_acc", "eval_loss", "epoch", "training_iteration"], + ) + + trainer.hyperparameter_search( + hp_space=lambda _: tune_config, + backend="ray", + n_trials=num_samples, + resources_per_trial={"cpu": 1, "gpu": gpus_per_trial}, + scheduler=scheduler, + checkpoint_config=CheckpointConfig( + num_to_keep=1, + checkpoint_score_attribute="training_iteration", + ), + stop={"training_iteration": 1} if smoke_test else None, + progress_reporter=reporter, + local_dir="~/ray_results/", + name="tune_transformer_pbt", + log_to_file=True, + ) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + if args.smoke_test: + tune_transformer(num_samples=1, gpus_per_trial=0, smoke_test=True) + else: + # You can change the number of GPUs here: + tune_transformer(num_samples=8, gpus_per_trial=1) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/utils.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ff304664b98b2fe7835d18a5f7dc33a4a6563fd8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_transformers/utils.py @@ -0,0 +1,46 @@ +"""Utilities to load and cache data.""" + +import os +from typing import Callable, Dict + +import numpy as np +from transformers import EvalPrediction, glue_compute_metrics, glue_output_modes + + +def build_compute_metrics_fn(task_name: str) -> Callable[[EvalPrediction], Dict]: + """Function from transformers/examples/text-classification/run_glue.py""" + output_mode = glue_output_modes[task_name] + + def compute_metrics_fn(p: EvalPrediction): + if output_mode == "classification": + preds = np.argmax(p.predictions, axis=1) + elif output_mode == "regression": + preds = np.squeeze(p.predictions) + metrics = glue_compute_metrics(task_name, preds, p.label_ids) + return metrics + + return compute_metrics_fn + + +def download_data(task_name, data_dir="./data"): + # Download RTE training data + print("Downloading dataset.") + import urllib + import zipfile + + if task_name == "rte": + url = "https://dl.fbaipublicfiles.com/glue/data/RTE.zip" + else: + raise ValueError("Unknown task: {}".format(task_name)) + data_file = os.path.join(data_dir, "{}.zip".format(task_name)) + if not os.path.exists(data_file): + urllib.request.urlretrieve(url, data_file) + with zipfile.ZipFile(data_file) as zip_ref: + zip_ref.extractall(data_dir) + print("Downloaded data for task {} to {}".format(task_name, data_dir)) + else: + print( + "Data already exists. Using downloaded data for task {} from {}".format( + task_name, data_dir + ) + ) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_tune_cifar10_with_keras.py b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_tune_cifar10_with_keras.py new file mode 100644 index 0000000000000000000000000000000000000000..06638036b311afc32a6565240223450682f7e7c9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/pbt_tune_cifar10_with_keras.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Train keras CNN on the CIFAR10 small images dataset. + +The model comes from: https://zhuanlan.zhihu.com/p/29214791, +and it gets to about 87% validation accuracy in 100 epochs. + +Note that the script requires a machine with 4 GPUs. You +can set {"gpu": 0} to use CPUs for training, although +it is less efficient. +""" + +from __future__ import print_function + +import argparse + +import numpy as np +import tensorflow as tf +from tensorflow.keras.datasets import cifar10 +from tensorflow.keras.layers import ( + Convolution2D, + Dense, + Dropout, + Flatten, + Input, + MaxPooling2D, +) +from tensorflow.keras.models import Model, load_model +from tensorflow.keras.preprocessing.image import ImageDataGenerator + +from ray import tune +from ray.tune import Trainable +from ray.tune.schedulers import PopulationBasedTraining + +num_classes = 10 +NUM_SAMPLES = 128 + + +class Cifar10Model(Trainable): + def _read_data(self): + # The data, split between train and test sets: + (x_train, y_train), (x_test, y_test) = cifar10.load_data() + + # Convert class vectors to binary class matrices. + y_train = tf.keras.utils.to_categorical(y_train, num_classes) + y_test = tf.keras.utils.to_categorical(y_test, num_classes) + + x_train = x_train.astype("float32") + x_train /= 255 + x_test = x_test.astype("float32") + x_test /= 255 + + return (x_train, y_train), (x_test, y_test) + + def _build_model(self, input_shape): + x = Input(shape=(32, 32, 3)) + y = x + y = Convolution2D( + filters=64, + kernel_size=3, + strides=1, + padding="same", + activation="relu", + kernel_initializer="he_normal", + )(y) + y = Convolution2D( + filters=64, + kernel_size=3, + strides=1, + padding="same", + activation="relu", + kernel_initializer="he_normal", + )(y) + y = MaxPooling2D(pool_size=2, strides=2, padding="same")(y) + + y = Convolution2D( + filters=128, + kernel_size=3, + strides=1, + padding="same", + activation="relu", + kernel_initializer="he_normal", + )(y) + y = Convolution2D( + filters=128, + kernel_size=3, + strides=1, + padding="same", + activation="relu", + kernel_initializer="he_normal", + )(y) + y = MaxPooling2D(pool_size=2, strides=2, padding="same")(y) + + y = Convolution2D( + filters=256, + kernel_size=3, + strides=1, + padding="same", + activation="relu", + kernel_initializer="he_normal", + )(y) + y = Convolution2D( + filters=256, + kernel_size=3, + strides=1, + padding="same", + activation="relu", + kernel_initializer="he_normal", + )(y) + y = MaxPooling2D(pool_size=2, strides=2, padding="same")(y) + + y = Flatten()(y) + y = Dropout(self.config.get("dropout", 0.5))(y) + y = Dense(units=10, activation="softmax", kernel_initializer="he_normal")(y) + + model = Model(inputs=x, outputs=y, name="model1") + return model + + def setup(self, config): + self.train_data, self.test_data = self._read_data() + x_train = self.train_data[0] + model = self._build_model(x_train.shape[1:]) + + opt = tf.keras.optimizers.Adadelta( + lr=self.config.get("lr", 1e-4), weight_decay=self.config.get("decay", 1e-4) + ) + model.compile( + loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"] + ) + self.model = model + + def step(self): + x_train, y_train = self.train_data + x_train, y_train = x_train[:NUM_SAMPLES], y_train[:NUM_SAMPLES] + x_test, y_test = self.test_data + x_test, y_test = x_test[:NUM_SAMPLES], y_test[:NUM_SAMPLES] + + aug_gen = ImageDataGenerator( + # set input mean to 0 over the dataset + featurewise_center=False, + # set each sample mean to 0 + samplewise_center=False, + # divide inputs by dataset std + featurewise_std_normalization=False, + # divide each input by its std + samplewise_std_normalization=False, + # apply ZCA whitening + zca_whitening=False, + # randomly rotate images in the range (degrees, 0 to 180) + rotation_range=0, + # randomly shift images horizontally (fraction of total width) + width_shift_range=0.1, + # randomly shift images vertically (fraction of total height) + height_shift_range=0.1, + # randomly flip images + horizontal_flip=True, + # randomly flip images + vertical_flip=False, + ) + + aug_gen.fit(x_train) + batch_size = self.config.get("batch_size", 64) + gen = aug_gen.flow(x_train, y_train, batch_size=batch_size) + self.model.fit_generator( + generator=gen, epochs=self.config.get("epochs", 1), validation_data=None + ) + + # loss, accuracy + _, accuracy = self.model.evaluate(x_test, y_test, verbose=0) + return {"mean_accuracy": accuracy} + + def save_checkpoint(self, checkpoint_dir): + file_path = checkpoint_dir + "/model" + self.model.save(file_path) + + def load_checkpoint(self, checkpoint_dir): + # See https://stackoverflow.com/a/42763323 + del self.model + file_path = checkpoint_dir + "/model" + self.model = load_model(file_path) + + def cleanup(self): + # If need, save your model when exit. + # saved_path = self.model.save(self.logdir) + # print("save model at: ", saved_path) + pass + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + space = { + "epochs": 1, + "batch_size": 64, + "lr": tune.grid_search([10**-4, 10**-5]), + "decay": tune.sample_from(lambda spec: spec.config.lr / 100.0), + "dropout": tune.grid_search([0.25, 0.5]), + } + if args.smoke_test: + space["lr"] = 10**-4 + space["dropout"] = 0.5 + + perturbation_interval = 10 + pbt = PopulationBasedTraining( + time_attr="training_iteration", + perturbation_interval=perturbation_interval, + hyperparam_mutations={ + "dropout": lambda _: np.random.uniform(0, 1), + }, + ) + + tuner = tune.Tuner( + tune.with_resources( + Cifar10Model, + resources={"cpu": 1, "gpu": 1}, + ), + run_config=tune.RunConfig( + name="pbt_cifar10", + stop={ + "mean_accuracy": 0.80, + "training_iteration": 30, + }, + checkpoint_config=tune.CheckpointConfig( + checkpoint_frequency=perturbation_interval, + checkpoint_score_attribute="mean_accuracy", + num_to_keep=2, + ), + ), + tune_config=tune.TuneConfig( + scheduler=pbt, + num_samples=4, + metric="mean_accuracy", + mode="max", + reuse_actors=True, + ), + param_space=space, + ) + results = tuner.fit() + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/tf_mnist_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/tf_mnist_example.py new file mode 100644 index 0000000000000000000000000000000000000000..2d51944f51a29fa8c15ee5241b69b03cc1e724e0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/tf_mnist_example.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python +# coding: utf-8 +# +# This example showcases how to use TF2.0 APIs with Tune. +# Original code: https://www.tensorflow.org/tutorials/quickstart/advanced +# +# As of 10/12/2019: One caveat of using TF2.0 is that TF AutoGraph +# functionality does not interact nicely with Ray actors. One way to get around +# this is to `import tensorflow` inside the Tune Trainable. +# + +import argparse +import os +import sys + +from filelock import FileLock + +from ray import tune + +MAX_TRAIN_BATCH = 10 + +if sys.version_info >= (3, 12): + # Tensorflow is not installed for Python 3.12 because of keras compatibility. + sys.exit(0) +else: + from tensorflow.keras import Model + from tensorflow.keras.datasets.mnist import load_data + from tensorflow.keras.layers import Conv2D, Dense, Flatten + + +class MyModel(Model): + def __init__(self, hiddens=128): + super(MyModel, self).__init__() + self.conv1 = Conv2D(32, 3, activation="relu") + self.flatten = Flatten() + self.d1 = Dense(hiddens, activation="relu") + self.d2 = Dense(10, activation="softmax") + + def call(self, x): + x = self.conv1(x) + x = self.flatten(x) + x = self.d1(x) + return self.d2(x) + + +class MNISTTrainable(tune.Trainable): + def setup(self, config): + # IMPORTANT: See the above note. + import tensorflow as tf + + # Use FileLock to avoid race conditions. + with FileLock(os.path.expanduser("~/.tune.lock")): + (x_train, y_train), (x_test, y_test) = load_data() + x_train, x_test = x_train / 255.0, x_test / 255.0 + + # Add a channels dimension + x_train = x_train[..., tf.newaxis] + x_test = x_test[..., tf.newaxis] + self.train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)) + self.train_ds = self.train_ds.shuffle(10000).batch(config.get("batch", 32)) + + self.test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32) + + self.model = MyModel(hiddens=config.get("hiddens", 128)) + self.loss_object = tf.keras.losses.SparseCategoricalCrossentropy() + self.optimizer = tf.keras.optimizers.Adam() + self.train_loss = tf.keras.metrics.Mean(name="train_loss") + self.train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy( + name="train_accuracy" + ) + + self.test_loss = tf.keras.metrics.Mean(name="test_loss") + self.test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy( + name="test_accuracy" + ) + + @tf.function + def train_step(images, labels): + with tf.GradientTape() as tape: + predictions = self.model(images) + loss = self.loss_object(labels, predictions) + gradients = tape.gradient(loss, self.model.trainable_variables) + self.optimizer.apply_gradients( + zip(gradients, self.model.trainable_variables) + ) + + self.train_loss(loss) + self.train_accuracy(labels, predictions) + + @tf.function + def test_step(images, labels): + predictions = self.model(images) + t_loss = self.loss_object(labels, predictions) + + self.test_loss(t_loss) + self.test_accuracy(labels, predictions) + + self.tf_train_step = train_step + self.tf_test_step = test_step + + def save_checkpoint(self, checkpoint_dir: str): + return None + + def load_checkpoint(self, checkpoint): + return None + + def step(self): + self.train_loss.reset_states() + self.train_accuracy.reset_states() + self.test_loss.reset_states() + self.test_accuracy.reset_states() + + for idx, (images, labels) in enumerate(self.train_ds): + if idx > MAX_TRAIN_BATCH: # This is optional and can be removed. + break + self.tf_train_step(images, labels) + + for test_images, test_labels in self.test_ds: + self.tf_test_step(test_images, test_labels) + + # It is important to return tf.Tensors as numpy objects. + return { + "epoch": self.iteration, + "loss": self.train_loss.result().numpy(), + "accuracy": self.train_accuracy.result().numpy() * 100, + "test_loss": self.test_loss.result().numpy(), + "mean_accuracy": self.test_accuracy.result().numpy() * 100, + } + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + tuner = tune.Tuner( + MNISTTrainable, + tune_config=tune.TuneConfig( + metric="test_loss", + mode="min", + ), + run_config=tune.RunConfig( + stop={"training_iteration": 5 if args.smoke_test else 50}, + verbose=1, + ), + param_space={"hiddens": tune.grid_search([32, 64, 128])}, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/tune_basic_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/tune_basic_example.py new file mode 100644 index 0000000000000000000000000000000000000000..7834010c59f39f532b43ae946d6d75f21395a582 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/tune_basic_example.py @@ -0,0 +1,57 @@ +"""This example demonstrates basic Ray Tune random search and grid search.""" +import time + +import ray +from ray import tune + + +def evaluation_fn(step, width, height): + time.sleep(0.1) + return (0.1 + width * step / 100) ** (-1) + height * 0.1 + + +def easy_objective(config): + # Hyperparameters + width, height = config["width"], config["height"] + + for step in range(config["steps"]): + # Iterative training function - can be any arbitrary training procedure + intermediate_score = evaluation_fn(step, width, height) + # Feed the score back back to Tune. + tune.report({"iterations": step, "mean_loss": intermediate_score}) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + ray.init(configure_logging=False) + + # This will do a grid search over the `activation` parameter. This means + # that each of the two values (`relu` and `tanh`) will be sampled once + # for each sample (`num_samples`). We end up with 2 * 50 = 100 samples. + # The `width` and `height` parameters are sampled randomly. + # `steps` is a constant parameter. + + tuner = tune.Tuner( + easy_objective, + tune_config=tune.TuneConfig( + metric="mean_loss", + mode="min", + num_samples=5 if args.smoke_test else 50, + ), + param_space={ + "steps": 5 if args.smoke_test else 100, + "width": tune.uniform(0, 20), + "height": tune.uniform(-100, 100), + "activation": tune.grid_search(["relu", "tanh"]), + }, + ) + results = tuner.fit() + + print("Best hyperparameters found were: ", results.get_best_result().config) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/tune_mnist_keras.py b/venv/lib/python3.10/site-packages/ray/tune/examples/tune_mnist_keras.py new file mode 100644 index 0000000000000000000000000000000000000000..87d632eb9db724d70ddc6f6873ff8cf281083ce1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/tune_mnist_keras.py @@ -0,0 +1,99 @@ +import argparse +import os +import sys + +from filelock import FileLock + +import ray +from ray import tune +from ray.tune.schedulers import AsyncHyperBandScheduler + +if sys.version_info >= (3, 12): + # Tensorflow is not installed for Python 3.12 because of keras compatibility. + sys.exit(0) +else: + from tensorflow.keras.datasets import mnist + + from ray.air.integrations.keras import ReportCheckpointCallback + + +def train_mnist(config): + # https://github.com/tensorflow/tensorflow/issues/32159 + import tensorflow as tf + + batch_size = 128 + num_classes = 10 + epochs = 12 + + with FileLock(os.path.expanduser("~/.data.lock")): + (x_train, y_train), (x_test, y_test) = mnist.load_data() + x_train, x_test = x_train / 255.0, x_test / 255.0 + model = tf.keras.models.Sequential( + [ + tf.keras.layers.Flatten(input_shape=(28, 28)), + tf.keras.layers.Dense(config["hidden"], activation="relu"), + tf.keras.layers.Dropout(0.2), + tf.keras.layers.Dense(num_classes, activation="softmax"), + ] + ) + + model.compile( + loss="sparse_categorical_crossentropy", + optimizer=tf.keras.optimizers.SGD(lr=config["lr"], momentum=config["momentum"]), + metrics=["accuracy"], + ) + + model.fit( + x_train, + y_train, + batch_size=batch_size, + epochs=epochs, + verbose=0, + validation_data=(x_test, y_test), + callbacks=[ + ReportCheckpointCallback( + checkpoint_on=[], metrics={"mean_accuracy": "accuracy"} + ) + ], + ) + + +def tune_mnist(num_training_iterations): + sched = AsyncHyperBandScheduler( + time_attr="training_iteration", max_t=400, grace_period=20 + ) + + tuner = tune.Tuner( + tune.with_resources(train_mnist, resources={"cpu": 2, "gpu": 0}), + run_config=tune.RunConfig( + name="exp", + stop={"mean_accuracy": 0.99, "training_iteration": num_training_iterations}, + ), + tune_config=tune.TuneConfig( + scheduler=sched, + metric="mean_accuracy", + mode="max", + num_samples=10, + ), + param_space={ + "threads": 2, + "lr": tune.uniform(0.001, 0.1), + "momentum": tune.uniform(0.1, 0.9), + "hidden": tune.randint(32, 512), + }, + ) + results = tuner.fit() + print("Best hyperparameters found were: ", results.get_best_result().config) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--smoke-test", action="store_true", help="Finish quickly for testing" + ) + args, _ = parser.parse_known_args() + + if args.smoke_test: + ray.init(num_cpus=4) + + tune_mnist(num_training_iterations=2 if args.smoke_test else 300) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/utils.py b/venv/lib/python3.10/site-packages/ray/tune/examples/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8d2eb8b700d2ed3a0bf797d6d385ccd5bd8f2580 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/utils.py @@ -0,0 +1,21 @@ +import tensorflow as tf +from sklearn.datasets import load_iris +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import OneHotEncoder + + +def get_iris_data(test_size=0.2): + iris_data = load_iris() + x = iris_data.data + y = iris_data.target.reshape(-1, 1) + encoder = OneHotEncoder(sparse=False) + y = encoder.fit_transform(y) + train_x, test_x, train_y, test_y = train_test_split(x, y) + return train_x, train_y, test_x, test_y + + +def set_keras_threads(threads): + # We set threads here to avoid contention, as Keras + # is heavily parallelized across multiple cores. + tf.config.threading.set_inter_op_parallelism_threads(threads) + tf.config.threading.set_intra_op_parallelism_threads(threads) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/xgboost_dynamic_resources_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/xgboost_dynamic_resources_example.py new file mode 100644 index 0000000000000000000000000000000000000000..e84ef5219e226e1a7e64959c4bba6640da7f9b54 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/xgboost_dynamic_resources_example.py @@ -0,0 +1,183 @@ +from typing import TYPE_CHECKING, Any, Dict, Optional + +import sklearn.datasets +import sklearn.metrics +import xgboost as xgb +from sklearn.model_selection import train_test_split + +import ray +from ray import tune +from ray.tune.execution.placement_groups import PlacementGroupFactory +from ray.tune.experiment import Trial +from ray.tune.integration.xgboost import TuneReportCheckpointCallback +from ray.tune.schedulers import ASHAScheduler, ResourceChangingScheduler + +if TYPE_CHECKING: + from ray.tune.execution.tune_controller import TuneController + +CHECKPOINT_FILENAME = "booster-checkpoint.json" + + +def get_best_model_checkpoint(best_result: "ray.train.Result"): + best_bst = TuneReportCheckpointCallback.get_model( + best_result.checkpoint, filename=CHECKPOINT_FILENAME + ) + + accuracy = 1.0 - best_result.metrics["eval-logloss"] + print(f"Best model parameters: {best_result.config}") + print(f"Best model total accuracy: {accuracy:.4f}") + return best_bst + + +# our train function needs to be able to checkpoint +# to work with ResourceChangingScheduler +def train_breast_cancer(config: dict): + # This is a simple training function to be passed into Tune + # Load dataset + data, labels = sklearn.datasets.load_breast_cancer(return_X_y=True) + # Split into train and test set + train_x, test_x, train_y, test_y = train_test_split(data, labels, test_size=0.25) + # Build input matrices for XGBoost + train_set = xgb.DMatrix(train_x, label=train_y) + test_set = xgb.DMatrix(test_x, label=test_y) + + # Checkpointing needs to be set up in order for dynamic + # resource allocation to work as intended + xgb_model = None + checkpoint = tune.get_checkpoint() + if checkpoint: + xgb_model = TuneReportCheckpointCallback.get_model( + checkpoint, filename=CHECKPOINT_FILENAME + ) + + # Set `nthread` to the number of CPUs available to the trial, + # which is assigned by the scheduler. + config["nthread"] = int(tune.get_context().get_trial_resources().head_cpus) + print(f"nthreads: {config['nthread']} xgb_model: {xgb_model}") + # Train the classifier, using the Tune callback + xgb.train( + config, + train_set, + evals=[(test_set, "eval")], + verbose_eval=False, + xgb_model=xgb_model, + callbacks=[ + TuneReportCheckpointCallback( + # checkpointing should happen every iteration + # with dynamic resource allocation + frequency=1, + filename=CHECKPOINT_FILENAME, + ) + ], + ) + + +def tune_xgboost(): + search_space = { + # You can mix constants with search space objects. + "objective": "binary:logistic", + "eval_metric": ["logloss", "error"], + "max_depth": 9, + "learning_rate": 1, + "min_child_weight": tune.grid_search([2, 3]), + "subsample": tune.grid_search([0.8, 0.9]), + "colsample_bynode": tune.grid_search([0.8, 0.9]), + "random_state": 1, + "num_parallel_tree": 2000, + } + # This will enable aggressive early stopping of bad trials. + base_scheduler = ASHAScheduler( + max_t=16, grace_period=1, reduction_factor=2 # 16 training iterations + ) + + def example_resources_allocation_function( + tune_controller: "TuneController", + trial: Trial, + result: Dict[str, Any], + scheduler: "ResourceChangingScheduler", + ) -> Optional[PlacementGroupFactory]: + """This is a basic example of a resource allocating function. + + The function naively balances available CPUs over live trials. + + This function returns a new ``PlacementGroupFactory`` with updated + resource requirements, or None. If the returned + ``PlacementGroupFactory`` is equal by value to the one the + trial has currently, the scheduler will skip the update process + internally (same with None). + + See :class:`DistributeResources` for a more complex, + robust approach. + + Args: + tune_controller: Trial runner for this Tune run. + Can be used to obtain information about other trials. + trial: The trial to allocate new resources to. + result: The latest results of trial. + scheduler: The scheduler calling the function. + """ + + # Get base trial resources as defined in + # ``tune.with_resources`` + base_trial_resource = scheduler._base_trial_resources + + # Don't bother if this is just the first iteration + if result["training_iteration"] < 1: + return None + + # default values if resources_per_trial is unspecified + if base_trial_resource is None: + base_trial_resource = PlacementGroupFactory([{"CPU": 1, "GPU": 0}]) + + # Assume that the number of CPUs cannot go below what was + # specified in ``Tuner.fit()``. + min_cpu = base_trial_resource.required_resources.get("CPU", 0) + + # Get the number of CPUs available in total (not just free) + total_available_cpus = tune_controller._resource_updater.get_num_cpus() + + # Divide the free CPUs among all live trials + cpu_to_use = max( + min_cpu, total_available_cpus // len(tune_controller.get_live_trials()) + ) + + # Assign new CPUs to the trial in a PlacementGroupFactory + return PlacementGroupFactory([{"CPU": cpu_to_use, "GPU": 0}]) + + # You can either define your own resources_allocation_function, or + # use the default one - DistributeResources + + # from ray.tune.schedulers.resource_changing_scheduler import \ + # DistributeResources + + scheduler = ResourceChangingScheduler( + base_scheduler=base_scheduler, + resources_allocation_function=example_resources_allocation_function, + # resources_allocation_function=DistributeResources() # default + ) + + tuner = tune.Tuner( + tune.with_resources( + train_breast_cancer, resources=PlacementGroupFactory([{"CPU": 1, "GPU": 0}]) + ), + tune_config=tune.TuneConfig( + metric="eval-logloss", + mode="min", + num_samples=1, + scheduler=scheduler, + ), + param_space=search_space, + ) + results = tuner.fit() + + return results.get_best_result() + + +if __name__ == "__main__": + ray.init(num_cpus=8) + + best_result = tune_xgboost() + best_bst = get_best_model_checkpoint(best_result) + + # You could now do further predictions with + # best_bst.predict(...) diff --git a/venv/lib/python3.10/site-packages/ray/tune/examples/xgboost_example.py b/venv/lib/python3.10/site-packages/ray/tune/examples/xgboost_example.py new file mode 100644 index 0000000000000000000000000000000000000000..951ab897705615dc6cfda3a6dee4bd7b3aecb63c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/examples/xgboost_example.py @@ -0,0 +1,130 @@ +from typing import Dict, List + +import numpy as np +import sklearn.datasets +import sklearn.metrics +import xgboost as xgb +from sklearn.model_selection import train_test_split + +import ray +from ray import tune +from ray.tune.integration.xgboost import TuneReportCheckpointCallback +from ray.tune.schedulers import ASHAScheduler + +CHECKPOINT_FILENAME = "booster-checkpoint.json" + + +def train_breast_cancer(config: dict): + # This is a simple training function to be passed into Tune + + # Load dataset + data, labels = sklearn.datasets.load_breast_cancer(return_X_y=True) + + # Split into train and test set + train_x, test_x, train_y, test_y = train_test_split(data, labels, test_size=0.25) + # Build input matrices for XGBoost + train_set = xgb.DMatrix(train_x, label=train_y) + test_set = xgb.DMatrix(test_x, label=test_y) + + # Train the classifier, using the Tune callback + xgb.train( + config, + train_set, + evals=[(test_set, "test")], + verbose_eval=False, + callbacks=[ + TuneReportCheckpointCallback(frequency=1, filename=CHECKPOINT_FILENAME) + ], + ) + + +def train_breast_cancer_cv(config: dict): + # This is a simple training function to be passed into Tune + # using xgboost's cross validation functionality + + # Load dataset + data, labels = sklearn.datasets.load_breast_cancer(return_X_y=True) + + # For CV, we need to average over a list of results form folds + def average_cv_folds(results_dict: Dict[str, List[float]]) -> Dict[str, float]: + return {k: np.mean(v) for k, v in results_dict.items()} + + train_set = xgb.DMatrix(data, label=labels) + + # Run CV, using the Tune callback + xgb.cv( + config, + train_set, + verbose_eval=False, + stratified=True, + # Checkpointing is not supported for CV + callbacks=[ + TuneReportCheckpointCallback( + results_postprocessing_fn=average_cv_folds, frequency=0 + ) + ], + ) + + +def get_best_model_checkpoint(best_result: "ray.train.Result"): + best_bst = TuneReportCheckpointCallback.get_model( + best_result.checkpoint, filename=CHECKPOINT_FILENAME + ) + accuracy = 1.0 - best_result.metrics["test-error"] + print(f"Best model parameters: {best_result.config}") + print(f"Best model total accuracy: {accuracy:.4f}") + return best_bst + + +def tune_xgboost(use_cv: bool = False): + search_space = { + # You can mix constants with search space objects. + "objective": "binary:logistic", + "eval_metric": ["logloss", "error"], + "max_depth": tune.randint(1, 9), + "min_child_weight": tune.choice([1, 2, 3]), + "subsample": tune.uniform(0.5, 1.0), + "eta": tune.loguniform(1e-4, 1e-1), + } + # This will enable aggressive early stopping of bad trials. + scheduler = ASHAScheduler( + max_t=10, grace_period=1, reduction_factor=2 # 10 training iterations + ) + + tuner = tune.Tuner( + tune.with_resources( + train_breast_cancer if not use_cv else train_breast_cancer_cv, + # You can add "gpu": 0.1 to allocate GPUs + resources={"cpu": 1}, + ), + tune_config=tune.TuneConfig( + metric="test-logloss", + mode="min", + num_samples=10, + scheduler=scheduler, + ), + param_space=search_space, + ) + results = tuner.fit() + + return results.get_best_result() + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--use-cv", action="store_true", help="Use `xgb.cv` instead of `xgb.train`." + ) + args, _ = parser.parse_known_args() + + best_result = tune_xgboost(args.use_cv) + + # Load the best model checkpoint. + # Checkpointing is not supported when using `xgb.cv` + if not args.use_cv: + best_bst = get_best_model_checkpoint(best_result) + + # You could now do further predictions with + # best_bst.predict(...) diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/execution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2262d522b63ba549ece261057b430a210b8f012f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/class_cache.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/class_cache.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3cd0a9729a7308dbfdda59c09b338985e2ee243 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/class_cache.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/cluster_info.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/cluster_info.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97254c42c94e81032ba01a9a2caee7061f673f10 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/cluster_info.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/experiment_state.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/experiment_state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4bf43d2288c7d341f93257a1983a3d93a3d5642 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/experiment_state.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/insufficient_resources_manager.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/insufficient_resources_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f49ce057fe7c0ceec3bd959d0006e5495aa11b93 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/insufficient_resources_manager.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/placement_groups.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/placement_groups.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b461e32d7d306d7ae12e4842191c784e2d08863 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/placement_groups.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/tune_controller.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/tune_controller.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e290360fd5570709da8e6acff8783822601a33b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/execution/__pycache__/tune_controller.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/class_cache.py b/venv/lib/python3.10/site-packages/ray/tune/execution/class_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..94c4b5148a4db18ce506515469cc5272595f2af3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/execution/class_cache.py @@ -0,0 +1,68 @@ +import os + +import ray +from ray.air.constants import COPY_DIRECTORY_CHECKPOINTS_INSTEAD_OF_MOVING_ENV +from ray.train.constants import ( + ENABLE_V2_MIGRATION_WARNINGS_ENV_VAR, + RAY_CHDIR_TO_TRIAL_DIR, +) +from ray.train.v2._internal.constants import ( + ENV_VARS_TO_PROPAGATE as TRAIN_ENV_VARS_TO_PROPAGATE, +) + +DEFAULT_ENV_VARS = { + # https://github.com/ray-project/ray/issues/28197 + "PL_DISABLE_FORK": "1" +} +ENV_VARS_TO_PROPAGATE = ( + { + COPY_DIRECTORY_CHECKPOINTS_INSTEAD_OF_MOVING_ENV, + RAY_CHDIR_TO_TRIAL_DIR, + ENABLE_V2_MIGRATION_WARNINGS_ENV_VAR, + "AWS_ACCESS_KEY_ID", + "AWS_SECRET_ACCESS_KEY", + "AWS_SECURITY_TOKEN", + "AWS_SESSION_TOKEN", + } + # Propagate the Ray Train environment variables from the driver process + # to the trainable process so that Tune + Train v2 can be used together. + | TRAIN_ENV_VARS_TO_PROPAGATE +) + + +class _ActorClassCache: + """Caches actor classes. + + ray.remote is a registration call. It sends the serialized object to the + key value store (redis), and will be fetched at an arbitrary worker + later. Registration does not use any Ray scheduling resources. + + Later, class.remote() actually creates the remote actor. The + actor will be instantiated on some arbitrary machine, + according to the underlying Ray scheduler. + + Without this cache, you would register the same serialized object + over and over again. Naturally, since redis doesn’t spill to disk, + this can easily nuke the redis instance (and basically blow up Ray). + This cache instead allows us to register once and only once. + + Note that we assume there can be multiple trainables in the + system at once. + """ + + def __init__(self): + self._cache = {} + + def get(self, trainable_cls): + """Gets the wrapped trainable_cls, otherwise calls ray.remote.""" + env_vars = DEFAULT_ENV_VARS.copy() + + for env_var_to_propagate in ENV_VARS_TO_PROPAGATE: + if env_var_to_propagate in os.environ: + env_vars[env_var_to_propagate] = os.environ[env_var_to_propagate] + + runtime_env = {"env_vars": env_vars} + if trainable_cls not in self._cache: + remote_cls = ray.remote(runtime_env=runtime_env)(trainable_cls) + self._cache[trainable_cls] = remote_cls + return self._cache[trainable_cls] diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/cluster_info.py b/venv/lib/python3.10/site-packages/ray/tune/execution/cluster_info.py new file mode 100644 index 0000000000000000000000000000000000000000..23bb9d03dbd04a7ee8ff99ee07a1f455ef95ac9f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/execution/cluster_info.py @@ -0,0 +1,12 @@ +from functools import lru_cache +from pathlib import Path + + +@lru_cache() +def _is_ray_cluster(): + """Checks if the bootstrap config file exists. + + This will always exist if using an autoscaling cluster/started + with the ray cluster launcher. + """ + return Path("~/ray_bootstrap_config.yaml").expanduser().exists() diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/experiment_state.py b/venv/lib/python3.10/site-packages/ray/tune/execution/experiment_state.py new file mode 100644 index 0000000000000000000000000000000000000000..8afda2a3a2751b6bb6f44f4e59a6bc24c89b81d3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/execution/experiment_state.py @@ -0,0 +1,287 @@ +import fnmatch +import logging +import os +import time +from collections import Counter +from pathlib import Path +from typing import Callable, Dict, Optional, Union + +import pyarrow.fs + +from ray.train._internal.storage import ( + StorageContext, + _download_from_fs_path, + _list_at_fs_path, + get_fs_and_path, +) +from ray.tune.experiment.trial import Trial +from ray.tune.impl.out_of_band_serialize_dataset import out_of_band_serialize_dataset + +logger = logging.getLogger(__name__) + + +_SLOW_SYNC_WARNING = ( + "This could be due to a large number of trials, " + "large logfiles from lots of reported metrics, or throttling from the " + "remote storage if uploading too frequently.\n" + "You may want to consider switching the `RunConfig(storage_filesystem)`" + " to a more performant storage backend such as s3fs for a " + "S3 storage path.\n" + "You can suppress this error by setting the environment variable " + "TUNE_WARN_SLOW_EXPERIMENT_CHECKPOINT_SYNC_THRESHOLD_S to a higher " + "value than the current threshold ({threshold})." +) + + +def _find_newest_experiment_checkpoint( + experiment_path: str, fs: Optional[pyarrow.fs.FileSystem] = None +) -> Optional[str]: + """Returns file name of most recently created experiment checkpoint. + + Args: + experiment_path: Local or remote path to the experiment directory + containing at least one experiment checkpoint file. + + Returns: + str: The local or remote path to the latest experiment checkpoint file + based on timestamp. None if no experiment checkpoints were found. + """ + from ray.tune.execution.tune_controller import TuneController + + fs, experiment_fs_path = get_fs_and_path(experiment_path, storage_filesystem=fs) + filenames = _list_at_fs_path(fs=fs, fs_path=experiment_fs_path) + pattern = TuneController.CKPT_FILE_TMPL.format("*") + matching = fnmatch.filter(filenames, pattern) + if not matching: + return None + filename = max(matching) + return Path(experiment_fs_path, filename).as_posix() + + +class _ExperimentCheckpointManager: + """Helper class for managing experiment-level checkpoints. + + This class implements the ``checkpoint()`` method used to checkpoint + experiment state. When called, this will serialize and write to disk + the state of the trial runner, trial executor, and search algorithm, to + a specified checkpoint file. + + The checkpoint period is automatically adjusted to + ``max(10, time_per_checkpoint * 19)``. This means that at most 5% of the + time (1/20) will be used for writing checkpoints, while 95% of the time + (19/20) will be used to handle the rest of the training loop. + """ + + def __init__( + self, + *, + storage: Optional[StorageContext], + checkpoint_period: Union[int, float, str], + sync_every_n_trial_checkpoints: Optional[int] = None, + ): + self._storage = storage + + self._last_save_time = float("-inf") + self._last_sync_time = None + + # Dynamic checkpointing period + self._auto_checkpoint_enabled = checkpoint_period == "auto" + if self._auto_checkpoint_enabled: + self._checkpoint_period = 10.0 # Initial value + else: + self._checkpoint_period = float(checkpoint_period) + + # TODO(justinvyu): This is a non-performant workaround to force sync + # every num_to_keep checkpoints in order to maintain consistency + # between the experiment state's view of the latest checkpoint, + # and the actual latest checkpoint that was uploaded. + self._sync_every_n_trial_checkpoints = sync_every_n_trial_checkpoints + self._trial_num_checkpoints_since_last_sync: Dict[Trial, int] = Counter() + self._should_force_sync_up: bool = False + + self._excessive_sync_threshold = float( + os.environ.get( + "TUNE_WARN_EXCESSIVE_EXPERIMENT_CHECKPOINT_SYNC_THRESHOLD_S", "5" + ) + ) + self._slow_sync_threshold = float( + os.environ.get( + "TUNE_WARN_SLOW_EXPERIMENT_CHECKPOINT_SYNC_THRESHOLD_S", "30" + ) + ) + + @property + def auto_checkpoint_enabled(self): + return self._auto_checkpoint_enabled + + def _update_auto_checkpoint_time(self, time_taken: float): + if self._auto_checkpoint_enabled: + # Multiplying this time by 19 means we spend ~5% of the time + # writing global checkpoints and 95% of the time processing trials + self._checkpoint_period = max(10.0, time_taken * 19) + logger.debug( + f"Experiment state snapshotting took " + f"{time_taken:.2f} seconds. " + f"Adjusting snapshotting period to " + f"{self._checkpoint_period:.2f} seconds." + ) + + def sync_up_experiment_state( + self, + save_fn: Callable[[], None], + force: bool = False, + wait: bool = False, + ): + """Saves execution state to the experiment directory on the storage path. + This includes an experiment checkpoint file that contains trial statuses + and the searcher state. + + Overwrites the current session checkpoint, which starts when self + is instantiated. Throttle depends on self._checkpoint_period. + + Args: + save_fn: Function to call to actually save data to the driver + staging path. The files in the driver staging path will be + uploaded to the storage path. + force: Forces an experiment checkpoint and launches a sync to storage. + This happens regardless of checkpoint_period + wait: Waits for the sync up to complete before returning. + """ + driver_staging_path = self._storage.experiment_driver_staging_path + + force = force or self._should_force_sync_up + + now = time.monotonic() + if now - self._last_save_time < self._checkpoint_period and not force: + return + + # Checkpoint + checkpoint_time_start = time.monotonic() + + # NOTE: This context manager is for Datasets captured in a trial config. + # This is the case when *tuning over datasets*. + # If the datasets have already been full executed, then serializing + # block refs means that this checkpoint is not usable in a new Ray cluster. + # This context will serialize the dataset execution plan instead, if available. + with out_of_band_serialize_dataset(): + save_fn() + + def wait_for_sync(): + try: + self._storage.syncer.wait() + except Exception: + logger.error( + "Saving experiment state to storage at " + f"'{self._storage.experiment_fs_path}' failed with exception: ", + exc_info=True, + ) + + if force: + start_time = time.monotonic() + wait_for_sync() + wait_time = time.monotonic() - start_time + if wait_time > self._slow_sync_threshold: + logger.warning( + "Saving the experiment state (which holds a global view " + "of trial statuses and is used to restore the experiment) " + f"took ~{wait_time:.2f} seconds, which may be a performance " + "bottleneck.\n" + f"{_SLOW_SYNC_WARNING.format(threshold=self._slow_sync_threshold)}" + ) + + time_since_last_sync = ( + time.monotonic() - self._last_sync_time + if self._last_sync_time is not None + else None + ) + launched_sync = self._storage.syncer.sync_up( + driver_staging_path, self._storage.experiment_fs_path + ) + if launched_sync: + if ( + time_since_last_sync is not None + and time_since_last_sync < self._excessive_sync_threshold + and self._should_force_sync_up + ): + logger.warning( + "Experiment state snapshotting has been triggered multiple " + f"times in the last {self._excessive_sync_threshold} seconds " + "and may become a bottleneck. " + "A snapshot is forced if `CheckpointConfig(num_to_keep)` is set, " + "and a trial has checkpointed >= `num_to_keep` times " + "since the last snapshot.\n" + "You may want to consider increasing the " + "`CheckpointConfig(num_to_keep)` or decreasing the frequency of " + "saving checkpoints.\n" + "You can suppress this warning by setting the environment variable " + "TUNE_WARN_EXCESSIVE_EXPERIMENT_CHECKPOINT_SYNC_THRESHOLD_S " + "to a smaller value than the current threshold " + f"({self._excessive_sync_threshold}). " + "Set it to 0 to completely suppress this warning." + ) + + self._last_sync_time = time.monotonic() + + # We just synced, so reset the force flag + self._trial_num_checkpoints_since_last_sync.clear() + self._should_force_sync_up = False + else: + if ( + time_since_last_sync is not None + and time_since_last_sync > self._slow_sync_threshold + ): + logger.warning( + "Saving the experiment state (which holds a global view " + "of trial statuses and is used to restore the experiment) " + f"has already taken {time_since_last_sync:.2f} seconds, " + "which may cause consistency issues upon restoration if your " + "driver script ungracefully exits.\n" + f"{_SLOW_SYNC_WARNING.format(threshold=self._slow_sync_threshold)}" + ) + + if wait: + wait_for_sync() + + checkpoint_time_taken = time.monotonic() - checkpoint_time_start + + # Adjust dynamic checkpointing + self._update_auto_checkpoint_time(time_taken=checkpoint_time_taken) + + # Finish + self._last_save_time = time.monotonic() + + def sync_down_experiment_state(self) -> None: + fs = self._storage.storage_filesystem + filepaths = _list_at_fs_path(fs=fs, fs_path=self._storage.experiment_fs_path) + # TODO(ekl) we should refactor our restore code to read the necessary data + # directly from the storage context. As a temporary hack, restore all the + # serialized files from the root dir where other modules expect them to be. + matches = [ + path + for path in filepaths + if path.endswith(".json") or path.endswith(".pkl") + ] + for relpath in matches: + fs_path = Path(self._storage.experiment_fs_path, relpath).as_posix() + local_path = Path( + self._storage.experiment_driver_staging_path, relpath + ).as_posix() + _download_from_fs_path(fs=fs, fs_path=fs_path, local_path=local_path) + logger.debug( + f"Copied {matches} from:\n(fs, path) = " + f"({self._storage.storage_filesystem.type_name}, " + f"{self._storage.experiment_fs_path})\n" + f"-> {self._storage.experiment_driver_staging_path}" + ) + + def on_trial_checkpoint(self, trial: Trial): + if not self._sync_every_n_trial_checkpoints: + return + + self._trial_num_checkpoints_since_last_sync[trial] += 1 + + if ( + self._trial_num_checkpoints_since_last_sync[trial] + >= self._sync_every_n_trial_checkpoints + ): + self._should_force_sync_up = True diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/insufficient_resources_manager.py b/venv/lib/python3.10/site-packages/ray/tune/execution/insufficient_resources_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..0f788d2df7df64c3f34c12fef8b39d68ec758e66 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/execution/insufficient_resources_manager.py @@ -0,0 +1,167 @@ +import logging +import os +import time +from functools import lru_cache +from typing import Dict, Optional, Tuple + +import ray +from ray.tune.execution.cluster_info import _is_ray_cluster +from ray.tune.experiment import Trial + +logger = logging.getLogger(__name__) + + +# Ideally we want to use @cache; but it's only available for python 3.9. +# Caching is only helpful/correct for no autoscaler case. +@lru_cache() +def _get_cluster_resources_no_autoscaler() -> Dict: + return ray.cluster_resources() + + +def _get_trial_cpu_and_gpu(trial: Trial) -> Tuple[int, int]: + cpu = trial.placement_group_factory.required_resources.get("CPU", 0) + gpu = trial.placement_group_factory.required_resources.get("GPU", 0) + return cpu, gpu + + +def _can_fulfill_no_autoscaler(trial: Trial) -> bool: + """Calculates if there is enough resources for a PENDING trial. + + For no autoscaler case. + """ + assert trial.status == Trial.PENDING + asked_cpus, asked_gpus = _get_trial_cpu_and_gpu(trial) + + return asked_cpus <= _get_cluster_resources_no_autoscaler().get( + "CPU", 0 + ) and asked_gpus <= _get_cluster_resources_no_autoscaler().get("GPU", 0) + + +@lru_cache() +def _get_insufficient_resources_warning_threshold() -> float: + if _is_ray_cluster(): + return float( + os.environ.get( + "TUNE_WARN_INSUFFICENT_RESOURCE_THRESHOLD_S_AUTOSCALER", "60" + ) + ) + else: + # Set the default to 10s so that we don't prematurely determine that + # a cluster cannot fulfill the resources requirements. + # TODO(xwjiang): Change it back once #18608 is resolved. + return float(os.environ.get("TUNE_WARN_INSUFFICENT_RESOURCE_THRESHOLD_S", "60")) + + +MSG_TRAIN_START = ( + "Training has not started in the last {wait_time:.0f} seconds. " + "This could be due to the cluster not having enough resources available. " +) +MSG_TRAIN_INSUFFICIENT = ( + "You asked for {asked_cpus} CPUs and {asked_gpus} GPUs, but the cluster only " + "has {cluster_cpus} CPUs and {cluster_gpus} GPUs available. " +) +MSG_TRAIN_END = ( + "Stop the training and adjust the required resources (e.g. via the " + "`ScalingConfig` or `resources_per_trial`, or `num_workers` for rllib), " + "or add more resources to your cluster." +) + +MSG_TUNE_START = ( + "No trial is running and no new trial has been started within " + "the last {wait_time:.0f} seconds. " + "This could be due to the cluster not having enough resources available. " +) +MSG_TUNE_INSUFFICIENT = ( + "You asked for {asked_cpus} CPUs and {asked_gpus} GPUs per trial, " + "but the cluster only has {cluster_cpus} CPUs and {cluster_gpus} GPUs available. " +) +MSG_TUNE_END = ( + "Stop the tuning and adjust the required resources (e.g. via the " + "`ScalingConfig` or `resources_per_trial`, or `num_workers` for rllib), " + "or add more resources to your cluster." +) + + +# TODO(xwjiang): Consider having a help page with more detailed instructions. +@lru_cache() +def _get_insufficient_resources_warning_msg( + for_train: bool = False, trial: Optional[Trial] = None +) -> str: + msg = "Ignore this message if the cluster is autoscaling. " + + if for_train: + start = MSG_TRAIN_START + insufficient = MSG_TRAIN_INSUFFICIENT + end = MSG_TRAIN_END + else: + start = MSG_TUNE_START + insufficient = MSG_TUNE_INSUFFICIENT + end = MSG_TUNE_END + + msg += start.format(wait_time=_get_insufficient_resources_warning_threshold()) + + if trial: + asked_cpus, asked_gpus = _get_trial_cpu_and_gpu(trial) + cluster_resources = _get_cluster_resources_no_autoscaler() + + msg += insufficient.format( + asked_cpus=asked_cpus, + asked_gpus=asked_gpus, + cluster_cpus=cluster_resources.get("CPU", 0), + cluster_gpus=cluster_resources.get("GPU", 0), + ) + + msg += end + + return msg + + +class _InsufficientResourcesManager: + """Insufficient resources manager. + + Makes best effort, conservative guesses about if Tune loop is stuck due to + infeasible resources. If so, outputs usability messages for users to + act upon. + """ + + def __init__(self, for_train: bool = False): + # The information tracked across the life time of Tune loop. + self._no_running_trials_since = -1 + self._last_trial_num = -1 + self._for_train = for_train + + def on_no_available_trials(self, all_trials): + """Tracks information across the life of Tune loop and makes guesses + about if Tune loop is stuck due to infeasible resources. + If so, outputs certain warning messages. + The logic should be conservative, non-intrusive and informative. + For example, rate limiting is applied so that the message is not + spammy. + """ + # This is approximately saying we are not making progress. + if len(all_trials) == self._last_trial_num: + if self._no_running_trials_since == -1: + self._no_running_trials_since = time.monotonic() + elif ( + time.monotonic() - self._no_running_trials_since + > _get_insufficient_resources_warning_threshold() + ): + can_fulfill_any = any( + trial.status == Trial.PENDING and _can_fulfill_no_autoscaler(trial) + for trial in all_trials + ) + + if can_fulfill_any: + # If one trial can be fulfilled, it will be fulfilled eventually + self._no_running_trials_since = -1 + return + + # Otherwise, can fulfill none + msg = _get_insufficient_resources_warning_msg( + for_train=self._for_train, trial=all_trials[0] + ) + logger.warning(msg) + self._no_running_trials_since = time.monotonic() + else: + self._no_running_trials_since = -1 + self._last_trial_num = len(all_trials) diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/placement_groups.py b/venv/lib/python3.10/site-packages/ray/tune/execution/placement_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..a2eaf548fd35af7ffa9df7a78b224987e5b19e15 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/execution/placement_groups.py @@ -0,0 +1,131 @@ +import warnings +from typing import Dict, Optional + +from ray.air.execution.resources.request import ResourceRequest +from ray.util.annotations import DeveloperAPI, PublicAPI +from ray.util.placement_group import placement_group + + +@PublicAPI(stability="beta") +class PlacementGroupFactory(ResourceRequest): + """Wrapper class that creates placement groups for trials. + + This function should be used to define resource requests for Ray Tune + trials. It holds the parameters to create + :ref:`placement groups `. + At a minimum, this will hold at least one bundle specifying the + resource requirements for each trial: + + .. code-block:: python + + from ray import tune + + tuner = tune.Tuner( + tune.with_resources( + train, + resources=tune.PlacementGroupFactory([ + {"CPU": 1, "GPU": 0.5, "custom_resource": 2} + ]) + ) + ) + tuner.fit() + + If the trial itself schedules further remote workers, the resource + requirements should be specified in additional bundles. You can also + pass the placement strategy for these bundles, e.g. to enforce + co-located placement: + + .. code-block:: python + + from ray import tune + + tuner = tune.Tuner( + tune.with_resources( + train, + resources=tune.PlacementGroupFactory([ + {"CPU": 1, "GPU": 0.5, "custom_resource": 2}, + {"CPU": 2}, + {"CPU": 2}, + ], strategy="PACK") + ) + ) + tuner.fit() + + The example above will reserve 1 CPU, 0.5 GPUs and 2 custom_resources + for the trainable itself, and reserve another 2 bundles of 2 CPUs each. + The trial will only start when all these resources are available. This + could be used e.g. if you had one learner running in the main trainable + that schedules two remote workers that need access to 2 CPUs each. + + If the trainable itself doesn't require resources. + You can specify it as: + + .. code-block:: python + + from ray import tune + + tuner = tune.Tuner( + tune.with_resources( + train, + resources=tune.PlacementGroupFactory([ + {}, + {"CPU": 2}, + {"CPU": 2}, + ], strategy="PACK") + ) + ) + tuner.fit() + + Args: + bundles: A list of bundles which + represent the resources requirements. + strategy: The strategy to create the placement group. + + - "PACK": Packs Bundles into as few nodes as possible. + - "SPREAD": Places Bundles across distinct nodes as even as possible. + - "STRICT_PACK": Packs Bundles into one node. The group is + not allowed to span multiple nodes. + - "STRICT_SPREAD": Packs Bundles across distinct nodes. + *args: Passed to the call of ``placement_group()`` + **kwargs: Passed to the call of ``placement_group()`` + + """ + + def __call__(self, *args, **kwargs): + warnings.warn( + "Calling PlacementGroupFactory objects is deprecated. Use " + "`to_placement_group()` instead.", + DeprecationWarning, + ) + kwargs.update(self._bound.kwargs) + # Call with bounded *args and **kwargs + return placement_group(*self._bound.args, **kwargs) + + +@DeveloperAPI +def resource_dict_to_pg_factory(spec: Optional[Dict[str, float]] = None): + """Translates resource dict into PlacementGroupFactory.""" + spec = spec or {"cpu": 1} + + spec = spec.copy() + + cpus = spec.pop("cpu", spec.pop("CPU", 0.0)) + gpus = spec.pop("gpu", spec.pop("GPU", 0.0)) + memory = spec.pop("memory", 0.0) + + # If there is a custom_resources key, use as base for bundle + bundle = dict(spec.pop("custom_resources", {})) + + # Otherwise, consider all other keys as custom resources + if not bundle: + bundle = spec + + bundle.update( + { + "CPU": cpus, + "GPU": gpus, + "memory": memory, + } + ) + + return PlacementGroupFactory([bundle]) diff --git a/venv/lib/python3.10/site-packages/ray/tune/execution/tune_controller.py b/venv/lib/python3.10/site-packages/ray/tune/execution/tune_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..ea513eaf4c59a965b3b9faaa79faf42463d1fc43 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/execution/tune_controller.py @@ -0,0 +1,2181 @@ +import copy +import json +import logging +import os +import time +import traceback +import warnings +from collections import defaultdict, deque +from datetime import datetime +from functools import partial +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union + +import ray +from ray.air import ResourceRequest +from ray.air.constants import TIME_THIS_ITER_S +from ray.air.execution import PlacementGroupResourceManager, ResourceManager +from ray.air.execution._internal import RayActorManager, TrackedActor +from ray.exceptions import RayActorError, RayTaskError +from ray.train._internal.session import _FutureTrainingResult, _TrainingResult +from ray.train._internal.storage import StorageContext +from ray.tune import CheckpointConfig +from ray.tune.callback import Callback, CallbackList +from ray.tune.error import TuneError, _AbortTrialExecution, _TuneStopTrialError +from ray.tune.execution.class_cache import _ActorClassCache +from ray.tune.execution.experiment_state import ( + _ExperimentCheckpointManager, + _find_newest_experiment_checkpoint, +) +from ray.tune.execution.insufficient_resources_manager import ( + _InsufficientResourcesManager, +) +from ray.tune.execution.placement_groups import PlacementGroupFactory +from ray.tune.experiment import Experiment, Trial +from ray.tune.experiment.trial import ( + _change_working_directory, + _get_trainable_kwargs, + _Location, + _noop_logger_creator, + _TrialInfo, +) +from ray.tune.result import ( + DEBUG_METRICS, + DEFAULT_METRIC, + DONE, + RESULT_DUPLICATE, + SHOULD_CHECKPOINT, + STDERR_FILE, + STDOUT_FILE, + TRIAL_INFO, +) +from ray.tune.schedulers import FIFOScheduler, TrialScheduler +from ray.tune.search import BasicVariantGenerator, SearchAlgorithm +from ray.tune.stopper import NoopStopper, Stopper +from ray.tune.tune_config import ResumeConfig +from ray.tune.utils import flatten_dict, warn_if_slow +from ray.tune.utils.log import Verbosity, _dedup_logs, has_verbosity +from ray.tune.utils.object_cache import _ObjectCache +from ray.tune.utils.resource_updater import _ResourceUpdater +from ray.tune.utils.serialization import TuneFunctionDecoder, TuneFunctionEncoder +from ray.util.annotations import DeveloperAPI +from ray.util.debug import log_once + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class TuneController: + CKPT_FILE_TMPL = "experiment_state-{}.json" + RAISE = "RAISE" + + def __init__( + self, + *, + search_alg: Optional[SearchAlgorithm] = None, + placeholder_resolvers: Optional[Dict[Tuple, Any]] = None, + scheduler: Optional[TrialScheduler] = None, + stopper: Optional[Stopper] = None, + resume_config: Optional[ResumeConfig] = None, + fail_fast: bool = False, + checkpoint_period: Union[str, int] = None, + callbacks: Optional[List[Callback]] = None, + metric: Optional[str] = None, + trial_checkpoint_config: Optional[CheckpointConfig] = None, + storage: Optional[StorageContext] = None, + reuse_actors: bool = False, + resource_manager_factory: Optional[Callable[[], ResourceManager]] = None, + _trainer_api: bool = False, + ): + if resource_manager_factory: + resource_manager = resource_manager_factory() + else: + resource_manager = PlacementGroupResourceManager() + + self._actor_manager = RayActorManager(resource_manager=resource_manager) + + self._class_cache = _ActorClassCache() + + # Resource status + self._resource_updater = _ResourceUpdater(None) + + # Actor <-> Trial mappings + self._actor_to_trial: Dict[TrackedActor, Trial] = {} + self._trial_to_actor: Dict[Trial, TrackedActor] = {} + + # Resources <-> Trial + self._resources_to_pending_trials: Dict[ + ResourceRequest, Set[Trial] + ] = defaultdict(set) + + # Keep track of actor states + self._pending_trials: Set[Trial] = set() + self._pending_trials_list: List[Trial] = [] + + self._running_trials: Set[Trial] = set() + + self._paused_trials: Set[Trial] = set() + + self._stopped_trials: Set[Trial] = set() + self._failed_trials: Set[Trial] = set() + + self._resetting_trials: Set[Trial] = set() + self._staged_trials: Set[Trial] = set() + + # Removed actors + self._started_actors: Set[TrackedActor] = set() + + # Map of tracked actors -> timestamp + # The timestamp is when we requested the stop. + # We track these actors here to force a + # cleanup after some time (as they might be hanging). + # Todo: This timeout logic should be moved into the actor manager. + # This map is populated whenever we request an actor stop: + # - Regular STOP decision + # - Removing an actor because its trial REUSEs a different trial's actor + # - Removing a cached actor because it's not needed anymore + # Actors are only tracked in this map if they actually started (not if they + # were only requested but never started). + # Actors are removed from this map: + # - When the STOP resolved and the actor actually stopped + # - When they are forcefully cleaned up after the timeout. + self._stopping_actors: Dict[TrackedActor, float] = {} + self._earliest_stopping_actor: float = float("inf") + self._actor_cleanup_timeout: int = int( + os.environ.get("TUNE_FORCE_TRIAL_CLEANUP_S", "600") + ) + self._actor_force_cleanup_timeout: int = 10 + + # Reuse actors + self._reuse_actors = reuse_actors + self._actor_cache = _ObjectCache(may_keep_one=True) + + # Trial metadata for experiment checkpoints + self._trials_to_cache: Set[Trial] = set() + self._trial_metadata: Dict[str, str] = {} + + # TRAINING + self._buffer_length = int(os.getenv("TUNE_RESULT_BUFFER_LENGTH", 1)) + self._buffer_min_time_s = float(os.getenv("TUNE_RESULT_BUFFER_MIN_TIME_S", 0.0)) + self._buffer_max_time_s = float( + os.getenv("TUNE_RESULT_BUFFER_MAX_TIME_S", 100.0) + ) + + # Legacy TrialRunner init + self._search_alg = search_alg or BasicVariantGenerator() + self._placeholder_resolvers = placeholder_resolvers + self._scheduler_alg = scheduler or FIFOScheduler() + self._callbacks = CallbackList(callbacks or []) + self._insufficient_resources_manager = _InsufficientResourcesManager( + for_train=_trainer_api + ) + self._pending_trial_queue_times = {} + + self._max_pending_trials = _get_max_pending_trials(self._search_alg) + + self._storage = storage + self._metric = metric + + self._total_time = 0 + self._iteration = 0 + self._has_errored = False + self._fail_fast = fail_fast + if isinstance(self._fail_fast, str): + self._fail_fast = self._fail_fast.upper() + if self._fail_fast == self.RAISE: + warnings.warn( + "fail_fast='raise' detected. Be careful when using this " + "mode as resources (such as Ray processes, " + "file descriptors, and temporary files) may not be " + "cleaned up properly. To use " + "a safer mode, use fail_fast=True." + ) + else: + raise ValueError( + "fail_fast must be one of {bool, RAISE}. " f"Got {self._fail_fast}." + ) + + self._print_trial_errors = bool( + int(os.environ.get("TUNE_PRINT_ALL_TRIAL_ERRORS", "1")) + ) + + self._trials: List[Trial] = [] + self._live_trials: Set[Trial] = set() # Set of non-terminated trials + self._cached_trial_decisions = {} + self._queued_trial_decisions = {} + + self._stop_queue = [] + self._should_stop_experiment = False # used by TuneServer + + self._stopper = stopper or NoopStopper() + + self._start_time = time.time() + + self._session_str = datetime.fromtimestamp(self._start_time).strftime( + "%Y-%m-%d_%H-%M-%S" + ) + + if checkpoint_period is None: + checkpoint_period = os.getenv("TUNE_GLOBAL_CHECKPOINT_S", "auto") + + self._checkpoint_period = checkpoint_period + self._trial_checkpoint_config = trial_checkpoint_config or CheckpointConfig() + self._checkpoint_manager = self._create_checkpoint_manager() + + self._resumed = False + + if resume_config is not None: + # Use the metadata file to restore TuneController state + try: + self.resume(resume_config=resume_config) + self._resumed = True + except Exception as e: + if has_verbosity(Verbosity.V3_TRIAL_DETAILS): + logger.error(str(e)) + logger.exception("Failed to restore the run state.") + if self._fail_fast: + raise + logger.info("Restarting experiment.") + else: + logger.debug("Starting a new experiment.") + + def _wrapped(self): + """Return wrapped tune controller to be passed to scheduler/searchers.""" + return TrialRunnerWrapper( + self, + trial_executor=_FakeRayTrialExecutor(self), + runner_whitelist_attr={ + "search_alg", + "get_trials", + "get_live_trials", + "_set_trial_status", + "pause_trial", + "stop_trial", + "_schedule_trial_save", + }, + executor_whitelist_attr={ + "has_resources_for_trial", + "pause_trial", + "save", + "_resource_updater", + }, + ) + + @property + def resumed(self): + return self._resumed + + @property + def search_alg(self): + return self._search_alg + + @property + def scheduler_alg(self): + return self._scheduler_alg + + def setup_experiments( + self, experiments: List[Experiment], total_num_samples: int + ) -> None: + """Obtains any necessary information from experiments. + + Mainly used to setup callbacks. + + Args: + experiments: List of Experiments + to use. + total_num_samples: Total number of samples + factoring in grid search samplers. + """ + experiment = experiments[0] + spec = experiment.public_spec if experiment else {} + spec["total_num_samples"] = total_num_samples + self._callbacks.setup(**spec) + + def end_experiment_callbacks(self) -> None: + """Calls ``on_experiment_end`` method in callbacks.""" + self._callbacks.on_experiment_end(trials=self._trials) + + @property + def experiment_state_file_name(self) -> str: + return self.CKPT_FILE_TMPL.format(self._session_str) + + @property + def experiment_state_path(self) -> str: + """Returns the local experiment checkpoint path.""" + return Path( + self._storage.experiment_driver_staging_path, + self.experiment_state_file_name, + ).as_posix() + + @property + def experiment_path(self) -> str: + return self._storage.experiment_fs_path + + def _create_checkpoint_manager(self): + return _ExperimentCheckpointManager( + storage=self._storage, + checkpoint_period=self._checkpoint_period, + sync_every_n_trial_checkpoints=self._trial_checkpoint_config.num_to_keep, + ) + + def save_to_dir(self): + """Save TuneController state to the local staging experiment directory. + + This includes: + - trial states + - TuneController internal state (all the serializable attributes) + - the searcher state + - the callback states + """ + # Get state from trial executor and runner + runner_state = { + # Trials + "trial_data": list(self._get_trial_checkpoints().values()), + # Experiment data + "runner_data": self.__getstate__(), + # Metadata + "stats": {"start_time": self._start_time}, + } + + driver_staging_path = self._storage.experiment_driver_staging_path + os.makedirs(driver_staging_path, exist_ok=True) + with open( + Path(driver_staging_path, self.experiment_state_file_name), + "w", + ) as f: + json.dump(runner_state, f, cls=TuneFunctionEncoder) + + self._search_alg.save_to_dir(driver_staging_path, session_str=self._session_str) + self._callbacks.save_to_dir(driver_staging_path, session_str=self._session_str) + + def checkpoint(self, force: bool = False, wait: bool = False): + self._checkpoint_manager.sync_up_experiment_state( + save_fn=self.save_to_dir, force=force, wait=wait + ) + + def _requeue_restored_trials( + self, trials: List[Trial], resume_config: ResumeConfig + ): + # Set trial statuses according to the resume configuration + for trial in sorted( + trials, key=lambda t: t.run_metadata.last_result_time, reverse=True + ): + if trial.status == Trial.ERROR: + resume_type = resume_config.errored + elif trial.status == Trial.TERMINATED: + resume_type = resume_config.finished + else: # Unfinished (PENDING, RUNNING, PAUSED) + resume_type = resume_config.unfinished + + trial_to_add = None + if resume_type == ResumeConfig.ResumeType.RESUME: + # Keep trial ID on resume + trial_to_add = trial + trial_to_add.run_metadata.error_filename = None + trial_to_add.run_metadata.pickled_error_filename = None + trial_to_add.set_status(Trial.PENDING) + elif resume_type == ResumeConfig.ResumeType.RESTART: + trial_to_add = trial.reset() + trial_to_add.restore_path = None + elif resume_type == ResumeConfig.ResumeType.SKIP: + trial_to_add = trial + if trial_to_add.status != Trial.ERROR: + # Set the status to terminated to skip it. + # Keep errored trial status as ERROR. + trial_to_add.set_status(Trial.TERMINATED) + else: + raise ValueError(f"Unknown resume type: {resume_type}") + assert trial_to_add is not None + + self.add_trial(trial_to_add) + + def _restore_trials(self, experiment_state: Dict) -> List[Trial]: + trials = [] + for trial_json_state, trial_runtime_metadata in experiment_state["trial_data"]: + trial = Trial.from_json_state(trial_json_state) + trial.restore_run_metadata(trial_runtime_metadata) + + # The following properties may be updated on restoration + # Ex: moved local/cloud experiment directory + + # Propagate updated storage ctx properties to the trial's restored copy. + new_storage = copy.copy(trial.storage) + new_storage.storage_filesystem = self._storage.storage_filesystem + new_storage.storage_fs_path = self._storage.storage_fs_path + new_storage.experiment_dir_name = self._storage.experiment_dir_name + + # ATTN: `trial.set_storage` is used intentionally, since it + # also updates the absolute paths and filesystem of tracked checkpoints. + trial.set_storage(new_storage) + + # Avoid creating logdir in client mode for returned trial results, + # since the dir might not be creatable locally. + # TODO(ekl) this is kind of a hack. + if not ray.util.client.ray.is_connected(): + trial.init_local_path() # Create logdir if it does not exist + + trials.append(trial) + + # NOTE: The restored run should reuse the same driver staging directory. + self._storage._timestamp = trials[0].storage._timestamp + + return trials + + def resume(self, resume_config: ResumeConfig): + """Resumes all checkpointed trials from previous run. + + Requires user to manually re-register their objects. Also stops + all ongoing trials. + """ + # 1. Restore TuneController state + # Find newest state file + newest_state_path = _find_newest_experiment_checkpoint( + self._storage.experiment_fs_path, fs=self._storage.storage_filesystem + ) + + if newest_state_path is None: + raise ValueError( + f"Tried to resume experiment from directory " + f"'{self._storage.experiment_fs_path}', but no " + f"experiment state file of the form '{TuneController.CKPT_FILE_TMPL}' " + "was found. This is expected if you are launching a new experiment." + ) + + logger.info( + "Restoring the run from the latest experiment state file: " + f"{Path(newest_state_path).name}" + ) + with self._storage.storage_filesystem.open_input_stream(newest_state_path) as f: + experiment_state = json.loads(f.readall(), cls=TuneFunctionDecoder) + + self.__setstate__(experiment_state["runner_data"]) + + # 2. Get the trial states that the run left off at. + trials = self._restore_trials(experiment_state) + + # 3. Restore search algorithm and callback state + # Download the search algorithm and callback state to the driver staging dir. + self._checkpoint_manager.sync_down_experiment_state() + + driver_staging_dir = self._storage.experiment_driver_staging_path + if self._search_alg.has_checkpoint(driver_staging_dir): + self._search_alg.restore_from_dir(driver_staging_dir) + + if self._callbacks.can_restore(driver_staging_dir): + self._callbacks.restore_from_dir(driver_staging_dir) + + # 4. Re-queue trials as needed, depending on their status. + self._requeue_restored_trials(trials, resume_config) + + def update_max_pending_trials(self, max_pending_trials: Optional[int] = None): + self._max_pending_trials = max_pending_trials or _get_max_pending_trials( + self._search_alg + ) + + def update_pending_trial_resources( + self, resources: Union[dict, PlacementGroupFactory] + ): + """Update trial resources when resuming from checkpoint. + + Only updating the pending ones. + """ + assert resources + if isinstance(resources, dict) and "gpu" not in resources: + resources["gpu"] = 0 + for trial in self._trials: + if trial.status == Trial.PENDING: + trial.update_resources(resources=resources) + + def is_finished(self): + """Returns whether all trials have finished running.""" + # The checks here are partly redundant but optimized for quick + # evaluation. Specifically, if there are live trials, we check + # these live trials first. Only if none of the live trials is + # live anymore do we loop over all trials for a final check. + trials_done = ( + len(self._live_trials) == 0 + or all(trial.is_finished() for trial in self._live_trials) + ) and all(trial.is_finished() for trial in self._trials) + return trials_done and self._search_alg.is_finished() + + def get_trial(self, tid): + trial = [t for t in self._trials if t.trial_id == tid] + return trial[0] if trial else None + + def get_trials(self): + """Returns the list of trials managed by this TrialRunner. + + Note that the caller usually should not mutate trial state directly. + """ + return self._trials + + def get_live_trials(self): + """Returns the set of trials that are not in Trial.TERMINATED state.""" + return self._live_trials + + def add_trial(self, trial: Trial): + """Adds a new trial to this TrialRunner. + + Trials may be added at any time. + + Args: + trial: Trial to queue. + """ + # If the config map has had all the references replaced with placeholders, + # resolve them before adding the trial. + if self._placeholder_resolvers: + trial.resolve_config_placeholders(self._placeholder_resolvers) + + # With trial.config resolved, create placement group factory if needed. + trial.create_placement_group_factory() + + self._trials.append(trial) + if trial.status != Trial.TERMINATED: + self._live_trials.add(trial) + with warn_if_slow("scheduler.on_trial_add"): + self._scheduler_alg.on_trial_add(self._wrapped(), trial) + self._mark_trial_to_checkpoint(trial) + + logger.debug(f"Adding trial {trial} with status {trial.status}") + + status_str_map = { + Trial.PENDING: self._pending_trials, + Trial.RUNNING: self._running_trials, + Trial.PAUSED: self._paused_trials, + Trial.TERMINATED: self._stopped_trials, + Trial.ERROR: self._failed_trials, + } + + status_str_map[trial.status].add(trial) + + if trial.status == Trial.PENDING: + self._pending_trials_list.append(trial) + self._resources_to_pending_trials[trial.placement_group_factory].add(trial) + + def _update_trial_queue(self, blocking: bool = False, timeout: int = 600) -> bool: + """Adds next trials to queue if possible. + + Note that the timeout is currently unexposed to the user. + + Args: + blocking: Blocks until either a trial is available + or is_finished (timeout or search algorithm finishes). + timeout: Seconds before blocking times out. + + Returns: + Boolean indicating if a new trial was created or not. + """ + trial = self._search_alg.next_trial() + if blocking and not trial: + start = time.time() + # Checking `is_finished` instead of _search_alg.is_finished + # is fine because blocking only occurs if all trials are + # finished and search_algorithm is not yet finished + while ( + not trial and not self.is_finished() and time.time() - start < timeout + ): + logger.debug("Blocking for next trial...") + trial = self._search_alg.next_trial() + time.sleep(1) + + if trial: + self.add_trial(trial) + return True + + return False + + def _used_resources_string(self) -> str: + allocated_resources = self._actor_manager.get_live_actors_resources() + + return self._resource_updater.debug_string(allocated_resources) + + def on_step_begin(self): + self._resource_updater.update_avail_resources() + + def on_step_end(self): + self._cleanup_cached_actors(force_all=False) + self._cleanup_stopping_actors(force_all=False) + + def _cleanup_cached_actors(self, force_all: bool = False): + if ( + self._search_alg.is_finished() + and not self._staged_trials + and self._actor_cache.total_max_objects == 0 + ): + # If there are no more trials coming in, no trials are pending execution, + # and we don't explicitly want to cache objects, we can evict the full + # cache. + force_all = True + + for tracked_actor in self._actor_cache.flush_cached_objects( + force_all=force_all + ): + logger.debug(f"Cleaning up cached actor: {tracked_actor}") + # Unset termination callbacks as no trial is associated + tracked_actor.set_on_stop(None) + tracked_actor.set_on_error(None) + self._remove_actor(tracked_actor=tracked_actor) + + def _cleanup_stopping_actors(self, force_all: bool = False): + now = time.monotonic() + + if ( + not force_all + and now - self._earliest_stopping_actor <= self._actor_cleanup_timeout + ): + # If the earliest actor to timeout has not reached the timeout, return + return + + # This is a bit costly, so we want to avoid running it too often + times = deque( + sorted( + [ + (timestamp, tracked_actor) + for tracked_actor, timestamp in self._stopping_actors.items() + ], + key=lambda item: item[0], + ) + ) + + while times and ( + force_all or time.monotonic() - times[0][0] > self._actor_cleanup_timeout + ): + if ( + time.monotonic() - times[0][0] < self._actor_force_cleanup_timeout + ) and self._actor_manager.is_actor_started(tracked_actor=times[0][1]): + # Even if force_all=True, we give the actors time to clean up + self._actor_manager.next(timeout=1) + continue + + _, tracked_actor = times.popleft() + + if tracked_actor not in self._stopping_actors: + # Actor stopping has been handled by the block above + continue + + if self._actor_manager.is_actor_started(tracked_actor=tracked_actor): + logger.debug(f"Forcefully killing actor: {tracked_actor}") + self._actor_manager.remove_actor(tracked_actor=tracked_actor, kill=True) + self._stopping_actors.pop(tracked_actor) + + if times: + self._earliest_stopping_actor = times[0][0] + else: + self._earliest_stopping_actor = float("inf") + + def step(self): + if self.is_finished(): + raise TuneError("Called step when all trials finished?") + + with warn_if_slow("on_step_begin"): + self.on_step_begin() + + with warn_if_slow("callbacks.on_step_begin"): + self._callbacks.on_step_begin( + iteration=self._iteration, trials=self._trials + ) + + # Ask searcher for more trials + self._maybe_update_trial_queue() + + # Start actors for added trials + self._maybe_add_actors() + + # Handle one event + if not self._actor_manager.next(timeout=0.1): + # If there are no actors running, warn about potentially + # insufficient resources + if not self._actor_manager.num_live_actors: + self._insufficient_resources_manager.on_no_available_trials( + self.get_trials() + ) + + # Maybe stop whole experiment + self._stop_experiment_if_needed() + + # Maybe save experiment state + try: + self.checkpoint() + except Exception as e: + logger.warning(f"Trial controller checkpointing failed: {str(e)}") + raise e + + self._iteration += 1 + + with warn_if_slow("on_step_end"): + self.on_step_end() + with warn_if_slow("callbacks.on_step_end"): + self._callbacks.on_step_end(iteration=self._iteration, trials=self._trials) + + def _set_trial_status(self, trial: Trial, status: str): + """Set trial to a specific status. + + This will keep track of trials with specific statuses in sets. + + For PENDING and PAUSED trials we also keep a list of trials to be able + to retain FIFO ordering. See ``_maybe_add_actors`` for details. + + Lastly we also keep a mapping from resources to pending/paused trials + to be able to efficiently start trials for cached actors. + """ + current_status = trial.status + + if current_status == status: + logger.debug(f"Trial {trial} already has status {status}. Skipping update.") + return + + status_str_map = { + Trial.PENDING: self._pending_trials, + Trial.RUNNING: self._running_trials, + Trial.PAUSED: self._paused_trials, + Trial.TERMINATED: self._stopped_trials, + Trial.ERROR: self._failed_trials, + } + + logger.debug( + f"Setting status for trial {trial} from {current_status} to {status}" + ) + + assert trial in status_str_map[current_status], (trial, current_status) + assert trial not in status_str_map[status], (trial, status) + + status_str_map[current_status].remove(trial) + status_str_map[status].add(trial) + + # We keep a log for pending trials for FIFO scheduling. + # We do not need to remove from this list as we will just discard + # items that are in this list but not in the respective set. + if status == Trial.PENDING: + self._pending_trials_list.append(trial) + self._resources_to_pending_trials[trial.placement_group_factory].add(trial) + else: + self._resources_to_pending_trials[trial.placement_group_factory].discard( + trial + ) + + trial.set_status(status) + + def _get_trial_checkpoints(self) -> Dict[str, str]: + for trial in self._trials_to_cache: + self._trial_metadata[trial.trial_id] = trial.get_json_state() + self._trials_to_cache.clear() + return self._trial_metadata + + def _mark_trial_to_checkpoint(self, trial: Trial): + self._trials_to_cache.add(trial) + + ### + # UPDATE TRIALS + def _maybe_update_trial_queue(self): + """Ask the searcher for more trials.""" + if self._search_alg.is_finished(): + return + + dont_wait_for_trial = ( + self._pending_trials or self._running_trials or self._paused_trials + ) + + while len(self._pending_trials) < self._max_pending_trials: + if not self._update_trial_queue(blocking=not dont_wait_for_trial): + break + dont_wait_for_trial = True + + def _cleanup_trials(self): + logger.debug("CLEANING UP all trials") + + for tracked_actor in list(self._actor_to_trial): + trial = self._actor_to_trial[tracked_actor] + logger.debug( + f"Scheduling trial stop at end of experiment (trial {trial}): " + f"{tracked_actor}" + ) + self._schedule_trial_stop(trial) + + # Clean up cached actors now + self._cleanup_cached_actors(force_all=True) + + start = time.monotonic() + while time.monotonic() - start < 5 and self._actor_manager.num_total_actors: + if _dedup_logs("actor_manager_cleanup", str(start)): + logger.debug( + "Waiting for actor manager to clean up final state [dedup]" + ) + self._actor_manager.next(timeout=1) + + logger.debug("Force cleanup of remaining actors") + self._cleanup_stopping_actors(force_all=True) + + self._actor_manager.cleanup() + + def _remove_actor(self, tracked_actor: TrackedActor): + stop_future = self._actor_manager.schedule_actor_task( + tracked_actor, "stop", _return_future=True + ) + now = time.monotonic() + + if self._actor_manager.remove_actor( + tracked_actor, kill=False, stop_future=stop_future + ): + # If the actor was previously alive, track + self._stopping_actors[tracked_actor] = now + self._earliest_stopping_actor = min(self._earliest_stopping_actor, now) + + ### + # ADD ACTORS + def _maybe_add_actors(self) -> None: + """Add actors for pending and paused trials. + + For actors that have not been staged, yet, we request an actor. + + For actors that have been staged, already, we try to reuse a cached actor. + + First, we handle the trial that the scheduler chooses to run. + + Then, we handle all trials that are pending. + + Lastly, we see if we have cached actors that we can assign to a pending or + paused trial. This can be the case when a trial has not been staged, yet, + for instance because the number of staging trials was too large. + """ + + ### + # 1: Start trial that the scheduler wants to run + with warn_if_slow("choose_trial_to_run"): + trial_to_run = self._scheduler_alg.choose_trial_to_run(self._wrapped()) + + if trial_to_run: + if _dedup_logs("trial_to_run_chosen", trial_to_run.trial_id): + logger.debug( + f"Chose trial to run from scheduler: {trial_to_run} [dedup]" + ) + if ( + trial_to_run not in self._staged_trials + and trial_to_run not in self._trial_to_actor + ): + logger.debug(f"Staging trial to run: {trial_to_run}") + self._set_trial_status(trial_to_run, Trial.PENDING) + self._staged_trials.add(trial_to_run) + self._actor_cache.increase_max(trial_to_run.placement_group_factory) + # schedule_trial_actor also potentially uses cached actors + self._schedule_trial_actor(trial_to_run) + else: + # Otherwise, only try to use the cached actor + if _dedup_logs("trial_to_run_reuse", trial_to_run.trial_id): + logger.debug( + f"Trying to re-use actor for trial to run: {trial_to_run} " + f"[dedup]" + ) + self._maybe_reuse_cached_actor(trial_to_run) + + ### + # 2: Start trials that are PENDING + def _maybe_add_actors(candidates: List[Trial]): + new_candidates = [] + + while candidates: + if self._actor_manager.num_pending_actors >= self._max_pending_trials: + break + + trial = candidates.pop(0) + + # If the trial is part of the list, but not of the set, + # we just ignore it. Removing it from the list on status + # change is too expensive. + if trial not in self._pending_trials: + continue + + if trial in self._trial_to_actor: + new_candidates.append(trial) + continue + + if trial in self._staged_trials: + self._maybe_reuse_cached_actor(trial) + continue + + logger.debug(f"Scheduling actor for enqueued trial: {trial}") + self._staged_trials.add(trial) + self._actor_cache.increase_max(trial.placement_group_factory) + self._schedule_trial_actor(trial) + + return new_candidates + candidates + + self._pending_trials_list = _maybe_add_actors(self._pending_trials_list) + + ### + # 3: Start any trial that can be started with a cached actor + if self._actor_cache.num_cached_objects: + for resource in self._resources_to_pending_trials: + if not self._resources_to_pending_trials[resource]: + continue + + if not self._actor_cache.has_cached_object(resource): + continue + + start_trial = self._resources_to_pending_trials[resource].pop() + logger.debug( + f"Trying to re-use actor for enqueued trial: {start_trial}" + ) + if not self._maybe_reuse_cached_actor(start_trial): + self._resources_to_pending_trials[resource].add(start_trial) + else: + if start_trial not in self._staged_trials: + self._staged_trials.add(start_trial) + self._actor_cache.increase_max( + start_trial.placement_group_factory + ) + + def _maybe_reuse_cached_actor(self, trial: Trial) -> bool: + """Maybe reuse a cached actor for a trial. + + If an actor has been scheduled for the trial already, + this will remove the original actor. + """ + if trial in self._resetting_trials: + return True + + resource_request = trial.placement_group_factory + + if not self._actor_cache.has_cached_object(resource_request): + return False + + cached_actor = self._actor_cache.pop_cached_object(resource_request) + logger.debug(f"Reusing ACTOR for trial {trial}: {cached_actor}") + + if trial in self._trial_to_actor: + original_actor = self._trial_to_actor.pop(trial) + self._actor_to_trial.pop(original_actor) + + logger.debug(f"Removing ORIGINAL ACTOR for trial {trial}: {original_actor}") + self._remove_actor(tracked_actor=original_actor) + + self._trial_to_actor[trial] = cached_actor + self._actor_to_trial[cached_actor] = trial + + # Todo: get rid of Trial.runner + ray_actor = self._actor_manager._live_actors_to_ray_actors_resources[ + cached_actor + ][0] + trial.set_ray_actor(ray_actor) + + self._schedule_trial_reset(trial, trial.config, trial.experiment_tag) + + return True + + def _schedule_trial_actor(self, trial: Trial): + """Schedule an actor for a trial. + + If a cached actor is available, use it. Otherwise, request a + new actor. + """ + logger.debug(f"Trying to schedule new ACTOR for trial {trial}") + + assert trial.status == Trial.PENDING + + trial.init_local_path() + # We checkpoint metadata here to try mitigating logdir duplication + self._mark_trial_to_checkpoint(trial) + + if self._maybe_reuse_cached_actor(trial): + return + + # Safeguard + if trial in self._trial_to_actor: + raise RuntimeError( + f"Tried to request a new actor for trial {trial}, but an old " + f"actor still exists. This can lead to leaked resources. The old " + f"actor should be removed first. " + f"This is an internal problem in Ray Tune. If you encounter this " + f"error, please raise an issue on " + f"https://github.com/ray-project/ray/issues" + ) + + trainable_cls = trial.get_trainable_cls() + if not trainable_cls: + exception = _AbortTrialExecution( + f"Invalid trainable: {trial.trainable_name}. If you passed " + f"a string, make sure the trainable was registered before." + ) + trial.handle_error(exception) + self._schedule_trial_stop(trial, exception=exception) + return + + _actor_cls = self._class_cache.get(trainable_cls) + + trial.set_location(_Location()) + trainable_kwargs = _get_trainable_kwargs(trial=trial) + + with _change_working_directory(trial): + tracked_actor = self._actor_manager.add_actor( + cls=_actor_cls, + resource_request=trial.placement_group_factory, + kwargs=trainable_kwargs, + on_start=self._actor_started, + on_stop=self._actor_stopped, + on_error=self._actor_failed, + ) + self._trial_to_actor[trial] = tracked_actor + self._actor_to_trial[tracked_actor] = trial + + logger.debug( + f"Scheduled new ACTOR for trial {trial}: {tracked_actor}. " + f"Resources: {trial.placement_group_factory}" + ) + + def _unstage_trial_with_resources(self, trial: Trial): + """Unstage trial, or one with the same resources as ``trial``.""" + # Case 1: The trial we started was staged. Just remove it + if trial in self._staged_trials: + self._staged_trials.remove(trial) + self._actor_cache.decrease_max(trial.placement_group_factory) + return + + # Case 2: We staged a trial "A" with the same resources, but our trial "B" + # was selected by the scheduler to run. The resource manager does not care + # about "trials", it just cares about resources being available. Thus we + # look for a staged trial with the same resource requirements and remove it + + resource_request = trial.placement_group_factory + # Remove staged trial with same resource requirements + candidate_trial = None + for staged_trial in self._staged_trials: + staged_resources = staged_trial.placement_group_factory + if staged_resources == resource_request: + candidate_trial = staged_trial + break + + if candidate_trial: + self._staged_trials.remove(candidate_trial) + self._actor_cache.decrease_max(candidate_trial.placement_group_factory) + return + + raise RuntimeError( + "Started a trial with resources requested by a different trial, but " + "this trial was lost. This is an error in Ray Tune's execution " + "logic. Please raise a GitHub issue at " + "https://github.com/ray-project/ray/issues" + ) + + def _maybe_cache_trial_actor(self, trial: Trial) -> bool: + """Cache trial actor for reuse, if needed. + + We will only cache as many actors as are needed to fulfill any pending + resource requests for actors with the same resource requirements. + E.g. if we have 6 running trials and 4 additional staged actors, we will only + cache up to 4 of the running trial actors when they finish. + + One exception is the case when we have no cached actors, yet. In that case, + we will always cache the actor in this method. + + Later, in `_cleanup_cached_actors`, we will check again if we need this cached + actor. That method will keep the actor if we don't have any staged trials, + because we don't know at that point if the next trial might require the same + resources. But because there is no staged trial, it is safe to keep the actor + around, as it won't occupy resources needed by another trial until it's staged. + """ + if not self._reuse_actors: + return False + + if self._search_alg.is_finished() and not self._staged_trials: + logger.debug( + f"Not caching actor of trial {trial} as the search is over " + f"and no more trials are staged." + ) + return False + + tracked_actor = self._trial_to_actor[trial] + + if ( + not self._actor_manager.is_actor_started(tracked_actor) + or self._actor_manager.is_actor_failed(tracked_actor) + or tracked_actor not in self._started_actors + ): + logger.debug( + f"Not caching actor of trial {trial} as it has not been started, yet: " + f"{tracked_actor}" + ) + return False + + if not self._actor_cache.cache_object( + trial.placement_group_factory, tracked_actor + ): + logger.debug( + f"Could not cache actor of trial {trial} for " + "reuse, as there are no pending trials " + "requiring its resources." + ) + return False + + logger.debug(f"Caching actor of trial {trial} for re-use: {tracked_actor}") + + tracked_actor = self._trial_to_actor.pop(trial) + self._actor_to_trial.pop(tracked_actor) + + trial.set_ray_actor(None) + + return True + + def _actor_started(self, tracked_actor: TrackedActor, log: str = "STARTED"): + self._started_actors.add(tracked_actor) + + trial = self._actor_to_trial[tracked_actor] + + logger.debug(f"Actor {log} for trial {trial}: {tracked_actor}") + + self._unstage_trial_with_resources(trial) + + ray_actor = self._actor_manager._live_actors_to_ray_actors_resources[ + tracked_actor + ][0] + trial.set_ray_actor(ray_actor) + + self._callbacks.on_trial_start( + iteration=self._iteration, trials=self._trials, trial=trial + ) + + self._set_trial_status(trial, Trial.RUNNING) + + self._mark_trial_to_checkpoint(trial) + + if not self._schedule_trial_restore(trial): + self._schedule_trial_train(trial) + + def _actor_stopped(self, tracked_actor: TrackedActor): + if tracked_actor in self._actor_to_trial: + trial = self._actor_to_trial.pop(tracked_actor) + logger.debug(f"Actor STOPPED for trial {trial}: {tracked_actor}") + self._trial_to_actor.pop(trial) + trial.set_ray_actor(None) + + logger.debug(f"Actor STOPPED: {tracked_actor}") + + self._stopping_actors.pop(tracked_actor, None) + self._started_actors.discard(tracked_actor) + + def _actor_failed(self, tracked_actor: TrackedActor, exception: Exception): + trial = self._actor_to_trial[tracked_actor] + + logger.debug( + f"Actor FAILED for trial {trial}: {tracked_actor}. " + f"Exception: {exception}" + ) + + if trial in (self._pending_trials | self._paused_trials): + # First, set to running (needed downstream in _process_trial_failure) + self._set_trial_status(trial, Trial.RUNNING) + + logger.debug( + f"Trial {trial} failed in its creation task. Unstaging " + f"to allow it to be re-scheduled." + ) + + self._unstage_trial_with_resources(trial) + self._trial_task_failure(trial, exception=exception) + + self._actor_manager.clear_actor_task_futures(tracked_actor) + + # Clean up actor + tracked_actor.set_on_stop(None) + tracked_actor.set_on_error(None) + self._actor_manager.remove_actor(tracked_actor, kill=False) + + # Trigger actor stopped callback + self._actor_stopped(tracked_actor) + + def _schedule_trial_task( + self, + trial: Trial, + method_name: str, + args: Optional[Tuple] = None, + kwargs: Optional[Dict] = None, + on_result: Optional[Callable[[Trial, Any], None]] = None, + on_error: Optional[Callable[[Trial, Exception], None]] = None, + _return_future: bool = False, + ) -> Optional[ray.ObjectRef]: + """Schedule an actor task future for a trial. + + This is a wrapper around ``ActorManager.schedule_actor_task``. This method + retrieves the tracked actor for a trial to kick off the task. + + It also wraps around the callbacks, retrieving the trial object given the + tracked actor. + """ + + tracked_actor = self._trial_to_actor[trial] + + _on_result = None + _on_error = None + + args = args or tuple() + kwargs = kwargs or {} + + if on_result: + + def _on_result(tracked_actor: TrackedActor, *args, **kwargs): + assert trial == self._actor_to_trial[tracked_actor] + logger.debug( + f"Future {method_name.upper()} RESOLVED for trial {trial}: " + f"{args}, {kwargs}" + ) + try: + on_result(trial, *args, **kwargs) + except Exception as e: + logger.debug( + f"Error handling {method_name.upper()} result " + f"for trial {trial}: {e}" + ) + if e is TuneError or self._fail_fast == self.RAISE: + raise e + else: + raise TuneError(traceback.format_exc()) + + if on_error: + + def _on_error(tracked_actor: TrackedActor, exception: Exception): + # If the actor failed, it has already been cleaned up. + if tracked_actor not in self._actor_to_trial: + assert isinstance(exception, RayActorError), type(exception) + else: + assert trial == self._actor_to_trial[tracked_actor] + + logger.debug( + f"Future {method_name.upper()} FAILED for trial {trial}: " + f"{exception}" + ) + try: + on_error(trial, exception) + except Exception as e: + logger.debug( + f"Error handling {method_name.upper()} failure " + f"for trial {trial}: {e}" + ) + if e is TuneError or self._fail_fast == self.RAISE: + raise e + else: + raise TuneError(traceback.format_exc()) + + logger.debug(f"Future {method_name.upper()} SCHEDULED for trial {trial}") + + with _change_working_directory(trial): + future = self._actor_manager.schedule_actor_task( + tracked_actor=tracked_actor, + method_name=method_name, + args=args, + kwargs=kwargs, + on_result=_on_result, + on_error=_on_error, + _return_future=_return_future, + ) + if _return_future: + return future + + def _queue_decision(self, trial, decision): + # Get old decision, setting it to the current decision if it isn't set + old_decision = self._queued_trial_decisions.setdefault(trial.trial_id, decision) + + # Stopping always takes precedence. If we decided to stop, just quit + if old_decision is TrialScheduler.STOP: + return + + # The old decision wasn't STOP. We update the decision only if it is + # STOP or PAUSE. The action will only be CONTINUE if it was set by + # the first received result and was never updated after that. + if decision is TrialScheduler.STOP or decision is TrialScheduler.PAUSE: + self._queued_trial_decisions[trial.trial_id] = decision + + def _execute_action(self, trial: Trial, decision: str, after_save: bool = False): + """Executes action based on decision. + + Args: + trial: Trial to act on. + decision: Scheduling decision to undertake. + """ + if decision == TrialScheduler.CONTINUE: + self._schedule_trial_train(trial) + elif decision == TrialScheduler.PAUSE: + self.pause_trial(trial, should_checkpoint=not after_save) + elif decision == TrialScheduler.STOP: + self.stop_trial(trial) + elif decision == TrialScheduler.NOOP: + pass + else: + raise ValueError("Invalid decision: {}".format(decision)) + + def _maybe_execute_queued_decision(self, trial: Trial, after_save: bool = False): + # `self._queued_trial_decisions` now contains a final decision + # based on all results + final_decision = self._queued_trial_decisions.pop(trial.trial_id, None) + if final_decision: + logger.debug( + f"Executing final queued decision for {trial}: {final_decision}" + ) + self._execute_action(trial, final_decision, after_save=after_save) + + def _stop_experiment_if_needed(self): + """Stops all trials.""" + fail_fast = self._fail_fast and self._has_errored + if self._stopper.stop_all() or fail_fast or self._should_stop_experiment: + self._search_alg.set_finished() + [ + self._schedule_trial_stop(t) + for t in self._trials + if t.status not in {Trial.ERROR, Trial.TERMINATED} + ] + + ### + # Failure + def _trial_task_failure(self, trial: Trial, exception: Exception): + if self._fail_fast == self.RAISE: + raise exception + else: + if self._print_trial_errors: + logger.error(f"Trial task failed for trial {trial}", exc_info=exception) + self._process_trial_failure(trial, exception=exception) + + def _process_trial_failure( + self, + trial: Trial, + exception: Union[TuneError, RayTaskError, RayActorError], + ): + """Handle trial failure. + + Attempt trial recovery if possible, clean up state otherwise. + + Args: + trial: Failed trial. + exception: Exception prior to invoking this method. + """ + self._has_errored = True + trial.handle_error(exception) + if trial.status == Trial.RUNNING and trial.should_recover(): + self._try_recover(trial, exc=exception) + self._callbacks.on_trial_recover( + iteration=self._iteration, trials=self._trials, trial=trial + ) + elif trial.status in {Trial.RUNNING, Trial.PENDING}: + self._scheduler_alg.on_trial_error(self, trial) + self._search_alg.on_trial_complete(trial.trial_id, error=True) + self._schedule_trial_stop(trial, exception=exception) + self._callbacks.on_trial_error( + iteration=self._iteration, trials=self._trials, trial=trial + ) + + def _schedule_trial_stop(self, trial: Trial, exception: Optional[Exception] = None): + if trial.status == Trial.ERROR: + logger.debug(f"Not requesting trial STOP as it is ERROR already: {trial}") + return + + logger.debug(f"Requesting to STOP actor for trial {trial}") + + if trial.is_saving: + logger.debug( + f"Trial {trial} is currently saving/pausing. Scheduling STOP after " + f"save resolved." + ) + self._cached_trial_decisions[trial.trial_id] = TrialScheduler.STOP + + trial.temporary_state.saving_to = None + trial.temporary_state.restoring_from = None + + self._set_trial_status(trial, Trial.ERROR if exception else Trial.TERMINATED) + trial.set_location(_Location()) + + if trial not in self._trial_to_actor: + logger.debug(f"Will not STOP trial actor as it is not live: {trial}") + return + + tracked_actor = self._trial_to_actor[trial] + + self._actor_manager.clear_actor_task_futures(tracked_actor=tracked_actor) + + self._mark_trial_to_checkpoint(trial) + + if not exception and self._maybe_cache_trial_actor(trial): + # Trial runner has been cached + return + + logger.debug(f"Terminating actor for trial {trial}: {tracked_actor}") + + tracked_actor = self._trial_to_actor.pop(trial) + self._actor_to_trial.pop(tracked_actor) + + trial.set_ray_actor(None) + + self._remove_actor(tracked_actor=tracked_actor) + + def stop_trial(self, trial): + """The canonical implementation of stopping a trial. + + Trials may be in any external status when this function is called. + If trial is in state PENDING or PAUSED, calls `on_trial_remove` for + scheduler and `on_trial_complete()` for search_alg. + If trial is in state RUNNING, calls `on_trial_complete` for scheduler + and search_alg if RUNNING. Caller to ensure that there is no + outstanding future to be handled for the trial. If there is, the future + would be discarded. + """ + try: + if trial.status in [Trial.ERROR, Trial.TERMINATED]: + return + elif trial.status in [Trial.PENDING, Trial.PAUSED]: + self._scheduler_alg.on_trial_remove(self, trial) + self._search_alg.on_trial_complete(trial.trial_id) + elif trial.status is Trial.RUNNING: + # By this time trial.last_result should have been + # updated already. + self._scheduler_alg.on_trial_complete( + self, trial, flatten_dict(trial.last_result) + ) + self._search_alg.on_trial_complete( + trial.trial_id, result=flatten_dict(trial.last_result) + ) + self._callbacks.on_trial_complete( + iteration=self._iteration, trials=self._trials, trial=trial + ) + self._schedule_graceful_trial_stop(trial) + self._live_trials.discard(trial) + except Exception as e: + logger.exception("Trial %s: Error stopping trial.", trial) + if self._fail_fast == self.RAISE: + raise + if isinstance(e, TuneError): + self._process_trial_failure(trial, exception=e) + else: + self._process_trial_failure( + trial, _TuneStopTrialError(traceback.format_exc()) + ) + + def _schedule_graceful_trial_stop(self, trial: Trial): + self._schedule_trial_export(trial) + if trial.status != "ERROR": + self._schedule_trial_stop(trial) + + def _schedule_trial_pause(self, trial: Trial, should_checkpoint: bool = True): + if trial not in self._trial_to_actor: + logger.debug( + f"Trial PAUSE requested for trial {trial} but trial is already " + f"stopping. Ignoring." + ) + return + + if should_checkpoint: + self._cached_trial_decisions[trial.trial_id] = TrialScheduler.PAUSE + self._schedule_trial_save(trial=trial) + else: + self._schedule_trial_stop(trial) + self._set_trial_status(trial, Trial.PAUSED) + + ### + # TRAIN + + def _schedule_trial_train(self, trial: Trial): + args = () + method_name = "train" + + buffer_length, buffer_time_s = self._maybe_buffer_training(trial) + + if buffer_length > 1: + method_name = "train_buffered" + args = (buffer_length, buffer_time_s) + + logger.debug(f"Scheduling future {method_name.upper()} for trial {trial}") + + self._schedule_trial_task( + trial=trial, + method_name=method_name, + args=args, + on_result=self._on_training_result, + on_error=self._trial_task_failure, + ) + + def _maybe_buffer_training(self, trial: Trial) -> Tuple[int, float]: + buffer_time_s = max( + self._buffer_min_time_s, + min(self._buffer_max_time_s, self._actor_manager.num_actor_tasks // 10), + ) + buffer_length = self._buffer_length + + if buffer_length > 1 and trial.checkpoint_at_end: + # If a trial checkpoint can be triggered externally, + # it is not safe to buffer results. + if log_once("trial_executor_buffer_checkpoint"): + logger.warning( + "Disabling buffered training as you passed " + "`checkpoint_at_end` to `tune.CheckpointConfig()`." + ) + return 1, buffer_time_s + + if buffer_length > 1 and trial.checkpoint_freq > 0: + return min(buffer_length, trial.checkpoint_freq), buffer_time_s + + return buffer_length, buffer_time_s + + ### + # RESULT + + def _on_training_result(self, trial, result): + if not isinstance(result, list): + result = [result] + with warn_if_slow("process_trial_result"): + self._process_trial_results(trial, result) + self._maybe_execute_queued_decision(trial, after_save=False) + + def _process_trial_results(self, trial, results): + logger.debug(f"Processing trial results for trial {trial}: {results}") + with warn_if_slow( + "process_trial_results", + message="Processing trial results took {duration:.3f} s, " + "which may be a performance bottleneck. Please consider " + "reporting results less frequently to Ray Tune.", + ): + for i, result in enumerate(results): + with warn_if_slow("process_trial_result"): + decision = self._process_trial_result(trial, result) + if decision is None: + # If we didn't get a decision, this means a + # non-training future (e.g. a save) was scheduled. + # We do not allow processing more results then. + if i < len(results) - 1: + if log_once("tune_controller_buffer_checkpoint"): + logger.warning( + f"Trial {trial} has a non-training future " + f"scheduled but {len(results) - i} results " + f"left to process. This means that a " + f"checkpoint was requested, but buffered " + f"training was continued before it was " + f"saved. Consider using non-buffered " + f"training by setting the env variable " + f"`TUNE_RESULT_BUFFER_LENGTH=1`." + ) + elif decision == TrialScheduler.STOP: + # If the decision is to stop the trial, + # ignore all results that came after that. + break + + def _process_trial_result(self, trial, result): + result.update(trial_id=trial.trial_id) + is_duplicate = RESULT_DUPLICATE in result + force_checkpoint = result.get(SHOULD_CHECKPOINT, False) + # TrialScheduler and SearchAlgorithm still receive a + # notification because there may be special handling for + # the `on_trial_complete` hook. + if is_duplicate: + logger.debug("Trial finished without logging 'done'.") + result = trial.last_result + result.update(done=True) + + self._total_time += result.get(TIME_THIS_ITER_S, 0) + + flat_result = flatten_dict(result) + self._validate_result_metrics(flat_result) + + if self._stopper(trial.trial_id, result) or trial.should_stop(flat_result): + decision = TrialScheduler.STOP + else: + with warn_if_slow("scheduler.on_trial_result"): + decision = self._scheduler_alg.on_trial_result( + self._wrapped(), trial, flat_result + ) + if decision == TrialScheduler.STOP: + result.update(done=True) + else: + # Only updating search alg if the trial is not to be stopped. + with warn_if_slow("search_alg.on_trial_result"): + self._search_alg.on_trial_result(trial.trial_id, flat_result) + + # If this is not a duplicate result, the callbacks should + # be informed about the result. + if not is_duplicate: + with warn_if_slow("callbacks.on_trial_result"): + self._callbacks.on_trial_result( + iteration=self._iteration, + trials=self._trials, + trial=trial, + result=result.copy(), + ) + trial.update_last_result(result) + # Include in next experiment checkpoint + self._mark_trial_to_checkpoint(trial) + + # Checkpoints to disk. This should be checked even if + # the scheduler decision is STOP or PAUSE. Note that + # PAUSE only checkpoints to memory and does not update + # the global checkpoint state. + if decision != TrialScheduler.PAUSE: + # TODO(justinvyu): This is a temporary hack to fix pausing trials. + # We already schedule a save task in `pause_trial`, so no need + # to do it again here. + self._checkpoint_trial_if_needed(trial, force=force_checkpoint) + + if trial.is_saving: + logger.debug(f"Caching trial decision for trial {trial}: {decision}") + # Cache decision to execute on after the save is processed. + # This prevents changing the trial's state or kicking off + # another training step prematurely. + if not self._cached_trial_decisions.get(trial.trial_id) or decision in { + TrialScheduler.PAUSE, + TrialScheduler.STOP, + }: + # If already set, only overwrite if it's a PAUSE or STOP. This is + # to avoid that CONTINUE decisions from a training step that resolve + # late overwrite PAUSE/STOP decision. + self._cached_trial_decisions[trial.trial_id] = decision + return None + else: + self._queue_decision(trial, decision) + return decision + + def _validate_result_metrics(self, result): + """ + Check if any of the required metrics was not reported + in the last result. If the only items are ``done`` or any of + DEBUG_METRICS, this means that no result was ever received and + the trial just returned. This is also okay and will not raise + an error. + + This will ignore checking for the DEFAULT_METRIC. + """ + if int(os.environ.get("TUNE_DISABLE_STRICT_METRIC_CHECKING", 0)) != 1 and ( + len({k for k in result if k not in list(DEBUG_METRICS) + [DONE]}) > 1 + ): + base_metric = self._metric if self._metric != DEFAULT_METRIC else None + scheduler_metric = ( + self._scheduler_alg.metric + if self._scheduler_alg.metric != DEFAULT_METRIC + else None + ) + search_metrics = ( + self._search_alg.metric + if self._search_alg.metric != DEFAULT_METRIC + else None + ) + + if isinstance(search_metrics, str): + search_metrics = [search_metrics] + + if base_metric and base_metric not in result: + report_metric = base_metric + location = "tune.TuneConfig()" + elif scheduler_metric and scheduler_metric not in result: + report_metric = scheduler_metric + location = type(self._scheduler_alg).__name__ + elif search_metrics and any( + search_metric not in result for search_metric in search_metrics + ): + report_metric = list( + filter( + lambda search_metric: search_metric not in result, + search_metrics, + ) + ) + if len(report_metric) == 1: + report_metric = report_metric[0] + location = type(self._search_alg).__name__ + else: + report_metric = None + location = None + + if report_metric: + raise ValueError( + "Trial returned a result which did not include the " + "specified metric(s) `{}` that `{}` expects. " + "Make sure your calls to `tune.report()` include the " + "metric, or set the " + "TUNE_DISABLE_STRICT_METRIC_CHECKING " + "environment variable to 1. Result: {}".format( + report_metric, location, result + ) + ) + + ### + # SAVE + def _schedule_trial_save( + self, + trial: Trial, + result: Optional[Dict] = None, + ) -> Optional[_FutureTrainingResult]: + if trial not in self._trial_to_actor: + logger.debug( + f"Trial SAVE requested for trial {trial} but trial is already " + f"stopping. Ignoring." + ) + return None + + result = result or trial.last_result + + future = self._schedule_trial_task( + trial=trial, + method_name="save", + on_result=self._on_saving_result, + on_error=self._trial_task_failure, + _return_future=True, + ) + # TODO(justinvyu): `trial.saving_to` (and trial.is_saving) is needed + # in order to prevent a done=True result from executing a STOP decision + # (which clears all futures) before the save gets processed. + # Keep this in for now while `train` and `save` are 2 separate steps. + trial.temporary_state.saving_to = _FutureTrainingResult(future) + + # `trial.saving_to` holds a future training result -- this is only used + # in the case of PBT to block until the checkpoint is ready. + # In all other situations, the checkpoint future is processed by the + # actor event manager when it is ready. + return trial.temporary_state.saving_to + + def _on_saving_result(self, trial, checkpoint_value: _TrainingResult): + with warn_if_slow("process_trial_save"): + self._process_trial_save(trial, checkpoint_value) + + with warn_if_slow("callbacks.on_trial_save"): + self._callbacks.on_trial_save( + iteration=self._iteration, trials=self._trials, trial=trial + ) + + self._maybe_execute_queued_decision(trial, after_save=True) + + def _process_trial_save(self, trial: Trial, checkpoint_value: _TrainingResult): + """Processes a trial save. + + Acts on the decision cached during the last `_process_trial` call. + + Args: + trial: Trial being saved. + """ + logger.debug("Trial %s: Processing trial save.", trial) + + try: + if not checkpoint_value.checkpoint: + logger.debug(f"Got empty checkpoint for trial {trial}") + else: + try: + self._callbacks.on_checkpoint( + iteration=self._iteration, + trials=self._trials, + trial=trial, + checkpoint=checkpoint_value.checkpoint, + ) + except Exception: + logger.warning( + "Error encountered during processing of callbacks. " + "Ray Train/Tune recently changed the checkpoint interface " + "that is passed to callbacks. If you implemented your own " + "callback with an `on_checkpoint` handler, please review " + "the checkpoint interface and adjust your code " + "accordingly." + ) + raise + + trial.on_checkpoint(checkpoint_value) + + self._checkpoint_manager.on_trial_checkpoint(trial) + + self._mark_trial_to_checkpoint(trial) + except Exception: + logger.exception( + "Trial %s: Error handling checkpoint %s", trial, checkpoint_value + ) + + trial.temporary_state.saving_to = None + decision = self._cached_trial_decisions.pop(trial.trial_id, None) + if decision and checkpoint_value: + self._queue_decision(trial, decision) + + def _checkpoint_trial_if_needed(self, trial, force=False): + """Checkpoints trial based off trial.last_result.""" + if trial.should_checkpoint() or force: + # Save trial runtime if possible. + if trial.temporary_state.ray_actor: + self._schedule_trial_save(trial) + + ### + # RESTORE + def _schedule_trial_restore(self, trial: Trial) -> bool: + checkpoint_result = trial.latest_checkpoint_result + + if not checkpoint_result: + logger.debug(f"Not restoring trial {trial}: No checkpoint found.") + return False + + # TODO(justinvyu): Is this really needed? + trial.temporary_state.restoring_from = checkpoint_result + + method_name = "restore" + args = (checkpoint_result,) + self._schedule_trial_task( + trial=trial, + method_name=method_name, + args=args, + kwargs={}, + on_result=self._on_restoring_result, + on_error=self._trial_task_failure, + ) + return True + + def _on_restoring_result(self, trial: Trial, result: Any): + self._process_trial_restore(trial) + + def _process_trial_restore(self, trial: Trial): + """Processes a trial restore. + + Args: + trial: Trial being restored. + """ + logger.debug("Trial %s: Processing trial restore.", trial) + trial.on_restore() + logger.debug("Trial %s: Restore processed successfully", trial) + self._set_trial_status(trial, Trial.RUNNING) + self._schedule_trial_train(trial) + self._live_trials.add(trial) + + def _try_recover( + self, trial: Trial, exc: Union[TuneError, RayTaskError, RayActorError] + ): + """Tries to recover trial. + + Notifies SearchAlgorithm and Scheduler if failure to recover. + + Args: + trial: Trial to recover. + exc: Exception prior to invoking this method. + """ + self._cached_trial_decisions.pop(trial.trial_id, None) + # Resetting this, in case that the trial is in saving status when it crashes. + if trial.is_saving: + trial.temporary_state.saving_to = None + self._schedule_trial_stop(trial, exception=exc) + + logger.debug("Trial %s: Notifying Scheduler and requeueing.", trial) + self._requeue_trial(trial) + + def _requeue_trial(self, trial): + """Notification to TrialScheduler and requeue trial. + + This does not notify the SearchAlgorithm because the function + evaluation is still in progress. + + """ + self._scheduler_alg.on_trial_error(self, trial) + self._set_trial_status(trial, status=Trial.PENDING) + + # TODO(rliaw): Right now, this pushes the trial to the end of queue + # because restoration can be expensive. However, this is not + # ideal since it just hides the issue - a better fix would + # be to use an actor table to detect the IP of the Trainable + # and rsync the files there. + # See https://github.com/ray-project/ray/issues/5168 + self._trials.pop(self._trials.index(trial)) + self._trials.append(trial) + self._live_trials.add(trial) + + with warn_if_slow("scheduler.on_trial_add"): + self._scheduler_alg.on_trial_add(self._wrapped(), trial) + + ### + # EXPORT + def _schedule_trial_export(self, trial: Trial): + if not trial.export_formats or len(trial.export_formats) <= 0: + return + + # Todo: We are waiting here synchronously until the task resolved. + # Instead, we should schedule the trial stop after the export resolved. + # This requires changes in TrialRunner, which we can remove once the + # legacy execution path has been removed. + future = self._schedule_trial_task( + trial=trial, + method_name="export_model", + args=(trial.export_formats,), + on_result=None, + on_error=self._trial_task_failure, + _return_future=True, + ) + self._actor_manager._actor_task_events.resolve_future(future) + + ### + # RESET + def _schedule_trial_reset( + self, + trial: Trial, + new_config: Dict, + new_experiment_tag: str, + ): + trial.set_experiment_tag(new_experiment_tag) + trial.set_config(new_config) + + # Pass magic variables + extra_config = copy.deepcopy(new_config) + extra_config[TRIAL_INFO] = _TrialInfo(trial) + + stdout_file, stderr_file = trial.log_to_file + extra_config[STDOUT_FILE] = stdout_file + extra_config[STDERR_FILE] = stderr_file + + logger_creator = partial( + _noop_logger_creator, logdir=trial.storage.trial_working_directory + ) + + self._resetting_trials.add(trial) + self._schedule_trial_task( + trial=trial, + method_name="reset", + args=(extra_config,), + kwargs={ + "logger_creator": logger_creator, + "storage": trial.storage, + }, + on_result=self._on_trial_reset, + on_error=self._trial_task_failure, + ) + + def _on_trial_reset(self, trial: Trial, success: bool): + self._resetting_trials.remove(trial) + + if not success: + info = ( + "Trainable runner reuse requires reset_config() to be " + "implemented and return True." + ) + + logger.error(f"Could not re-use actor for trial {trial}: {info}") + + exception = _AbortTrialExecution(info) + + trial.handle_error(exception) + self._schedule_trial_stop(trial, exception=exception) + return + + tracked_actor = self._trial_to_actor[trial] + + self._actor_started(tracked_actor, log="REUSED") + + def request_stop_trial(self, trial): + self._stop_queue.append(trial) + + def request_stop_experiment(self): + self._should_stop_experiment = True + + def _process_stop_requests(self): + while self._stop_queue: + t = self._stop_queue.pop() + self.stop_trial(t) + + def pause_trial(self, trial: Trial, should_checkpoint: bool = True): + """Pause a trial and reset the necessary state variables for resuming later. + + Args: + trial: Trial to pause. + should_checkpoint: Whether or not an in-memory checkpoint should be created + for this paused trial. Defaults to True. + """ + # NOTE: The cached trial decision is not needed since we will overrule this + # decision with PAUSE. + self._cached_trial_decisions.pop(trial.trial_id, None) + self._schedule_trial_pause(trial, should_checkpoint=should_checkpoint) + + def cleanup(self): + """Cleanup trials and callbacks.""" + self._cleanup_trials() + self.end_experiment_callbacks() + + def __getstate__(self): + """Gets state for trial. + + Note that this is not used as a pickling override as + does not have all fields. + """ + state = self.__dict__.copy() + for k in [ + "_trials", + "_live_trials", + "_stop_queue", + "_search_alg", + "_placeholder_resolvers", + "_scheduler_alg", + "_pending_trial_queue_times", + "_callbacks", + "_checkpoint_manager", + "_storage", + "_insufficient_resources_manager", + "_actor_manager", + "_class_cache", + "_resource_updater", + "_trials_to_cache", + "_trial_metadata", + "_actor_to_trial", + "_trial_to_actor", + "_resources_to_pending_trials", + "_pending_trials", + "_pending_trials_list", + "_running_trials", + "_paused_trials", + "_stopped_trials", + "_failed_trials", + "_resetting_trials", + "_started_actors", + "_stopping_actors", + "_staged_trials", + "_actor_cache", + ]: + del state[k] + return state + + def __setstate__(self, state): + # Use session_str from previous checkpoint if does not exist + session_str = state.pop("_session_str") + self.__dict__.setdefault("_session_str", session_str) + # Use start_time from previous checkpoint if does not exist + start_time = state.pop("_start_time") + self.__dict__.setdefault("_start_time", start_time) + + self.__dict__.update(state) + self._checkpoint_manager = self._create_checkpoint_manager() + + +class _TrialExecutorWrapper: + """Wraps around TrialExecutor class, intercepts API calls and warns users + of restricted API access. + + This is meant to facilitate restricting + the current API exposure of TrialExecutor by TrialScheduler. + """ + + def __init__( + self, + trial_executor: "_FakeRayTrialExecutor", + whitelist_attr: Optional[set] = None, + ): + self._trial_executor = trial_executor + self._whitelist_attr = whitelist_attr or set() + + for attr in self._whitelist_attr: + assert hasattr(self._trial_executor, attr) + + def __getattr__(self, attr): + if attr not in self._whitelist_attr: + if log_once("restrict_accessing_trial_executor"): + logger.warning( + f"You are trying to access {attr} interface of " + f"TrialExecutor in TrialScheduler, which is being " + f"restricted. If you believe it is reasonable for " + f"your scheduler to access this TrialExecutor API, " + f"please reach out to Ray team on GitHub. A more " + f"strict API access pattern would be enforced " + f"starting 1.12.0" + ) + return getattr(self._trial_executor, attr) + + +@DeveloperAPI +class TrialRunnerWrapper: + """Wraps around TrialRunner class, intercepts API calls and warns users + of restricted API access. + + This is meant to facilitate restricting + the current API exposure of TrialRunner by TrialScheduler. + """ + + _EXECUTOR_ATTR = "trial_executor" + + def __init__( + self, + tune_controller: TuneController, + trial_executor: Any, + runner_whitelist_attr: Optional[set] = None, + executor_whitelist_attr: Optional[set] = None, + ): + self._tune_controller = tune_controller + self._trial_executor = _TrialExecutorWrapper( + trial_executor, executor_whitelist_attr + ) + self._runner_whitelist_attr = runner_whitelist_attr or set() + + for attr in self._runner_whitelist_attr: + assert hasattr(self, attr) + + def __getattr__(self, attr): + if attr == self._EXECUTOR_ATTR: + return self._trial_executor + if attr not in self._runner_whitelist_attr: + if log_once("restrict_accessing_tune_controller"): + logger.warning( + f"You are trying to access {attr} interface of " + f"TrialRunner in TrialScheduler, which is being " + f"restricted. If you believe it is reasonable for " + f"your scheduler to access this TrialRunner API, " + f"please reach out to Ray team on GitHub. A more " + f"strict API access pattern would be enforced " + f"starting 1.12s.0" + ) + return getattr(self._tune_controller, attr) + + +def _get_max_pending_trials(search_alg: SearchAlgorithm) -> int: + max_pending_trials = os.getenv("TUNE_MAX_PENDING_TRIALS_PG", "auto") + + if max_pending_trials != "auto": + return int(max_pending_trials) + + # Else, auto detect. + + # Only BasicVariantGenerator supports > 1 pending trials. + # This is because we don't want to generate too many trials + # before we fit the searcher model. + if not isinstance(search_alg, BasicVariantGenerator): + return 1 + + # Allow up to at least 200 pending trials to trigger fast autoscaling + min_autoscaling_rate = 200 + + # Allow more pending trials for larger clusters (based on number of CPUs) + cluster_cpus = ray.cluster_resources().get("CPU", 1.0) + max_pending_trials = max(min_autoscaling_rate, int(cluster_cpus * 1.1)) + + if max_pending_trials > min_autoscaling_rate: + logger.warning( + f"The maximum number of pending trials has been " + f"automatically set to the number of available " + f"cluster CPUs, which is high " + f"({max_pending_trials} CPUs/pending trials). " + f"If you're running an experiment with a large number " + f"of trials, this could lead to scheduling overhead. " + f"In this case, consider setting the " + f"`TUNE_MAX_PENDING_TRIALS_PG` environment variable " + f"to the desired maximum number of concurrent pending trials." + ) + + return max_pending_trials + + +class _FakeRayTrialExecutor: + """The TuneController does not use a RayTrialExecutor anymore. + + Instead, we pass this fake executor for searchers/schedulers to use + as an interface. + + In the future, we should have the searchers/schedulers either interact with + the tune controller, or define a different API for more fine-grained scheduler + control. + """ + + def __init__(self, tune_controller: TuneController): + self._tune_controller = tune_controller + + def pause_trial(self, trial: Trial, should_checkpoint: bool = True): + return self._tune_controller._schedule_trial_pause( + trial, should_checkpoint=should_checkpoint + ) + + def save( + self, + trial: Trial, + result: Optional[Dict] = None, + ) -> Optional[_FutureTrainingResult]: + return self._tune_controller._schedule_trial_save(trial=trial, result=result) + + def has_resources_for_trial(self, trial: Trial): + return True + + @property + def _resource_updater(self): + return self._tune_controller._resource_updater + + def force_reconcilation_on_next_step_end(self): + pass diff --git a/venv/lib/python3.10/site-packages/ray/tune/experiment/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/experiment/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..39a20fc56e8e49826cbc5c4cd705efe7eb4b3f4f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/experiment/__init__.py @@ -0,0 +1,4 @@ +from ray.tune.experiment.experiment import Experiment, _convert_to_experiment_list +from ray.tune.experiment.trial import Trial + +__all__ = ["Experiment", "_convert_to_experiment_list", "Trial"] diff --git a/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6af6d7fcb941b98ea49fb4d85be4ca21911d37d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/config_parser.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/config_parser.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..252317e82c403543c242d2ef0c96fffdd7b7b03d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/config_parser.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/experiment.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/experiment.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a738a6ab5e4c423aa7356a37d902821111fdf282 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/experiment.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/trial.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/trial.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94be47364722bed977790b6b25f856398d85ebbe Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/experiment/__pycache__/trial.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/experiment/config_parser.py b/venv/lib/python3.10/site-packages/ray/tune/experiment/config_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..aaf1b8bde6453d70d2f58ac3b499c96afb7770e1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/experiment/config_parser.py @@ -0,0 +1,210 @@ +import argparse +import json + +from ray.tune import CheckpointConfig +from ray.tune.error import TuneError +from ray.tune.experiment import Trial +from ray.tune.resources import json_to_resources + +# For compatibility under py2 to consider unicode as str +from ray.tune.utils.serialization import TuneFunctionEncoder +from ray.tune.utils.util import SafeFallbackEncoder + + +def _make_parser(parser_creator=None, **kwargs): + """Returns a base argument parser for the ray.tune tool. + + Args: + parser_creator: A constructor for the parser class. + kwargs: Non-positional args to be passed into the + parser class constructor. + """ + + if parser_creator: + parser = parser_creator(**kwargs) + else: + parser = argparse.ArgumentParser(**kwargs) + + # Note: keep this in sync with rllib/train.py + parser.add_argument( + "--run", + default=None, + type=str, + help="The algorithm or model to train. This may refer to the name " + "of a built-on algorithm (e.g. RLlib's DQN or PPO), or a " + "user-defined trainable function or class registered in the " + "tune registry.", + ) + parser.add_argument( + "--stop", + default="{}", + type=json.loads, + help="The stopping criteria, specified in JSON. The keys may be any " + "field returned by 'train()' e.g. " + '\'{"time_total_s": 600, "training_iteration": 100000}\' to stop ' + "after 600 seconds or 100k iterations, whichever is reached first.", + ) + parser.add_argument( + "--config", + default="{}", + type=json.loads, + help="Algorithm-specific configuration (e.g. env, hyperparams), " + "specified in JSON.", + ) + parser.add_argument( + "--resources-per-trial", + default=None, + type=json_to_resources, + help="Override the machine resources to allocate per trial, e.g. " + '\'{"cpu": 64, "gpu": 8}\'. Note that GPUs will not be assigned ' + "unless you specify them here. For RLlib, you probably want to " + "leave this alone and use RLlib configs to control parallelism.", + ) + parser.add_argument( + "--num-samples", + default=1, + type=int, + help="Number of times to repeat each trial.", + ) + parser.add_argument( + "--checkpoint-freq", + default=0, + type=int, + help="How many training iterations between checkpoints. " + "A value of 0 (default) disables checkpointing.", + ) + parser.add_argument( + "--checkpoint-at-end", + action="store_true", + help="Whether to checkpoint at the end of the experiment. Default is False.", + ) + parser.add_argument( + "--keep-checkpoints-num", + default=None, + type=int, + help="Number of best checkpoints to keep. Others get " + "deleted. Default (None) keeps all checkpoints.", + ) + parser.add_argument( + "--checkpoint-score-attr", + default="training_iteration", + type=str, + help="Specifies by which attribute to rank the best checkpoint. " + "Default is increasing order. If attribute starts with min- it " + "will rank attribute in decreasing order. Example: " + "min-validation_loss", + ) + parser.add_argument( + "--export-formats", + default=None, + help="List of formats that exported at the end of the experiment. " + "Default is None. For RLlib, 'checkpoint' and 'model' are " + "supported for TensorFlow policy graphs.", + ) + parser.add_argument( + "--max-failures", + default=3, + type=int, + help="Try to recover a trial from its last checkpoint at least this " + "many times. Only applies if checkpointing is enabled.", + ) + parser.add_argument( + "--scheduler", + default="FIFO", + type=str, + help="FIFO (default), MedianStopping, AsyncHyperBand, " + "HyperBand, or HyperOpt.", + ) + parser.add_argument( + "--scheduler-config", + default="{}", + type=json.loads, + help="Config options to pass to the scheduler.", + ) + + # Note: this currently only makes sense when running a single trial + parser.add_argument( + "--restore", + default=None, + type=str, + help="If specified, restore from this checkpoint.", + ) + + return parser + + +def _to_argv(config): + """Converts configuration to a command line argument format.""" + argv = [] + for k, v in config.items(): + if "-" in k: + raise ValueError("Use '_' instead of '-' in `{}`".format(k)) + if v is None: + continue + if not isinstance(v, bool) or v: # for argparse flags + argv.append("--{}".format(k.replace("_", "-"))) + if isinstance(v, str): + argv.append(v) + elif isinstance(v, bool): + pass + elif callable(v): + argv.append(json.dumps(v, cls=TuneFunctionEncoder)) + else: + argv.append(json.dumps(v, cls=SafeFallbackEncoder)) + return argv + + +_cached_pgf = {} + + +def _create_trial_from_spec( + spec: dict, parser: argparse.ArgumentParser, **trial_kwargs +): + """Creates a Trial object from parsing the spec. + + Args: + spec: A resolved experiment specification. Arguments should + The args here should correspond to the command line flags + in ray.tune.experiment.config_parser. + parser: An argument parser object from + make_parser. + trial_kwargs: Extra keyword arguments used in instantiating the Trial. + + Returns: + A trial object with corresponding parameters to the specification. + """ + global _cached_pgf + + spec = spec.copy() + resources = spec.pop("resources_per_trial", None) + + try: + args, _ = parser.parse_known_args(_to_argv(spec)) + except SystemExit: + raise TuneError("Error parsing args, see above message", spec) + + if resources: + trial_kwargs["placement_group_factory"] = resources + + checkpoint_config = spec.get("checkpoint_config", CheckpointConfig()) + + return Trial( + # Submitting trial via server in py2.7 creates Unicode, which does not + # convert to string in a straightforward manner. + trainable_name=spec["run"], + # json.load leads to str -> unicode in py2.7 + config=spec.get("config", {}), + # json.load leads to str -> unicode in py2.7 + stopping_criterion=spec.get("stop", {}), + checkpoint_config=checkpoint_config, + export_formats=spec.get("export_formats", []), + # str(None) doesn't create None + restore_path=spec.get("restore"), + trial_name_creator=spec.get("trial_name_creator"), + trial_dirname_creator=spec.get("trial_dirname_creator"), + log_to_file=spec.get("log_to_file"), + # str(None) doesn't create None + max_failures=args.max_failures, + storage=spec.get("storage"), + **trial_kwargs, + ) diff --git a/venv/lib/python3.10/site-packages/ray/tune/experiment/experiment.py b/venv/lib/python3.10/site-packages/ray/tune/experiment/experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..f1b942d564053eb6b8c5f4c4c03361093f3a6b3c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/experiment/experiment.py @@ -0,0 +1,445 @@ +import copy +import datetime +import logging +import pprint as pp +import traceback +from functools import partial +from pathlib import Path +from pickle import PicklingError +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + Mapping, + Optional, + Sequence, + Type, + Union, +) + +import ray +from ray.exceptions import RpcError +from ray.train._internal.storage import StorageContext +from ray.train.constants import DEFAULT_STORAGE_PATH +from ray.tune import CheckpointConfig, SyncConfig +from ray.tune.error import TuneError +from ray.tune.registry import is_function_trainable, register_trainable +from ray.tune.stopper import CombinedStopper, FunctionStopper, Stopper, TimeoutStopper +from ray.util.annotations import Deprecated, DeveloperAPI + +if TYPE_CHECKING: + import pyarrow.fs + + from ray.tune import PlacementGroupFactory + from ray.tune.experiment import Trial + + +logger = logging.getLogger(__name__) + + +def _validate_log_to_file(log_to_file): + """Validate ``tune.RunConfig``'s ``log_to_file`` parameter. Return + validated relative stdout and stderr filenames.""" + if not log_to_file: + stdout_file = stderr_file = None + elif isinstance(log_to_file, bool) and log_to_file: + stdout_file = "stdout" + stderr_file = "stderr" + elif isinstance(log_to_file, str): + stdout_file = stderr_file = log_to_file + elif isinstance(log_to_file, Sequence): + if len(log_to_file) != 2: + raise ValueError( + "If you pass a Sequence to `log_to_file` it has to have " + "a length of 2 (for stdout and stderr, respectively). The " + "Sequence you passed has length {}.".format(len(log_to_file)) + ) + stdout_file, stderr_file = log_to_file + else: + raise ValueError( + "You can pass a boolean, a string, or a Sequence of length 2 to " + "`log_to_file`, but you passed something else ({}).".format( + type(log_to_file) + ) + ) + return stdout_file, stderr_file + + +@DeveloperAPI +class Experiment: + """Tracks experiment specifications. + + Implicitly registers the Trainable if needed. The args here take + the same meaning as the arguments defined `tune.py:run`. + + .. code-block:: python + + experiment_spec = Experiment( + "my_experiment_name", + my_func, + stop={"mean_accuracy": 100}, + config={ + "alpha": tune.grid_search([0.2, 0.4, 0.6]), + "beta": tune.grid_search([1, 2]), + }, + resources_per_trial={ + "cpu": 1, + "gpu": 0 + }, + num_samples=10, + local_dir="~/ray_results", + checkpoint_freq=10, + max_failures=2) + + """ + + # Keys that will be present in `public_spec` dict. + PUBLIC_KEYS = {"stop", "num_samples", "time_budget_s"} + _storage_context_cls = StorageContext + + def __init__( + self, + name: str, + run: Union[str, Callable, Type], + *, + stop: Optional[Union[Mapping, Stopper, Callable[[str, Mapping], bool]]] = None, + time_budget_s: Optional[Union[int, float, datetime.timedelta]] = None, + config: Optional[Dict[str, Any]] = None, + resources_per_trial: Union[ + None, Mapping[str, Union[float, int, Mapping]], "PlacementGroupFactory" + ] = None, + num_samples: int = 1, + storage_path: Optional[str] = None, + storage_filesystem: Optional["pyarrow.fs.FileSystem"] = None, + sync_config: Optional[Union[SyncConfig, dict]] = None, + checkpoint_config: Optional[Union[CheckpointConfig, dict]] = None, + trial_name_creator: Optional[Callable[["Trial"], str]] = None, + trial_dirname_creator: Optional[Callable[["Trial"], str]] = None, + log_to_file: bool = False, + export_formats: Optional[Sequence] = None, + max_failures: int = 0, + restore: Optional[str] = None, + # Deprecated + local_dir: Optional[str] = None, + ): + if isinstance(checkpoint_config, dict): + checkpoint_config = CheckpointConfig(**checkpoint_config) + else: + checkpoint_config = checkpoint_config or CheckpointConfig() + + if is_function_trainable(run): + if checkpoint_config.checkpoint_at_end: + raise ValueError( + "'checkpoint_at_end' cannot be used with a function trainable. " + "You should include one last call to " + "`ray.tune.report(metrics=..., checkpoint=...)` " + "at the end of your training loop to get this behavior." + ) + if checkpoint_config.checkpoint_frequency: + raise ValueError( + "'checkpoint_frequency' cannot be set for a function trainable. " + "You will need to report a checkpoint every " + "`checkpoint_frequency` iterations within your training loop using " + "`ray.tune.report(metrics=..., checkpoint=...)` " + "to get this behavior." + ) + try: + self._run_identifier = Experiment.register_if_needed(run) + except RpcError as e: + if e.rpc_code == ray._raylet.GRPC_STATUS_CODE_RESOURCE_EXHAUSTED: + raise TuneError( + f"The Trainable/training function is too large for grpc resource " + f"limit. Check that its definition is not implicitly capturing a " + f"large array or other object in scope. " + f"Tip: use tune.with_parameters() to put large objects " + f"in the Ray object store. \n" + f"Original exception: {traceback.format_exc()}" + ) + else: + raise e + + if not name: + name = StorageContext.get_experiment_dir_name(run) + + storage_path = storage_path or DEFAULT_STORAGE_PATH + self.storage = self._storage_context_cls( + storage_path=storage_path, + storage_filesystem=storage_filesystem, + sync_config=sync_config, + experiment_dir_name=name, + ) + logger.debug(f"StorageContext on the DRIVER:\n{self.storage}") + + config = config or {} + if not isinstance(config, dict): + raise ValueError( + f"`Experiment(config)` must be a dict, got: {type(config)}. " + "Please convert your search space to a dict before passing it in." + ) + + self._stopper = None + stopping_criteria = {} + if not stop: + pass + elif isinstance(stop, list): + bad_stoppers = [s for s in stop if not isinstance(s, Stopper)] + if bad_stoppers: + stopper_types = [type(s) for s in stop] + raise ValueError( + "If you pass a list as the `stop` argument to " + "`tune.RunConfig()`, each element must be an instance of " + f"`tune.stopper.Stopper`. Got {stopper_types}." + ) + self._stopper = CombinedStopper(*stop) + elif isinstance(stop, dict): + stopping_criteria = stop + elif callable(stop): + if FunctionStopper.is_valid_function(stop): + self._stopper = FunctionStopper(stop) + elif isinstance(stop, Stopper): + self._stopper = stop + else: + raise ValueError( + "Provided stop object must be either a dict, " + "a function, or a subclass of " + f"`ray.tune.Stopper`. Got {type(stop)}." + ) + else: + raise ValueError( + f"Invalid stop criteria: {stop}. Must be a " + f"callable or dict. Got {type(stop)}." + ) + + if time_budget_s: + if self._stopper: + self._stopper = CombinedStopper( + self._stopper, TimeoutStopper(time_budget_s) + ) + else: + self._stopper = TimeoutStopper(time_budget_s) + + stdout_file, stderr_file = _validate_log_to_file(log_to_file) + + spec = { + "run": self._run_identifier, + "stop": stopping_criteria, + "time_budget_s": time_budget_s, + "config": config, + "resources_per_trial": resources_per_trial, + "num_samples": num_samples, + "checkpoint_config": checkpoint_config, + "trial_name_creator": trial_name_creator, + "trial_dirname_creator": trial_dirname_creator, + "log_to_file": (stdout_file, stderr_file), + "export_formats": export_formats or [], + "max_failures": max_failures, + "restore": ( + Path(restore).expanduser().absolute().as_posix() if restore else None + ), + "storage": self.storage, + } + self.spec = spec + + @classmethod + def from_json(cls, name: str, spec: dict): + """Generates an Experiment object from JSON. + + Args: + name: Name of Experiment. + spec: JSON configuration of experiment. + """ + if "run" not in spec: + raise TuneError("No trainable specified!") + + # Special case the `env` param for RLlib by automatically + # moving it into the `config` section. + if "env" in spec: + spec["config"] = spec.get("config", {}) + spec["config"]["env"] = spec["env"] + del spec["env"] + + if "sync_config" in spec and isinstance(spec["sync_config"], dict): + spec["sync_config"] = SyncConfig(**spec["sync_config"]) + + if "checkpoint_config" in spec and isinstance(spec["checkpoint_config"], dict): + spec["checkpoint_config"] = CheckpointConfig(**spec["checkpoint_config"]) + + spec = copy.deepcopy(spec) + + run_value = spec.pop("run") + try: + exp = cls(name, run_value, **spec) + except TypeError as e: + raise TuneError( + f"Failed to load the following Tune experiment " + f"specification:\n\n {pp.pformat(spec)}.\n\n" + f"Please check that the arguments are valid. " + f"Experiment creation failed with the following " + f"error:\n {e}" + ) + return exp + + @classmethod + def get_trainable_name(cls, run_object: Union[str, Callable, Type]): + """Get Trainable name. + + Args: + run_object: Trainable to run. If string, + assumes it is an ID and does not modify it. Otherwise, + returns a string corresponding to the run_object name. + + Returns: + A string representing the trainable identifier. + + Raises: + TuneError: if ``run_object`` passed in is invalid. + """ + from ray.tune.search.sample import Domain + + if isinstance(run_object, str) or isinstance(run_object, Domain): + return run_object + elif isinstance(run_object, type) or callable(run_object): + name = "DEFAULT" + if hasattr(run_object, "_name"): + name = run_object._name + elif hasattr(run_object, "__name__"): + fn_name = run_object.__name__ + if fn_name == "": + name = "lambda" + elif fn_name.startswith("<"): + name = "DEFAULT" + else: + name = fn_name + elif ( + isinstance(run_object, partial) + and hasattr(run_object, "func") + and hasattr(run_object.func, "__name__") + ): + name = run_object.func.__name__ + else: + logger.warning("No name detected on trainable. Using {}.".format(name)) + return name + else: + raise TuneError("Improper 'run' - not string nor trainable.") + + @classmethod + def register_if_needed(cls, run_object: Union[str, Callable, Type]): + """Registers Trainable or Function at runtime. + + Assumes already registered if run_object is a string. + Also, does not inspect interface of given run_object. + + Args: + run_object: Trainable to run. If string, + assumes it is an ID and does not modify it. Otherwise, + returns a string corresponding to the run_object name. + + Returns: + A string representing the trainable identifier. + """ + from ray.tune.search.sample import Domain + + if isinstance(run_object, str): + return run_object + elif isinstance(run_object, Domain): + logger.warning("Not registering trainable. Resolving as variant.") + return run_object + name = cls.get_trainable_name(run_object) + try: + register_trainable(name, run_object) + except (TypeError, PicklingError) as e: + extra_msg = ( + "Other options: " + "\n-Try reproducing the issue by calling " + "`pickle.dumps(trainable)`. " + "\n-If the error is typing-related, try removing " + "the type annotations and try again." + ) + raise type(e)(str(e) + " " + extra_msg) from None + return name + + @property + def stopper(self): + return self._stopper + + @property + def local_path(self) -> Optional[str]: + return self.storage.experiment_driver_staging_path + + @property + @Deprecated("Replaced by `local_path`") + def local_dir(self): + # TODO(justinvyu): [Deprecated] Remove in 2.11. + raise DeprecationWarning("Use `local_path` instead of `local_dir`.") + + @property + def remote_path(self) -> Optional[str]: + return self.storage.experiment_fs_path + + @property + def path(self) -> Optional[str]: + return self.remote_path or self.local_path + + @property + def checkpoint_config(self): + return self.spec.get("checkpoint_config") + + @property + @Deprecated("Replaced by `local_path`") + def checkpoint_dir(self): + # TODO(justinvyu): [Deprecated] Remove in 2.11. + raise DeprecationWarning("Use `local_path` instead of `checkpoint_dir`.") + + @property + def run_identifier(self): + """Returns a string representing the trainable identifier.""" + return self._run_identifier + + @property + def public_spec(self) -> Dict[str, Any]: + """Returns the spec dict with only the public-facing keys. + + Intended to be used for passing information to callbacks, + Searchers and Schedulers. + """ + return {k: v for k, v in self.spec.items() if k in self.PUBLIC_KEYS} + + +def _convert_to_experiment_list(experiments: Union[Experiment, List[Experiment], Dict]): + """Produces a list of Experiment objects. + + Converts input from dict, single experiment, or list of + experiments to list of experiments. If input is None, + will return an empty list. + + Arguments: + experiments: Experiments to run. + + Returns: + List of experiments. + """ + exp_list = experiments + + # Transform list if necessary + if experiments is None: + exp_list = [] + elif isinstance(experiments, Experiment): + exp_list = [experiments] + elif type(experiments) is dict: + exp_list = [ + Experiment.from_json(name, spec) for name, spec in experiments.items() + ] + + # Validate exp_list + if type(exp_list) is list and all(isinstance(exp, Experiment) for exp in exp_list): + if len(exp_list) > 1: + logger.info( + "Running with multiple concurrent experiments. " + "All experiments will be using the same SearchAlgorithm." + ) + else: + raise TuneError("Invalid argument: {}".format(experiments)) + + return exp_list diff --git a/venv/lib/python3.10/site-packages/ray/tune/experiment/trial.py b/venv/lib/python3.10/site-packages/ray/tune/experiment/trial.py new file mode 100644 index 0000000000000000000000000000000000000000..506bd1a15740ace3fc18690bfee2bd1239e59435 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/experiment/trial.py @@ -0,0 +1,1073 @@ +import copy +import json +import logging +import os +import platform +import re +import time +import uuid +from contextlib import contextmanager +from functools import partial +from numbers import Number +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import ray +import ray.cloudpickle as cloudpickle +from ray._common.utils import binary_to_hex, hex_to_binary +from ray.air.constants import ( + EXPR_ERROR_FILE, + EXPR_ERROR_PICKLE_FILE, + TRAINING_ITERATION, +) +from ray.exceptions import RayActorError, RayTaskError +from ray.train._internal.checkpoint_manager import _CheckpointManager +from ray.train._internal.session import _FutureTrainingResult, _TrainingResult +from ray.train._internal.storage import StorageContext, _exists_at_fs_path +from ray.train.constants import ( + RAY_CHDIR_TO_TRIAL_DIR, + RAY_TRAIN_COUNT_PREEMPTION_AS_FAILURE, +) +from ray.tune import Checkpoint, CheckpointConfig +from ray.tune.error import TuneError +from ray.tune.execution.placement_groups import ( + PlacementGroupFactory, + resource_dict_to_pg_factory, +) +from ray.tune.logger import NoopLogger + +# NOTE(rkn): We import ray.tune.registry here instead of importing the names we +# need because there are cyclic imports that may cause specific names to not +# have been defined yet. See https://github.com/ray-project/ray/issues/1716. +from ray.tune.registry import get_trainable_cls, validate_trainable +from ray.tune.result import ( + DEBUG_METRICS, + DONE, + NODE_IP, + PID, + STDERR_FILE, + STDOUT_FILE, + TRIAL_ID, + TRIAL_INFO, +) +from ray.tune.trainable.metadata import _TrainingRunMetadata +from ray.tune.utils import date_str, flatten_dict +from ray.tune.utils.serialization import TuneFunctionDecoder, TuneFunctionEncoder +from ray.util import log_once +from ray.util.annotations import Deprecated, DeveloperAPI + +DEBUG_PRINT_INTERVAL = 5 +_DEFAULT_WIN_MAX_PATH_LENGTH = 260 +TRIAL_STATE_FILENAME = "trial_metadata.json" + + +logger = logging.getLogger(__name__) + + +class _Location: + """Describes the location at which Trial is placed to run.""" + + def __init__(self, hostname=None, pid=None): + self.hostname = hostname + self.pid = pid + + def __str__(self): + if not self.pid: + return "" + elif self.hostname == platform.node(): + return "pid={}".format(self.pid) + else: + return "{}:{}".format(self.hostname, self.pid) + + +@DeveloperAPI +class ExportFormat: + """Describes the format to import/export the trial Trainable. + + This may correspond to different file formats based on the + Trainable implementation. + """ + + CHECKPOINT = "checkpoint" + MODEL = "model" + ONNX = "onnx" + H5 = "h5" + + @staticmethod + def validate(formats): + """Validates formats. + + Raises: + ValueError: if the format is unknown. + """ + for i in range(len(formats)): + formats[i] = formats[i].strip().lower() + if formats[i] not in [ + ExportFormat.CHECKPOINT, + ExportFormat.MODEL, + ExportFormat.ONNX, + ExportFormat.H5, + ]: + raise TuneError("Unsupported import/export format: " + formats[i]) + + +class _TrialInfo: + """Serializable struct for holding information for a Trial. + + Attributes: + trial_name: String name of the current trial. + trial_id: trial_id of the trial + trial_resources: resources used by trial. + """ + + def __init__(self, trial: "Trial"): + self._trial_name = str(trial) + self._trial_id = trial.trial_id + self._trial_resources = trial.placement_group_factory + self._experiment_name = trial.experiment_dir_name + + @property + def experiment_name(self): + return self._experiment_name + + @property + def trial_name(self): + return self._trial_name + + @property + def trial_id(self): + return self._trial_id + + @property + def trial_resources(self) -> PlacementGroupFactory: + return self._trial_resources + + @trial_resources.setter + def trial_resources(self, new_resources: PlacementGroupFactory): + self._trial_resources = new_resources + + +class _TemporaryTrialState: + """Temporary trial state. + + Values saved here should not be restored on resume. + """ + + def __init__(self): + self.location = _Location() + + self.ray_actor: Optional[ray.actor.ActorHandle] = None + + self.saving_to: Optional[_FutureTrainingResult] = None + self.restoring_from: Optional[_TrainingResult] = None + + self.num_restore_failures: int = 0 + + def __getstate__(self): + return {} + + +def _get_max_path_length() -> int: + if hasattr(os, "pathconf"): + return os.pathconf("/", "PC_PATH_MAX") + # Windows + return _DEFAULT_WIN_MAX_PATH_LENGTH + + +def _create_unique_logdir_name(root: str, relative_logdir: str) -> str: + candidate = Path(root).expanduser().joinpath(relative_logdir) + if candidate.exists(): + relative_logdir_old = relative_logdir + relative_logdir += "_" + uuid.uuid4().hex[:4] + logger.info( + f"Creating a new dirname {relative_logdir} because " + f"trial dirname '{relative_logdir_old}' already exists." + ) + return relative_logdir + + +def _noop_logger_creator(config: Dict[str, Any], logdir: str): + # Upon remote process setup, record the actor's original working dir before + # changing to the Tune logdir + os.environ.setdefault("TUNE_ORIG_WORKING_DIR", os.getcwd()) + + os.makedirs(logdir, exist_ok=True) + + if bool(int(os.environ.get(RAY_CHDIR_TO_TRIAL_DIR, "1"))): + # Set the working dir to the trial directory in the remote process, + # for user file writes + if not ray._private.worker._mode() == ray._private.worker.LOCAL_MODE: + os.chdir(logdir) + + return NoopLogger(config, logdir) + + +def _get_trainable_kwargs(trial: "Trial") -> Dict[str, Any]: + trial.init_local_path() + + logger_creator = partial( + _noop_logger_creator, logdir=trial.storage.trial_working_directory + ) + + trial_config = copy.deepcopy(trial.config) + trial_config[TRIAL_INFO] = _TrialInfo(trial) + stdout_file, stderr_file = trial.log_to_file + trial_config[STDOUT_FILE] = stdout_file + trial_config[STDERR_FILE] = stderr_file + + assert trial.storage.trial_dir_name + + kwargs = { + "config": trial_config, + "logger_creator": logger_creator, + "storage": trial.storage, + } + + return kwargs + + +@contextmanager +def _change_working_directory(trial): + """Context manager changing working directory to trial logdir. + Used in local mode. + + For non-local mode it is no-op. + """ + if ray._private.worker._mode() == ray._private.worker.LOCAL_MODE: + old_dir = os.getcwd() + try: + os.chdir(trial.local_path) + yield + finally: + os.chdir(old_dir) + else: + yield + + +@DeveloperAPI +class Trial: + """A trial object holds the state for one model training run. + + Trials are themselves managed by the TrialRunner class, which implements + the event loop for submitting trial runs to a Ray cluster. + + Trials start in the PENDING state, and transition to RUNNING once started. + On error, it transitions to ERROR, otherwise TERMINATED on success. + + There are resources allocated to each trial. These should be specified + using ``PlacementGroupFactory``. + + Attributes: + trainable_name: Name of the trainable object to be executed. + config: Provided configuration dictionary with evaluated params. + trial_id: Unique identifier for the trial. + path: Path where results for this trial are stored. Can be on + the local node or on cloud storage. + local_path: Path on the local disk where results are stored. + remote_path: Path on cloud storage where results are stored, + or None if not set. + relative_logdir: Directory of the trial relative to its + experiment directory. + evaluated_params: Evaluated parameters by search algorithm, + experiment_tag: Identifying trial name to show in the console + status: One of PENDING, RUNNING, PAUSED, TERMINATED, ERROR/ + error_file: Path to the errors that this trial has raised. + + """ + + _nonjson_fields = [ + "results", + "extra_arg", + "placement_group_factory", + "_resources", + "_default_placement_group_factory", + ] + + PENDING = "PENDING" + RUNNING = "RUNNING" + PAUSED = "PAUSED" + TERMINATED = "TERMINATED" + ERROR = "ERROR" + + def __init__( + self, + trainable_name: str, + *, + config: Optional[Dict] = None, + trial_id: Optional[str] = None, + storage: Optional[StorageContext] = None, + evaluated_params: Optional[Dict] = None, + experiment_tag: str = "", + placement_group_factory: Optional[PlacementGroupFactory] = None, + stopping_criterion: Optional[Dict[str, float]] = None, + checkpoint_config: Optional[CheckpointConfig] = None, + export_formats: Optional[List[str]] = None, + restore_path: Optional[str] = None, + trial_name_creator: Optional[Callable[["Trial"], str]] = None, + trial_dirname_creator: Optional[Callable[["Trial"], str]] = None, + log_to_file: Union[Optional[str], Tuple[Optional[str], Optional[str]]] = None, + max_failures: int = 0, + stub: bool = False, + _setup_default_resource: bool = True, + ): + """Initialize a new trial. + + The args here take the same meaning as the command line flags defined + in ray.tune.experiment.config_parser. + + Args: + _setup_default_resource: Whether to set up default resources. + When initializing trials from checkpoints, this field is set to false, + so that setting up default resources can be delayed till after + ``trial.config`` is loaded from checkpoints. + """ + # If this is set, trainables are not validated or looked up. + # This can be used e.g. to initialize Trial objects from checkpoints + # without loading the trainable first. + self.stub = stub + + if not self.stub: + validate_trainable(trainable_name) + # Trial config + self.trainable_name = trainable_name + self.trial_id = Trial.generate_id() if trial_id is None else trial_id + + self.temporary_state = _TemporaryTrialState() + self.run_metadata = _TrainingRunMetadata() + + # Create a copy, since `init_local_path` updates the context with the + # generated trial dirname. + self.storage = copy.copy(storage) + + self.config = config or {} + # Save a copy of the original unresolved config so that we can swap + # out and update any reference config values after restoration. + self.__unresolved_config = self.config + + # Parameters that Tune varies across searches. + self.evaluated_params = evaluated_params or {} + self.experiment_tag = experiment_tag + self.stopping_criterion = stopping_criterion or {} + + self._setup_default_resource = _setup_default_resource + + if placement_group_factory and not isinstance( + placement_group_factory, PlacementGroupFactory + ): + placement_group_factory = resource_dict_to_pg_factory( + placement_group_factory + ) + + self._default_placement_group_factory = placement_group_factory + # Will be created in create_placement_group_factory(). + self.placement_group_factory = None + + self.log_to_file = log_to_file + # Make sure `stdout_file, stderr_file = Trial.log_to_file` works + if ( + not self.log_to_file + or not isinstance(self.log_to_file, Sequence) + or not len(self.log_to_file) == 2 + ): + self.log_to_file = (None, None) + + self.max_failures = max_failures + + # Local trial state that is updated during the run + self._default_result_or_future: Union[ray.ObjectRef, dict, None] = None + + self.export_formats = export_formats + self.status = Trial.PENDING + self.relative_logdir = None + + self.trial_name_creator = trial_name_creator + self.trial_dirname_creator = trial_dirname_creator + self.custom_trial_name = None + self.custom_dirname = None + + # Checkpoint config + checkpoint_config = checkpoint_config or CheckpointConfig() + + self.run_metadata.checkpoint_manager = _CheckpointManager( + checkpoint_config=checkpoint_config + ) + + # Restoration fields + self.restore_path = restore_path + self._restore_checkpoint_result: Optional[_TrainingResult] = None + if restore_path: + # tune.run(restore) passes in a path without metrics. + self._restore_checkpoint_result = _TrainingResult( + checkpoint=Checkpoint.from_directory(restore_path), metrics={} + ) + + if trial_name_creator: + self.custom_trial_name = trial_name_creator(self) + + if trial_dirname_creator: + self.custom_dirname = trial_dirname_creator(self) + if os.path.sep in self.custom_dirname: + raise ValueError( + f"Trial dirname must not contain '/'. Got {self.custom_dirname}" + ) + + self._state_json = None + + def create_placement_group_factory(self): + """Compute placement group factory if needed. + + Note: this must be called after all the placeholders in + self.config are resolved. + """ + trainable_cls = self.get_trainable_cls() + if not trainable_cls or not self._setup_default_resource: + # Create placement group factory using default resources. + self.placement_group_factory = ( + self._default_placement_group_factory or resource_dict_to_pg_factory() + ) + return + + default_resources = trainable_cls.default_resource_request(self.config) + + # If Trainable returns resources, do not allow manual override via + # `resources_per_trial` by the user. + if default_resources and self._default_placement_group_factory: + raise TuneError( + "Resources for {} have been automatically set to {} " + "by its `default_resource_request()` method. Please " + "clear the `resources_per_trial` option.".format( + trainable_cls, default_resources + ) + ) + + if default_resources and not isinstance( + default_resources, PlacementGroupFactory + ): + default_resources = resource_dict_to_pg_factory(default_resources) + + self.placement_group_factory = ( + # default_resource_request + default_resources + # resources_per_trial + or self._default_placement_group_factory + # cpu=1 + or resource_dict_to_pg_factory() + ) + + def _get_default_result_or_future(self) -> Optional[dict]: + """Calls ray.get on self._default_result_or_future and assigns back. + + Returns None in case of exceptions. + Will also set the trial location if runner is set. + """ + if self._default_result_or_future and isinstance( + self._default_result_or_future, ray.ObjectRef + ): + try: + self._default_result_or_future = ray.get(self._default_result_or_future) + except RayActorError: # error during initialization + self._default_result_or_future = None + if self._default_result_or_future and self.temporary_state.ray_actor: + self.set_location( + _Location( + self._default_result_or_future.get(NODE_IP), + self._default_result_or_future.get(PID), + ) + ) + return self._default_result_or_future + + def resolve_config_placeholders(self, placeholder_resolvers: Dict[Tuple, Any]): + from ray.tune.impl.placeholder import resolve_placeholders + + # Make a copy of the unresolved config before resolve it. + self.config = copy.deepcopy(self.__unresolved_config) + resolve_placeholders(self.config, placeholder_resolvers) + + @property + def last_result(self) -> dict: + # The logic in here is as follows: + # 1. If the trial has reported at least once, last_result would have + # been set and therefore would not be empty. We can just return it. + # 2. If the trial has not reported at least once but we have the + # future for the default results dict, (obtained through + # Trainable.get_auto_filled_metrics), we get that future + # and return it. + # 3. In the worst case where we have nothing, we just set the + # trial_id and return that. + result = self.run_metadata.last_result + if not {k for k in result if k != TRIAL_ID}: + self._get_default_result_or_future() + result = self._default_result_or_future or result + result.setdefault(TRIAL_ID, self.trial_id) + return result + + @property + def metric_analysis(self): + return self.run_metadata.metric_analysis + + @property + def metric_n_steps(self): + return self.run_metadata.metric_n_steps + + def get_ray_actor_ip(self) -> Optional[str]: + if self.temporary_state.location.hostname: + return self.temporary_state.location.hostname + + if not self.temporary_state.ray_actor: + return None + + hostname, pid = ray.get( + self.temporary_state.ray_actor.get_current_ip_pid.remote() + ) + self.temporary_state.location = _Location(hostname, pid) + return self.temporary_state.location.hostname + + @property + @Deprecated("Replaced by `local_experiment_path`") + def local_dir(self): + return self.local_experiment_path + + @property + def experiment_dir_name(self): + return self.storage.experiment_dir_name + + @property + def remote_experiment_path(self) -> str: + return self.storage.experiment_fs_path + + @property + def local_experiment_path(self) -> str: + return self.storage.experiment_driver_staging_path + + @property + @Deprecated("Replaced by `local_path`") + def logdir(self) -> Optional[str]: + # TODO(justinvyu): [Deprecated] Remove in 2.11. + raise DeprecationWarning("Use `local_path` instead of `logdir`.") + + @property + def local_path(self) -> Optional[str]: + return self.storage.trial_driver_staging_path + + @property + def path(self) -> Optional[str]: + return self.storage.trial_fs_path + + @property + def has_reported_at_least_once(self) -> bool: + return bool(self.run_metadata.last_result) + + @property + def node_ip(self): + return self.temporary_state.location.hostname + + @property + def checkpoint_at_end(self): + config = self.run_metadata.checkpoint_manager.checkpoint_config + return config.checkpoint_at_end + + @property + def checkpoint_freq(self): + config = self.run_metadata.checkpoint_manager.checkpoint_config + return config.checkpoint_frequency + + @property + def latest_checkpoint_result(self) -> Optional[_TrainingResult]: + # NOTE: Fallback to the checkpoint passed in from `tune.run(restore)` + # if the trial hasn't saved any checkpoints itself yet. + return ( + self.run_metadata.checkpoint_manager.latest_checkpoint_result + or self._restore_checkpoint_result + ) + + @property + def checkpoint(self) -> Optional[Checkpoint]: + """Returns the most recent checkpoint if one has been saved.""" + return ( + self.latest_checkpoint_result.checkpoint + if self.latest_checkpoint_result + else None + ) + + @classmethod + def generate_id(cls): + return str(uuid.uuid4().hex)[:8] + + def reset(self) -> "Trial": + # If there is `default_resource_request` associated with the trainable, + # clear `resources` and `placement_group_factory`. + # This is mainly relevant for RLlib tuning jobs, where we save users + # of the trouble to specify the resources themselves by having some + # default resources for popular RLlib algorithms. + trainable_cls = self.get_trainable_cls() + clear_resources = trainable_cls and trainable_cls.default_resource_request( + self.config + ) + placement_group_factory = ( + self.placement_group_factory if not clear_resources else None + ) + + checkpoint_config = self.run_metadata.checkpoint_manager.checkpoint_config + return Trial( + self.trainable_name, + config=self.config, + trial_id=None, + evaluated_params=self.evaluated_params, + experiment_tag=self.experiment_tag, + placement_group_factory=placement_group_factory, + stopping_criterion=self.stopping_criterion, + checkpoint_config=checkpoint_config, + export_formats=self.export_formats, + restore_path=self.restore_path, + trial_name_creator=self.trial_name_creator, + trial_dirname_creator=self.trial_dirname_creator, + log_to_file=self.log_to_file, + max_failures=self.max_failures, + storage=self.storage, + ) + + @Deprecated("Replaced by `init_local_path()`") + def init_logdir(self): + # TODO(justinvyu): [Deprecated] Remove in 2.11. + raise DeprecationWarning("Use `init_local_path` instead of `init_logdir`.") + + def init_local_path(self): + """Init logdir.""" + if not self.relative_logdir: + self.relative_logdir = _create_unique_logdir_name( + str(self.local_experiment_path), self._generate_dirname() + ) + # Populate the storage context with the trial dir name we just generated. + self.storage.trial_dir_name = self.relative_logdir + + assert self.local_path + logdir_path = Path(self.local_path) + max_path_length = _get_max_path_length() + if len(str(logdir_path)) >= max_path_length: + logger.warning( + f"The path to the trial log directory is too long " + f"(max length: {max_path_length}. " + f"Consider using `trial_dirname_creator` to shorten the path. " + f"Path: {logdir_path}" + ) + logdir_path.mkdir(parents=True, exist_ok=True) + + self.invalidate_json_state() + + def update_resources(self, resources: Union[dict, PlacementGroupFactory]): + """EXPERIMENTAL: Updates the resource requirements. + + Should only be called when the trial is not running. + + Raises: + ValueError: if trial status is running. + """ + if self.status is Trial.RUNNING: + raise ValueError("Cannot update resources while Trial is running.") + + placement_group_factory = resources + if isinstance(resources, dict): + placement_group_factory = resource_dict_to_pg_factory(resources) + + self.placement_group_factory = placement_group_factory + + self.invalidate_json_state() + + def set_ray_actor(self, ray_actor): + self.temporary_state.ray_actor = ray_actor + if ray_actor: + # Do not block here, the result will be gotten when last_result + # property is accessed + self._default_result_or_future = ray_actor.get_auto_filled_metrics.remote( + debug_metrics_only=True + ) + + def set_location(self, location): + """Sets the location of the trial.""" + self.temporary_state.location = location + + def set_status(self, status): + """Sets the status of the trial.""" + self.status = status + if status == Trial.RUNNING: + if self.run_metadata.start_time is None: + self.run_metadata.start_time = time.time() + self.invalidate_json_state() + + def set_config(self, config): + self.config = config + self.invalidate_json_state() + + def set_experiment_tag(self, experiment_tag): + self.experiment_tag = experiment_tag + self.invalidate_json_state() + + def set_storage(self, new_storage: StorageContext): + """Updates the storage context of the trial. + + If the `storage_path` or `experiment_dir_name` has changed, then this setter + also updates the paths of all checkpoints tracked by the checkpoint manager. + This enables restoration from a checkpoint if the user moves the directory. + """ + original_storage = self.storage + + checkpoint_manager = self.run_metadata.checkpoint_manager + + for checkpoint_result in checkpoint_manager.best_checkpoint_results: + checkpoint_result.checkpoint = Checkpoint( + path=checkpoint_result.checkpoint.path.replace( + original_storage.trial_fs_path, new_storage.trial_fs_path, 1 + ), + filesystem=new_storage.storage_filesystem, + ) + latest_checkpoint_result = checkpoint_manager.latest_checkpoint_result + if latest_checkpoint_result: + latest_checkpoint_result.checkpoint = Checkpoint( + path=latest_checkpoint_result.checkpoint.path.replace( + original_storage.trial_fs_path, new_storage.trial_fs_path, 1 + ), + filesystem=new_storage.storage_filesystem, + ) + + self.storage = new_storage + self.invalidate_json_state() + + @property + def num_failures(self): + return self.run_metadata.num_failures + + @property + def num_failures_after_restore(self): + return self.run_metadata.num_failures_after_restore + + @property + def error_file(self): + if not self.local_path or not self.run_metadata.error_filename: + return None + return Path(self.local_path, self.run_metadata.error_filename).as_posix() + + @property + def pickled_error_file(self): + if not self.local_path or not self.run_metadata.pickled_error_filename: + return None + return Path( + self.local_path, self.run_metadata.pickled_error_filename + ).as_posix() + + def get_pickled_error(self) -> Optional[Exception]: + """Returns the pickled error object if it exists in storage. + + This is a pickled version of the latest error that the trial encountered. + """ + error_filename = self.run_metadata.pickled_error_filename + if error_filename is None: + return None + + fs = self.storage.storage_filesystem + pickled_error_fs_path = Path( + self.storage.trial_fs_path, error_filename + ).as_posix() + + if _exists_at_fs_path(fs=fs, fs_path=pickled_error_fs_path): + with fs.open_input_stream(pickled_error_fs_path) as f: + return cloudpickle.loads(f.readall()) + return None + + def get_error(self) -> Optional[TuneError]: + """Returns the error text file trace as a TuneError object + if it exists in storage. + + This is a text trace of the latest error that the trial encountered, + which is used in the case that the error is not picklable. + """ + error_filename = self.run_metadata.error_filename + if error_filename is None: + return None + + fs = self.storage.storage_filesystem + txt_error_fs_path = Path(self.storage.trial_fs_path, error_filename).as_posix() + + if _exists_at_fs_path(fs=fs, fs_path=txt_error_fs_path): + with fs.open_input_stream(txt_error_fs_path) as f: + return f.readall().decode() + return None + + def _handle_restore_error(self, exc: Exception): + # For Restoration errors, we only increment the restore failure count + # if the number of failures exceeds the restore retry limit. + if self.temporary_state.num_restore_failures >= int( + os.environ.get("TUNE_RESTORE_RETRY_NUM", 0) + ): + self.run_metadata.num_failures += 1 + else: + self.temporary_state.num_restore_failures += 1 + + def _handle_ray_actor_error(self, exc: RayActorError): + count_preemption_errors = bool( + int(os.environ.get(RAY_TRAIN_COUNT_PREEMPTION_AS_FAILURE, "0")) + ) + if not exc.preempted or count_preemption_errors: + # Only count non-preempted actor errors as failures. + self.run_metadata.num_failures += 1 + + def _handle_ray_task_error(self, exc: RayTaskError): + cause = exc.as_instanceof_cause() + if isinstance(cause, RayActorError): + # Handle the RayActorError directly (ex: Ray Train worker actor errors) + return self._handle_ray_actor_error(cause) + + # Increment failures for all user errors (which get raised as RayTaskError) + self.run_metadata.num_failures += 1 + + def handle_error( + self, exc: Optional[Union[TuneError, RayTaskError, RayActorError]] = None + ): + if self.is_restoring: + self._handle_restore_error(exc) + elif isinstance(exc, RayActorError): + self._handle_ray_actor_error(exc) + elif isinstance(exc, RayTaskError): + self._handle_ray_task_error(exc) + else: + self.run_metadata.num_failures += 1 + + if self.local_path: + self.run_metadata.error_filename = EXPR_ERROR_FILE + if isinstance(exc, (RayTaskError, RayActorError)): + # Piping through the actual error to result grid. + self.run_metadata.pickled_error_filename = EXPR_ERROR_PICKLE_FILE + with open(self.pickled_error_file, "wb") as f: + cloudpickle.dump(exc, f) + with open(self.error_file, "a+") as f: + f.write( + "Failure # {} (occurred at {})\n".format( + self.run_metadata.num_failures, date_str() + ) + ) + f.write(str(exc) + "\n") + self.run_metadata.invalidate_cache() + + def should_stop(self, result): + """Whether the given result meets this trial's stopping criteria.""" + if result.get(DONE): + return True + + for criterion, stop_value in self.stopping_criterion.items(): + if isinstance(criterion, dict): + raise ValueError( + "Stopping criteria is now flattened by default. " + "Use forward slashes to nest values `key1/key2/key3`." + ) + elif criterion not in result: + if log_once("tune_trial_stop_criterion_not_found"): + logger.warning( + f"Stopping criterion '{criterion}' not found in result dict! " + f"Available keys are {list(result.keys())}. If '{criterion}' is" + " never reported, the run will continue until training is " + "finished." + ) + elif result[criterion] >= stop_value: + return True + return False + + def should_checkpoint(self): + """Whether this trial is due for checkpointing.""" + result = self.last_result or {} + if result.get(DONE) and self.checkpoint_at_end: + return True + return ( + self.checkpoint_freq + and result.get(TRAINING_ITERATION, 0) % self.checkpoint_freq == 0 + ) + + def has_checkpoint(self) -> bool: + return self.checkpoint is not None + + def on_checkpoint(self, checkpoint_result: _TrainingResult): + """Hook for handling checkpoints taken by the Trainable. + + Args: + checkpoint: Checkpoint taken. + """ + self.run_metadata.checkpoint_manager.register_checkpoint(checkpoint_result) + # Update the checkpoint index to keep the checkpoint index in sync. + # This index will get restored when the trial is restored and will + # be passed to the Trainable as the starting checkpoint index. + self.storage._update_checkpoint_index(checkpoint_result.metrics) + + self.invalidate_json_state() + self.run_metadata.invalidate_cache() + + def on_restore(self): + """Handles restoration completion.""" + assert self.is_restoring + self.run_metadata.last_result = self.temporary_state.restoring_from.metrics + self.run_metadata.last_result.setdefault("config", self.config) + self.temporary_state.restoring_from = None + self.temporary_state.num_restore_failures = 0 + + def should_recover(self): + """Returns whether the trial qualifies for retrying. + + `num_failures` should represent the number of times the trial has + failed *up to the moment this method is called.* If we've failed + 5 times and `max_failures=5`, then we should recover, since + we only pass the limit on the 6th failure. + + Note this may return true even when there is no checkpoint, either because + `self.checkpoint_freq` is `0` or because the trial failed before + a checkpoint has been made. + """ + return ( + self.run_metadata.num_failures <= self.max_failures or self.max_failures < 0 + ) + + def update_last_result(self, result): + if self.experiment_tag: + result.update(experiment_tag=self.experiment_tag) + + self.set_location(_Location(result.get(NODE_IP), result.get(PID))) + self.run_metadata.last_result = result + self.run_metadata.last_result_time = time.time() + + metric_result = self.last_result.copy() + for remove_metric in DEBUG_METRICS: + metric_result.pop(remove_metric, None) + + for metric, value in flatten_dict(metric_result).items(): + if isinstance(value, Number): + self.run_metadata.update_metric( + metric, value, step=result.get("training_iteration") + ) + + def get_trainable_cls(self): + if self.stub: + return None + return get_trainable_cls(self.trainable_name) + + def is_finished(self): + return self.status in [Trial.ERROR, Trial.TERMINATED] + + @property + def is_restoring(self): + return self.temporary_state.restoring_from is not None + + @property + def is_saving(self): + return self.temporary_state.saving_to is not None + + def __repr__(self): + return self._trainable_name(include_trial_id=True) + + def __str__(self): + return self._trainable_name(include_trial_id=True) + + def _trainable_name(self, include_trial_id=False): + """Combines ``env`` with ``trainable_name`` and ``trial_id``. + + Can be overridden with a custom string creator. + """ + if self.custom_trial_name: + return self.custom_trial_name + + if "env" in self.config: + env = self.config["env"] + if isinstance(env, type): + env = env.__name__ + identifier = "{}_{}".format(self.trainable_name, env) + else: + identifier = self.trainable_name + if include_trial_id: + identifier += "_" + self.trial_id + return identifier.replace("/", "_") + + def _generate_dirname(self): + if self.custom_dirname: + generated_dirname = self.custom_dirname + else: + MAX_LEN_IDENTIFIER = int(os.environ.get("TUNE_MAX_LEN_IDENTIFIER", "130")) + generated_dirname = f"{str(self)}_{self.experiment_tag}" + generated_dirname = generated_dirname[:MAX_LEN_IDENTIFIER] + generated_dirname += f"_{date_str()}" + # This is the file path used by rsync. ['/', '(', ')'] are not allowed. + return re.sub("[/()]", "_", generated_dirname) + + def invalidate_json_state(self): + self._state_json = None + + def get_json_state(self) -> Tuple[str, str]: + if self._state_json is None: + state = self.__getstate__() + state.pop("run_metadata", None) + self._state_json = json.dumps(state, indent=2, cls=TuneFunctionEncoder) + + runtime_metadata_json = self.run_metadata.get_json_state() + + return self._state_json, runtime_metadata_json + + @classmethod + def from_json_state(cls, json_state: str, stub: bool = False) -> "Trial": + state = json.loads(json_state, cls=TuneFunctionDecoder) + + new_trial = Trial( + state["trainable_name"], + stub=stub, + _setup_default_resource=False, + ) + + new_trial.__setstate__(state) + + return new_trial + + def restore_run_metadata(self, run_metadata: str): + self.run_metadata = _TrainingRunMetadata.from_json_state(run_metadata) + + @classmethod + def from_directory( + cls, path: Union[str, os.PathLike], stub: bool = False + ) -> "Trial": + metadata_path = Path(path, TRIAL_STATE_FILENAME) + if not metadata_path.exists(): + raise FileNotFoundError( + f"Can't restore trial from path: File `{metadata_path}` not found." + ) + + json_state = metadata_path.read_text() + return cls.from_json_state(json_state, stub=stub) + + def __getstate__(self): + """Memento generator for Trial. + + Sets RUNNING trials to PENDING. + Note this can only occur if the trial holds a PERSISTENT checkpoint. + """ + state = self.__dict__.copy() + + for key in self._nonjson_fields: + state[key] = binary_to_hex(cloudpickle.dumps(state.get(key))) + + state.pop("temporary_state", None) + + state["_state_json"] = None + state["_default_result_or_future"] = None + + return state + + def __setstate__(self, state): + if state["status"] == Trial.RUNNING: + state["status"] = Trial.PENDING + for key in self._nonjson_fields: + if key in state: + state[key] = cloudpickle.loads(hex_to_binary(state[key])) + + # Ensure that stub doesn't get overriden + stub = state.pop("stub", True) + self.__dict__.update(state) + self.stub = stub or getattr(self, "stub", False) + + if not self.stub: + validate_trainable(self.trainable_name) + + self.temporary_state = _TemporaryTrialState() + + assert self.placement_group_factory diff --git a/venv/lib/python3.10/site-packages/ray/tune/experimental/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/tune/experimental/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/experimental/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d642bdd868366c256c41842dadbcc99de2a7e70d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/experimental/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/experimental/__pycache__/output.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/experimental/__pycache__/output.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27b48be0d9217c30351fac1f7186db70ee48662f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/experimental/__pycache__/output.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/experimental/output.py b/venv/lib/python3.10/site-packages/ray/tune/experimental/output.py new file mode 100644 index 0000000000000000000000000000000000000000..271bd5529f02c1b45a2e9b536bba26a25c824cce --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/experimental/output.py @@ -0,0 +1,1043 @@ +import argparse +import collections +import datetime +import logging +import math +import numbers +import os +import sys +import textwrap +import time +from dataclasses import dataclass +from enum import IntEnum +from typing import Any, Collection, Dict, Iterable, List, Optional, Tuple, Union + +import numpy as np +import pandas as pd + +import ray +from ray._private.dict import flatten_dict, unflattened_lookup +from ray._private.thirdparty.tabulate.tabulate import ( + DataRow, + Line, + TableFormat, + tabulate, +) +from ray.air._internal.usage import AirEntrypoint +from ray.air.constants import TRAINING_ITERATION +from ray.tune import Checkpoint +from ray.tune.callback import Callback +from ray.tune.experiment.trial import Trial +from ray.tune.result import ( + AUTO_RESULT_KEYS, + EPISODE_REWARD_MEAN, + MEAN_ACCURACY, + MEAN_LOSS, + TIME_TOTAL_S, + TIMESTEPS_TOTAL, +) +from ray.tune.search.sample import Domain +from ray.tune.utils.log import Verbosity + +try: + import rich + import rich.layout + import rich.live +except ImportError: + rich = None + + +logger = logging.getLogger(__name__) + +# defines the mapping of the key in result and the key to be printed in table. +# Note this is ordered! +DEFAULT_COLUMNS = collections.OrderedDict( + { + MEAN_ACCURACY: "acc", + MEAN_LOSS: "loss", + TRAINING_ITERATION: "iter", + TIME_TOTAL_S: "total time (s)", + TIMESTEPS_TOTAL: "ts", + EPISODE_REWARD_MEAN: "reward", + } +) + +# These keys are blacklisted for printing out training/tuning intermediate/final result! +BLACKLISTED_KEYS = { + "config", + "date", + "done", + "hostname", + "iterations_since_restore", + "node_ip", + "pid", + "time_since_restore", + "timestamp", + "trial_id", + "experiment_tag", + "should_checkpoint", + "_report_on", # LIGHTNING_REPORT_STAGE_KEY +} + +VALID_SUMMARY_TYPES = { + int, + float, + np.float32, + np.float64, + np.int32, + np.int64, + type(None), +} + +# The order of summarizing trials. +ORDER = [ + Trial.RUNNING, + Trial.TERMINATED, + Trial.PAUSED, + Trial.PENDING, + Trial.ERROR, +] + + +class AirVerbosity(IntEnum): + SILENT = 0 + DEFAULT = 1 + VERBOSE = 2 + + def __repr__(self): + return str(self.value) + + +IS_NOTEBOOK = ray.widgets.util.in_notebook() + + +def get_air_verbosity( + verbose: Union[int, AirVerbosity, Verbosity] +) -> Optional[AirVerbosity]: + if os.environ.get("RAY_AIR_NEW_OUTPUT", "1") == "0": + return None + + if isinstance(verbose, AirVerbosity): + return verbose + + verbose_int = verbose if isinstance(verbose, int) else verbose.value + + # Verbosity 2 and 3 both map to AirVerbosity 2 + verbose_int = min(2, verbose_int) + + return AirVerbosity(verbose_int) + + +def _infer_params(config: Dict[str, Any]) -> List[str]: + params = [] + flat_config = flatten_dict(config) + for key, val in flat_config.items(): + if isinstance(val, Domain): + params.append(key) + # Grid search is a special named field. Because we flattened + # the whole config, we look it up per string + if key.endswith("/grid_search"): + # Truncate `/grid_search` + params.append(key[:-12]) + return params + + +def _get_time_str(start_time: float, current_time: float) -> Tuple[str, str]: + """Get strings representing the current and elapsed time. + + Args: + start_time: POSIX timestamp of the start of the tune run + current_time: POSIX timestamp giving the current time + + Returns: + Current time and elapsed time for the current run + """ + current_time_dt = datetime.datetime.fromtimestamp(current_time) + start_time_dt = datetime.datetime.fromtimestamp(start_time) + delta: datetime.timedelta = current_time_dt - start_time_dt + + rest = delta.total_seconds() + days = int(rest // (60 * 60 * 24)) + + rest -= days * (60 * 60 * 24) + hours = int(rest // (60 * 60)) + + rest -= hours * (60 * 60) + minutes = int(rest // 60) + + seconds = int(rest - minutes * 60) + + running_for_str = "" + if days > 0: + running_for_str += f"{days:d}d " + + if hours > 0 or running_for_str: + running_for_str += f"{hours:d}hr " + + if minutes > 0 or running_for_str: + running_for_str += f"{minutes:d}min " + + running_for_str += f"{seconds:d}s" + + return f"{current_time_dt:%Y-%m-%d %H:%M:%S}", running_for_str + + +def _get_trials_by_state(trials: List[Trial]) -> Dict[str, List[Trial]]: + trials_by_state = collections.defaultdict(list) + for t in trials: + trials_by_state[t.status].append(t) + return trials_by_state + + +def _get_trials_with_error(trials: List[Trial]) -> List[Trial]: + return [t for t in trials if t.error_file] + + +def _infer_user_metrics(trials: List[Trial], limit: int = 4) -> List[str]: + """Try to infer the metrics to print out. + + By default, only the first 4 meaningful metrics in `last_result` will be + inferred as user implied metrics. + """ + # Using OrderedDict for OrderedSet. + result = collections.OrderedDict() + for t in trials: + if not t.last_result: + continue + for metric, value in t.last_result.items(): + if metric not in DEFAULT_COLUMNS: + if metric not in AUTO_RESULT_KEYS: + if type(value) in VALID_SUMMARY_TYPES: + result[metric] = "" # not important + + if len(result) >= limit: + return list(result.keys()) + return list(result.keys()) + + +def _current_best_trial( + trials: List[Trial], metric: Optional[str], mode: Optional[str] +) -> Tuple[Optional[Trial], Optional[str]]: + """ + Returns the best trial and the metric key. If anything is empty or None, + returns a trivial result of None, None. + + Args: + trials: List of trials. + metric: Metric that trials are being ranked. + mode: One of "min" or "max". + + Returns: + Best trial and the metric key. + """ + if not trials or not metric or not mode: + return None, None + + metric_op = 1.0 if mode == "max" else -1.0 + best_metric = float("-inf") + best_trial = None + for t in trials: + if not t.last_result: + continue + metric_value = unflattened_lookup(metric, t.last_result, default=None) + if pd.isnull(metric_value): + continue + if not best_trial or metric_value * metric_op > best_metric: + best_metric = metric_value * metric_op + best_trial = t + return best_trial, metric + + +@dataclass +class _PerStatusTrialTableData: + trial_infos: List[List[str]] + more_info: str + + +@dataclass +class _TrialTableData: + header: List[str] + data: List[_PerStatusTrialTableData] + + +def _max_len(value: Any, max_len: int = 20, wrap: bool = False) -> Any: + """Abbreviate a string representation of an object to `max_len` characters. + + For numbers, booleans and None, the original value will be returned for + correct rendering in the table formatting tool. + + Args: + value: Object to be represented as a string. + max_len: Maximum return string length. + """ + if value is None or isinstance(value, (int, float, numbers.Number, bool)): + return value + + string = str(value) + if len(string) <= max_len: + return string + + if wrap: + # Maximum two rows. + # Todo: Make this configurable in the refactor + if len(value) > max_len * 2: + value = "..." + string[(3 - (max_len * 2)) :] + + wrapped = textwrap.wrap(value, width=max_len) + return "\n".join(wrapped) + + result = "..." + string[(3 - max_len) :] + return result + + +def _get_trial_info( + trial: Trial, param_keys: List[str], metric_keys: List[str] +) -> List[str]: + """Returns the following information about a trial: + + name | status | metrics... + + Args: + trial: Trial to get information for. + param_keys: Names of parameters to include. + metric_keys: Names of metrics to include. + """ + result = trial.last_result + trial_info = [str(trial), trial.status] + + # params + trial_info.extend( + [ + _max_len( + unflattened_lookup(param, trial.config, default=None), + ) + for param in param_keys + ] + ) + # metrics + trial_info.extend( + [ + _max_len( + unflattened_lookup(metric, result, default=None), + ) + for metric in metric_keys + ] + ) + return trial_info + + +def _get_trial_table_data_per_status( + status: str, + trials: List[Trial], + param_keys: List[str], + metric_keys: List[str], + force_max_rows: bool = False, +) -> Optional[_PerStatusTrialTableData]: + """Gather all information of trials pertained to one `status`. + + Args: + status: The trial status of interest. + trials: all the trials of that status. + param_keys: *Ordered* list of parameters to be displayed in the table. + metric_keys: *Ordered* list of metrics to be displayed in the table. + Including both default and user defined. + force_max_rows: Whether or not to enforce a max row number for this status. + If True, only a max of `5` rows will be shown. + + Returns: + All information of trials pertained to the `status`. + """ + # TODO: configure it. + max_row = 5 if force_max_rows else math.inf + if not trials: + return None + + trial_infos = list() + more_info = None + for t in trials: + if len(trial_infos) >= max_row: + remaining = len(trials) - max_row + more_info = f"{remaining} more {status}" + break + trial_infos.append(_get_trial_info(t, param_keys, metric_keys)) + return _PerStatusTrialTableData(trial_infos, more_info) + + +def _get_trial_table_data( + trials: List[Trial], + param_keys: List[str], + metric_keys: List[str], + all_rows: bool = False, + wrap_headers: bool = False, +) -> _TrialTableData: + """Generate a table showing the current progress of tuning trials. + + Args: + trials: List of trials for which progress is to be shown. + param_keys: Ordered list of parameters to be displayed in the table. + metric_keys: Ordered list of metrics to be displayed in the table. + Including both default and user defined. + Will only be shown if at least one trial is having the key. + all_rows: Force to show all rows. + wrap_headers: If True, header columns can be wrapped with ``\n``. + + Returns: + Trial table data, including header and trial table per each status. + """ + # TODO: configure + max_trial_num_to_show = 20 + max_column_length = 20 + trials_by_state = _get_trials_by_state(trials) + + # get the right metric to show. + metric_keys = [ + k + for k in metric_keys + if any( + unflattened_lookup(k, t.last_result, default=None) is not None + for t in trials + ) + ] + + # get header from metric keys + formatted_metric_columns = [ + _max_len(k, max_len=max_column_length, wrap=wrap_headers) for k in metric_keys + ] + + formatted_param_columns = [ + _max_len(k, max_len=max_column_length, wrap=wrap_headers) for k in param_keys + ] + + metric_header = [ + DEFAULT_COLUMNS[metric] if metric in DEFAULT_COLUMNS else formatted + for metric, formatted in zip(metric_keys, formatted_metric_columns) + ] + + param_header = formatted_param_columns + + # Map to the abbreviated version if necessary. + header = ["Trial name", "status"] + param_header + metric_header + + trial_data = list() + for t_status in ORDER: + trial_data_per_status = _get_trial_table_data_per_status( + t_status, + trials_by_state[t_status], + param_keys=param_keys, + metric_keys=metric_keys, + force_max_rows=not all_rows and len(trials) > max_trial_num_to_show, + ) + if trial_data_per_status: + trial_data.append(trial_data_per_status) + return _TrialTableData(header, trial_data) + + +def _best_trial_str( + trial: Trial, + metric: str, +): + """Returns a readable message stating the current best trial.""" + # returns something like + # Current best trial: 18ae7_00005 with loss=0.5918508041056858 and params={'train_loop_config': {'lr': 0.059253447253394785}}. # noqa + val = unflattened_lookup(metric, trial.last_result, default=None) + config = trial.last_result.get("config", {}) + parameter_columns = list(config.keys()) + params = {p: unflattened_lookup(p, config) for p in parameter_columns} + return ( + f"Current best trial: {trial.trial_id} with {metric}={val} and " + f"params={params}" + ) + + +def _render_table_item( + key: str, item: Any, prefix: str = "" +) -> Iterable[Tuple[str, str]]: + key = prefix + key + + if isinstance(item, argparse.Namespace): + item = item.__dict__ + + if isinstance(item, float): + # tabulate does not work well with mixed-type columns, so we format + # numbers ourselves. + yield key, f"{item:.5f}".rstrip("0") + elif isinstance(item, dict): + flattened = flatten_dict(item) + for k, v in sorted(flattened.items()): + yield key + "/" + str(k), _max_len(v) + else: + yield key, _max_len(item, 20) + + +def _get_dict_as_table_data( + data: Dict, + include: Optional[Collection] = None, + exclude: Optional[Collection] = None, + upper_keys: Optional[Collection] = None, +): + """Get ``data`` dict as table rows. + + If specified, excluded keys are removed. Excluded keys can either be + fully specified (e.g. ``foo/bar/baz``) or specify a top-level dictionary + (e.g. ``foo``), but no intermediate levels (e.g. ``foo/bar``). If this is + needed, we can revisit the logic at a later point. + + The same is true for included keys. If a top-level key is included (e.g. ``foo``) + then all sub keys will be included, too, except if they are excluded. + + If keys are both excluded and included, exclusion takes precedence. Thus, if + ``foo`` is excluded but ``foo/bar`` is included, it won't show up in the output. + """ + include = include or set() + exclude = exclude or set() + upper_keys = upper_keys or set() + + upper = [] + lower = [] + + for key, value in sorted(data.items()): + # Exclude top-level keys + if key in exclude: + continue + + for k, v in _render_table_item(str(key), value): + # k is now the full subkey, e.g. config/nested/key + + # We can exclude the full key + if k in exclude: + continue + + # If we specify includes, top-level includes should take precedence + # (e.g. if `config` is in include, include config always). + if include and key not in include and k not in include: + continue + + if key in upper_keys: + upper.append([k, v]) + else: + lower.append([k, v]) + + if not upper: + return lower + elif not lower: + return upper + else: + return upper + lower + + +if sys.stdout and sys.stdout.encoding and sys.stdout.encoding.startswith("utf"): + # Copied/adjusted from tabulate + AIR_TABULATE_TABLEFMT = TableFormat( + lineabove=Line("╭", "─", "─", "╮"), + linebelowheader=Line("├", "─", "─", "┤"), + linebetweenrows=None, + linebelow=Line("╰", "─", "─", "╯"), + headerrow=DataRow("│", " ", "│"), + datarow=DataRow("│", " ", "│"), + padding=1, + with_header_hide=None, + ) +else: + # For non-utf output, use ascii-compatible characters. + # This prevents errors e.g. when legacy windows encoding is used. + AIR_TABULATE_TABLEFMT = TableFormat( + lineabove=Line("+", "-", "-", "+"), + linebelowheader=Line("+", "-", "-", "+"), + linebetweenrows=None, + linebelow=Line("+", "-", "-", "+"), + headerrow=DataRow("|", " ", "|"), + datarow=DataRow("|", " ", "|"), + padding=1, + with_header_hide=None, + ) + + +def _print_dict_as_table( + data: Dict, + header: Optional[str] = None, + include: Optional[Collection[str]] = None, + exclude: Optional[Collection[str]] = None, + division: Optional[Collection[str]] = None, +): + table_data = _get_dict_as_table_data( + data=data, include=include, exclude=exclude, upper_keys=division + ) + + headers = [header, ""] if header else [] + + if not table_data: + return + + print( + tabulate( + table_data, + headers=headers, + colalign=("left", "right"), + tablefmt=AIR_TABULATE_TABLEFMT, + ) + ) + + +class ProgressReporter(Callback): + """Periodically prints out status update.""" + + # TODO: Make this configurable + _heartbeat_freq = 30 # every 30 sec + # to be updated by subclasses. + _heartbeat_threshold = None + _start_end_verbosity = None + _intermediate_result_verbosity = None + _addressing_tmpl = None + + def __init__( + self, + verbosity: AirVerbosity, + progress_metrics: Optional[Union[List[str], List[Dict[str, str]]]] = None, + ): + """ + + Args: + verbosity: AirVerbosity level. + """ + self._verbosity = verbosity + self._start_time = time.time() + self._last_heartbeat_time = float("-inf") + self._start_time = time.time() + self._progress_metrics = progress_metrics + self._trial_last_printed_results = {} + + self._in_block = None + + @property + def verbosity(self) -> AirVerbosity: + return self._verbosity + + def setup( + self, + start_time: Optional[float] = None, + **kwargs, + ): + self._start_time = start_time + + def _start_block(self, indicator: Any): + if self._in_block != indicator: + self._end_block() + self._in_block = indicator + + def _end_block(self): + if self._in_block: + print("") + self._in_block = None + + def on_experiment_end(self, trials: List["Trial"], **info): + self._end_block() + + def experiment_started( + self, + experiment_name: str, + experiment_path: str, + searcher_str: str, + scheduler_str: str, + total_num_samples: int, + tensorboard_path: Optional[str] = None, + **kwargs, + ): + self._start_block("exp_start") + print(f"\nView detailed results here: {experiment_path}") + + if tensorboard_path: + print( + f"To visualize your results with TensorBoard, run: " + f"`tensorboard --logdir {tensorboard_path}`" + ) + + @property + def _time_heartbeat_str(self): + current_time_str, running_time_str = _get_time_str( + self._start_time, time.time() + ) + return ( + f"Current time: {current_time_str}. Total running time: " + running_time_str + ) + + def print_heartbeat(self, trials, *args, force: bool = False): + if self._verbosity < self._heartbeat_threshold: + return + if force or time.time() - self._last_heartbeat_time >= self._heartbeat_freq: + self._print_heartbeat(trials, *args, force=force) + self._last_heartbeat_time = time.time() + + def _print_heartbeat(self, trials, *args, force: bool = False): + raise NotImplementedError + + def _print_result(self, trial, result: Optional[Dict] = None, force: bool = False): + """Only print result if a different result has been reported, or force=True""" + result = result or trial.last_result + + last_result_iter = self._trial_last_printed_results.get(trial.trial_id, -1) + this_iter = result.get(TRAINING_ITERATION, 0) + + if this_iter != last_result_iter or force: + _print_dict_as_table( + result, + header=f"{self._addressing_tmpl.format(trial)} result", + include=self._progress_metrics, + exclude=BLACKLISTED_KEYS, + division=AUTO_RESULT_KEYS, + ) + self._trial_last_printed_results[trial.trial_id] = this_iter + + def _print_config(self, trial): + _print_dict_as_table( + trial.config, header=f"{self._addressing_tmpl.format(trial)} config" + ) + + def on_trial_result( + self, + iteration: int, + trials: List[Trial], + trial: Trial, + result: Dict, + **info, + ): + if self.verbosity < self._intermediate_result_verbosity: + return + self._start_block(f"trial_{trial}_result_{result[TRAINING_ITERATION]}") + curr_time_str, running_time_str = _get_time_str(self._start_time, time.time()) + print( + f"{self._addressing_tmpl.format(trial)} " + f"finished iteration {result[TRAINING_ITERATION]} " + f"at {curr_time_str}. Total running time: " + running_time_str + ) + self._print_result(trial, result) + + def on_trial_complete( + self, iteration: int, trials: List[Trial], trial: Trial, **info + ): + if self.verbosity < self._start_end_verbosity: + return + curr_time_str, running_time_str = _get_time_str(self._start_time, time.time()) + finished_iter = 0 + if trial.last_result and TRAINING_ITERATION in trial.last_result: + finished_iter = trial.last_result[TRAINING_ITERATION] + + self._start_block(f"trial_{trial}_complete") + print( + f"{self._addressing_tmpl.format(trial)} " + f"completed after {finished_iter} iterations " + f"at {curr_time_str}. Total running time: " + running_time_str + ) + self._print_result(trial) + + def on_trial_error( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + curr_time_str, running_time_str = _get_time_str(self._start_time, time.time()) + finished_iter = 0 + if trial.last_result and TRAINING_ITERATION in trial.last_result: + finished_iter = trial.last_result[TRAINING_ITERATION] + + self._start_block(f"trial_{trial}_error") + print( + f"{self._addressing_tmpl.format(trial)} " + f"errored after {finished_iter} iterations " + f"at {curr_time_str}. Total running time: {running_time_str}\n" + f"Error file: {trial.error_file}" + ) + self._print_result(trial) + + def on_trial_recover( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + self.on_trial_error(iteration=iteration, trials=trials, trial=trial, **info) + + def on_checkpoint( + self, + iteration: int, + trials: List[Trial], + trial: Trial, + checkpoint: Checkpoint, + **info, + ): + if self._verbosity < self._intermediate_result_verbosity: + return + # don't think this is supposed to happen but just to be safe. + saved_iter = "?" + if trial.last_result and TRAINING_ITERATION in trial.last_result: + saved_iter = trial.last_result[TRAINING_ITERATION] + + self._start_block(f"trial_{trial}_result_{saved_iter}") + + loc = f"({checkpoint.filesystem.type_name}){checkpoint.path}" + + print( + f"{self._addressing_tmpl.format(trial)} " + f"saved a checkpoint for iteration {saved_iter} " + f"at: {loc}" + ) + + def on_trial_start(self, iteration: int, trials: List[Trial], trial: Trial, **info): + if self.verbosity < self._start_end_verbosity: + return + has_config = bool(trial.config) + + self._start_block(f"trial_{trial}_start") + if has_config: + print( + f"{self._addressing_tmpl.format(trial)} " f"started with configuration:" + ) + self._print_config(trial) + else: + print( + f"{self._addressing_tmpl.format(trial)} " + f"started without custom configuration." + ) + + +def _detect_reporter( + verbosity: AirVerbosity, + num_samples: int, + entrypoint: Optional[AirEntrypoint] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + config: Optional[Dict] = None, + progress_metrics: Optional[Union[List[str], List[Dict[str, str]]]] = None, +): + if entrypoint in { + AirEntrypoint.TUNE_RUN, + AirEntrypoint.TUNE_RUN_EXPERIMENTS, + AirEntrypoint.TUNER, + }: + reporter = TuneTerminalReporter( + verbosity, + num_samples=num_samples, + metric=metric, + mode=mode, + config=config, + progress_metrics=progress_metrics, + ) + else: + reporter = TrainReporter(verbosity, progress_metrics=progress_metrics) + return reporter + + +class TuneReporterBase(ProgressReporter): + _heartbeat_threshold = AirVerbosity.DEFAULT + _wrap_headers = False + _intermediate_result_verbosity = AirVerbosity.VERBOSE + _start_end_verbosity = AirVerbosity.DEFAULT + _addressing_tmpl = "Trial {}" + + def __init__( + self, + verbosity: AirVerbosity, + num_samples: int = 0, + metric: Optional[str] = None, + mode: Optional[str] = None, + config: Optional[Dict] = None, + progress_metrics: Optional[Union[List[str], List[Dict[str, str]]]] = None, + ): + self._num_samples = num_samples + self._metric = metric + self._mode = mode + # will be populated when first result comes in. + self._inferred_metric = None + self._inferred_params = _infer_params(config or {}) + super(TuneReporterBase, self).__init__( + verbosity=verbosity, progress_metrics=progress_metrics + ) + + def setup( + self, + start_time: Optional[float] = None, + total_samples: Optional[int] = None, + **kwargs, + ): + super().setup(start_time=start_time) + self._num_samples = total_samples + + def _get_overall_trial_progress_str(self, trials): + result = " | ".join( + [ + f"{len(trials)} {status}" + for status, trials in _get_trials_by_state(trials).items() + ] + ) + return f"Trial status: {result}" + + # TODO: Return a more structured type to share code with Jupyter flow. + def _get_heartbeat( + self, trials, *sys_args, force_full_output: bool = False + ) -> Tuple[List[str], _TrialTableData]: + result = list() + # Trial status: 1 RUNNING | 7 PENDING + result.append(self._get_overall_trial_progress_str(trials)) + # Current time: 2023-02-24 12:35:39 (running for 00:00:37.40) + result.append(self._time_heartbeat_str) + # Logical resource usage: 8.0/64 CPUs, 0/0 GPUs + result.extend(sys_args) + # Current best trial: TRIAL NAME, metrics: {...}, parameters: {...} + current_best_trial, metric = _current_best_trial( + trials, self._metric, self._mode + ) + if current_best_trial: + result.append(_best_trial_str(current_best_trial, metric)) + # Now populating the trial table data. + if not self._inferred_metric: + # try inferring again. + self._inferred_metric = _infer_user_metrics(trials) + + all_metrics = list(DEFAULT_COLUMNS.keys()) + self._inferred_metric + + trial_table_data = _get_trial_table_data( + trials, + param_keys=self._inferred_params, + metric_keys=all_metrics, + all_rows=force_full_output, + wrap_headers=self._wrap_headers, + ) + return result, trial_table_data + + def _print_heartbeat(self, trials, *sys_args, force: bool = False): + raise NotImplementedError + + +class TuneTerminalReporter(TuneReporterBase): + def experiment_started( + self, + experiment_name: str, + experiment_path: str, + searcher_str: str, + scheduler_str: str, + total_num_samples: int, + tensorboard_path: Optional[str] = None, + **kwargs, + ): + if total_num_samples > sys.maxsize: + total_num_samples_str = "infinite" + else: + total_num_samples_str = str(total_num_samples) + + print( + tabulate( + [ + ["Search algorithm", searcher_str], + ["Scheduler", scheduler_str], + ["Number of trials", total_num_samples_str], + ], + headers=["Configuration for experiment", experiment_name], + tablefmt=AIR_TABULATE_TABLEFMT, + ) + ) + super().experiment_started( + experiment_name=experiment_name, + experiment_path=experiment_path, + searcher_str=searcher_str, + scheduler_str=scheduler_str, + total_num_samples=total_num_samples, + tensorboard_path=tensorboard_path, + **kwargs, + ) + + def _print_heartbeat(self, trials, *sys_args, force: bool = False): + if self._verbosity < self._heartbeat_threshold and not force: + return + heartbeat_strs, table_data = self._get_heartbeat( + trials, *sys_args, force_full_output=force + ) + + self._start_block("heartbeat") + for s in heartbeat_strs: + print(s) + # now print the table using Tabulate + more_infos = [] + all_data = [] + fail_header = table_data.header + for sub_table in table_data.data: + all_data.extend(sub_table.trial_infos) + if sub_table.more_info: + more_infos.append(sub_table.more_info) + + print( + tabulate( + all_data, + headers=fail_header, + tablefmt=AIR_TABULATE_TABLEFMT, + showindex=False, + ) + ) + if more_infos: + print(", ".join(more_infos)) + + if not force: + # Only print error table at end of training + return + + trials_with_error = _get_trials_with_error(trials) + if not trials_with_error: + return + + self._start_block("status_errored") + print(f"Number of errored trials: {len(trials_with_error)}") + fail_header = ["Trial name", "# failures", "error file"] + fail_table_data = [ + [ + str(trial), + str(trial.run_metadata.num_failures) + + ("" if trial.status == Trial.ERROR else "*"), + trial.error_file, + ] + for trial in trials_with_error + ] + print( + tabulate( + fail_table_data, + headers=fail_header, + tablefmt=AIR_TABULATE_TABLEFMT, + showindex=False, + colalign=("left", "right", "left"), + ) + ) + if any(trial.status == Trial.TERMINATED for trial in trials_with_error): + print("* The trial terminated successfully after retrying.") + + +class TrainReporter(ProgressReporter): + # the minimal verbosity threshold at which heartbeat starts getting printed. + _heartbeat_threshold = AirVerbosity.VERBOSE + _intermediate_result_verbosity = AirVerbosity.DEFAULT + _start_end_verbosity = AirVerbosity.DEFAULT + _addressing_tmpl = "Training" + + def _get_heartbeat(self, trials: List[Trial], force_full_output: bool = False): + # Training on iteration 1. Current time: 2023-03-22 15:29:25 (running for 00:00:03.24) # noqa + if len(trials) == 0: + return + trial = trials[0] + if trial.status != Trial.RUNNING: + return " ".join( + [f"Training is in {trial.status} status.", self._time_heartbeat_str] + ) + if not trial.last_result or TRAINING_ITERATION not in trial.last_result: + iter_num = 1 + else: + iter_num = trial.last_result[TRAINING_ITERATION] + 1 + return " ".join( + [f"Training on iteration {iter_num}.", self._time_heartbeat_str] + ) + + def _print_heartbeat(self, trials, *args, force: bool = False): + print(self._get_heartbeat(trials, force_full_output=force)) + + def on_trial_result( + self, + iteration: int, + trials: List[Trial], + trial: Trial, + result: Dict, + **info, + ): + self._last_heartbeat_time = time.time() + super().on_trial_result( + iteration=iteration, trials=trials, trial=trial, result=result, **info + ) diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/impl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6c583f353a1461274c4d0b079722bd58ebec123 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/config.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5b87ca1cb756f6c1ea9a4f24da11c064f71da8d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/config.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/out_of_band_serialize_dataset.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/out_of_band_serialize_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4f87638d84e458c4f7921ac428b726af5bb6407 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/out_of_band_serialize_dataset.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/placeholder.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/placeholder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b10bda9a343624e704448383003223ce2b9ea421 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/placeholder.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/test_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/test_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07a5ffca7156c77b71699bb0b880f208ea4aa61c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/test_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/tuner_internal.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/tuner_internal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6e699de767647788a995adfe7620d060621c660 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/impl/__pycache__/tuner_internal.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/config.py b/venv/lib/python3.10/site-packages/ray/tune/impl/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a306366c013ee5e01be54febcc2e4545e93d5ad2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/impl/config.py @@ -0,0 +1,53 @@ +from dataclasses import dataclass + +from ray.air.config import ( + CheckpointConfig as _CheckpointConfig, + FailureConfig as _FailureConfig, + RunConfig as _RunConfig, +) +from ray.train.constants import ( + V2_MIGRATION_GUIDE_MESSAGE, + _v2_migration_warnings_enabled, +) +from ray.train.utils import _copy_doc, _log_deprecation_warning + +# NOTE: This is just a pass-through wrapper around `ray.tune.RunConfig` +# in order to detect whether the import module was correct (e.g. `ray.tune.RunConfig`). + + +@dataclass +@_copy_doc(_CheckpointConfig) +class CheckpointConfig(_CheckpointConfig): + pass + + +@dataclass +@_copy_doc(_FailureConfig) +class FailureConfig(_FailureConfig): + pass + + +@dataclass +@_copy_doc(_RunConfig) +class RunConfig(_RunConfig): + def __post_init__(self): + self.checkpoint_config = self.checkpoint_config or CheckpointConfig() + self.failure_config = self.failure_config or FailureConfig() + + super().__post_init__() + + if not isinstance(self.checkpoint_config, CheckpointConfig): + if _v2_migration_warnings_enabled(): + _log_deprecation_warning( + "The `CheckpointConfig` class should be imported from `ray.tune` " + "when passing it to the Tuner. Please update your imports." + f"{V2_MIGRATION_GUIDE_MESSAGE}" + ) + + if not isinstance(self.failure_config, FailureConfig): + if _v2_migration_warnings_enabled(): + _log_deprecation_warning( + "The `FailureConfig` class should be imported from `ray.tune` " + "when passing it to the Tuner. Please update your imports." + f"{V2_MIGRATION_GUIDE_MESSAGE}" + ) diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/out_of_band_serialize_dataset.py b/venv/lib/python3.10/site-packages/ray/tune/impl/out_of_band_serialize_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..112cee4d803298e54c78ebb24d3e82b76853a565 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/impl/out_of_band_serialize_dataset.py @@ -0,0 +1,33 @@ +import contextlib +import traceback + +import ray + + +def _deserialize_and_fully_execute_if_needed(serialized_ds: bytes): + ds = ray.data.Dataset.deserialize_lineage(serialized_ds) + return ds + + +def _reduce(ds: ray.data.Dataset): + tb_list = traceback.format_list(traceback.extract_stack()) + _already_in_out_of_band_serialization = False + for tb in tb_list: + # TODO(xwjiang): Let's make this less hacky. + if "serialize_lineage" in tb: + _already_in_out_of_band_serialization = True + break + if not _already_in_out_of_band_serialization and ds.has_serializable_lineage(): + return _deserialize_and_fully_execute_if_needed, (ds.serialize_lineage(),) + else: + return ds.__reduce__() + + +@contextlib.contextmanager +def out_of_band_serialize_dataset(): + context = ray._private.worker.global_worker.get_serialization_context() + try: + context._register_cloudpickle_reducer(ray.data.Dataset, _reduce) + yield + finally: + context._unregister_cloudpickle_reducer(ray.data.Dataset) diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/placeholder.py b/venv/lib/python3.10/site-packages/ray/tune/impl/placeholder.py new file mode 100644 index 0000000000000000000000000000000000000000..6865b46f3f04f155a3235fcd62c958de935d1cc8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/impl/placeholder.py @@ -0,0 +1,244 @@ +import hashlib +from collections import defaultdict +from typing import Any, Dict, Tuple + +from ray.tune.search.sample import Categorical, Domain, Function +from ray.tune.search.variant_generator import assign_value +from ray.util.annotations import DeveloperAPI + +ID_HASH_LENGTH = 8 + + +def create_resolvers_map(): + return defaultdict(list) + + +def _id_hash(path_tuple): + """Compute a hash for the specific placeholder based on its path.""" + return hashlib.sha1(str(path_tuple).encode("utf-8")).hexdigest()[:ID_HASH_LENGTH] + + +class _FunctionResolver: + """Replaced value for function typed objects.""" + + TOKEN = "__fn_ph" + + def __init__(self, hash, fn): + self.hash = hash + self._fn = fn + + def resolve(self, config: Dict): + """Some functions take a resolved spec dict as input. + + Note: Function placeholders are independently sampled during + resolution. Therefore their random states are not restored. + """ + return self._fn.sample(config=config) + + def get_placeholder(self) -> str: + return (self.TOKEN, self.hash) + + +class _RefResolver: + """Replaced value for all other non-primitive objects.""" + + TOKEN = "__ref_ph" + + def __init__(self, hash, value): + self.hash = hash + self._value = value + + def resolve(self): + return self._value + + def get_placeholder(self) -> str: + return (self.TOKEN, self.hash) + + +def _is_primitive(x): + """Returns True if x is a primitive type. + + Primitive types are int, float, str, bool, and None. + """ + return isinstance(x, (int, float, str, bool)) or x is None + + +@DeveloperAPI +def inject_placeholders( + config: Any, + resolvers: defaultdict, + id_prefix: Tuple = (), + path_prefix: Tuple = (), +) -> Dict: + """Replaces reference objects contained by a config dict with placeholders. + + Given a config dict, this function replaces all reference objects contained + by this dict with placeholder strings. It recursively expands nested dicts + and lists, and properly handles Tune native search objects such as Categorical + and Function. + This makes sure the config dict only contains primitive typed values, which + can then be handled by different search algorithms. + + A few details about id_prefix and path_prefix. Consider the following config, + where "param1" is a simple grid search of 3 tuples. + + config = { + "param1": tune.grid_search([ + (Cat, None, None), + (None, Dog, None), + (None, None, Fish), + ]), + } + + We will replace the 3 objects contained with placeholders. And after trial + expansion, the config may look like this: + + config = { + "param1": (None, (placeholder, hash), None) + } + + Now you need 2 pieces of information to resolve the placeholder. One is the + path of ("param1", 1), which tells you that the first element of the tuple + under "param1" key is a placeholder that needs to be resolved. + The other is the mapping from the placeholder to the actual object. In this + case hash -> Dog. + + id and path prefixes serve exactly this purpose here. The difference between + these two is that id_prefix is the location of the value in the pre-injected + config tree. So if a value is the second option in a grid_search, it gets an + id part of 1. Injected placeholders all get unique id prefixes. path prefix + identifies a placeholder in the expanded config tree. So for example, all + options of a single grid_search will get the same path prefix. This is how + we know which location has a placeholder to be resolved in the post-expansion + tree. + + Args: + config: The config dict to replace references in. + resolvers: A dict from path to replaced objects. + id_prefix: The prefix to prepend to id every single placeholders. + path_prefix: The prefix to prepend to every path identifying + potential locations of placeholders in an expanded tree. + + Returns: + The config with all references replaced. + """ + if isinstance(config, dict) and "grid_search" in config and len(config) == 1: + config["grid_search"] = [ + # Different options gets different id prefixes. + # But we should omit appending to path_prefix because after expansion, + # this level will not be there. + inject_placeholders(choice, resolvers, id_prefix + (i,), path_prefix) + for i, choice in enumerate(config["grid_search"]) + ] + return config + elif isinstance(config, dict): + return { + k: inject_placeholders(v, resolvers, id_prefix + (k,), path_prefix + (k,)) + for k, v in config.items() + } + elif isinstance(config, list): + return [ + inject_placeholders(elem, resolvers, id_prefix + (i,), path_prefix + (i,)) + for i, elem in enumerate(config) + ] + elif isinstance(config, tuple): + return tuple( + inject_placeholders(elem, resolvers, id_prefix + (i,), path_prefix + (i,)) + for i, elem in enumerate(config) + ) + elif _is_primitive(config): + # Primitive types. + return config + elif isinstance(config, Categorical): + config.categories = [ + # Different options gets different id prefixes. + # But we should omit appending to path_prefix because after expansion, + # this level will not be there. + inject_placeholders(choice, resolvers, id_prefix + (i,), path_prefix) + for i, choice in enumerate(config.categories) + ] + return config + elif isinstance(config, Function): + # Function type. + id_hash = _id_hash(id_prefix) + v = _FunctionResolver(id_hash, config) + resolvers[path_prefix].append(v) + return v.get_placeholder() + elif not isinstance(config, Domain): + # Other non-search space reference objects, dataset, actor handle, etc. + id_hash = _id_hash(id_prefix) + v = _RefResolver(id_hash, config) + resolvers[path_prefix].append(v) + return v.get_placeholder() + else: + # All the other cases, do nothing. + return config + + +def _get_placeholder(config: Any, prefix: Tuple, path: Tuple): + if not path: + return prefix, config + + key = path[0] + if isinstance(config, tuple): + if config[0] in (_FunctionResolver.TOKEN, _RefResolver.TOKEN): + # Found a matching placeholder. + # Note that we do not require that the full path are consumed before + # declaring a match. Because this placeholder may be part of a nested + # search space. For example, the following config: + # config = { + # "param1": tune.grid_search([ + # tune.grid_search([Object1, 2, 3]), + # tune.grid_search([Object2, 5, 6]), + # ]), + # } + # will result in placeholders under path ("param1", 0, 0). + # After expansion though, the choosen placeholder will live under path + # ("param1", 0) like this: config = {"param1": (Placeholder1, 2, 3)} + return prefix, config + elif key < len(config): + return _get_placeholder( + config[key], prefix=prefix + (path[0],), path=path[1:] + ) + elif (isinstance(config, dict) and key in config) or ( + isinstance(config, list) and key < len(config) + ): + # Expand config tree recursively. + return _get_placeholder(config[key], prefix=prefix + (path[0],), path=path[1:]) + + # Can not find a matching placeholder. + return None, None + + +@DeveloperAPI +def resolve_placeholders(config: Any, replaced: defaultdict): + """Replaces placeholders contained by a config dict with the original values. + + Args: + config: The config to replace placeholders in. + replaced: A dict from path to replaced objects. + """ + + def __resolve(resolver_type, args): + for path, resolvers in replaced.items(): + assert resolvers + + if not isinstance(resolvers[0], resolver_type): + continue + + prefix, ph = _get_placeholder(config, (), path) + if not ph: + # Represents an unchosen value. Just skip. + continue + + for resolver in resolvers: + if resolver.hash != ph[1]: + continue + # Found the matching resolver. + assign_value(config, prefix, resolver.resolve(*args)) + + # RefResolvers first. + __resolve(_RefResolver, args=()) + # Functions need to be resolved after RefResolvers, in case they are + # referencing values from the RefResolvers. + __resolve(_FunctionResolver, args=(config,)) diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/test_utils.py b/venv/lib/python3.10/site-packages/ray/tune/impl/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6c55ccbd51476d5f68a305775315451ecbb8b311 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/impl/test_utils.py @@ -0,0 +1,65 @@ +from sklearn.datasets import load_breast_cancer + +from ray import tune +from ray.data import Dataset, Datasource, ReadTask, read_datasource +from ray.data.block import BlockMetadata +from ray.tune.impl.utils import execute_dataset + + +# TODO(xwjiang): Enable this when Clark's out-of-band-serialization is landed. +class TestDatasource(Datasource): + def prepare_read(self, parallelism: int, **read_args): + import pyarrow as pa + + def load_data(): + data_raw = load_breast_cancer(as_frame=True) + dataset_df = data_raw["data"] + dataset_df["target"] = data_raw["target"] + return [pa.Table.from_pandas(dataset_df)] + + meta = BlockMetadata( + num_rows=None, + size_bytes=None, + input_files=None, + exec_stats=None, + ) + return [ReadTask(load_data, meta)] + + +def gen_dataset_func() -> Dataset: + test_datasource = TestDatasource() + return read_datasource(test_datasource) + + +def test_grid_search(): + ds1 = gen_dataset_func().lazy().map(lambda x: x) + ds2 = gen_dataset_func().lazy().map(lambda x: x) + assert not ds1._plan._has_final_stage_snapshot() + assert not ds2._plan._has_final_stage_snapshot() + param_space = {"train_dataset": tune.grid_search([ds1, ds2])} + execute_dataset(param_space) + executed_ds = param_space["train_dataset"]["grid_search"] + assert len(executed_ds) == 2 + assert executed_ds[0]._plan._has_final_stage_snapshot() + assert executed_ds[1]._plan._has_final_stage_snapshot() + + +def test_choice(): + ds1 = gen_dataset_func().lazy().map(lambda x: x) + ds2 = gen_dataset_func().lazy().map(lambda x: x) + assert not ds1._plan._has_final_stage_snapshot() + assert not ds2._plan._has_final_stage_snapshot() + param_space = {"train_dataset": tune.choice([ds1, ds2])} + execute_dataset(param_space) + executed_ds = param_space["train_dataset"].categories + assert len(executed_ds) == 2 + assert executed_ds[0]._plan._has_final_stage_snapshot() + assert executed_ds[1]._plan._has_final_stage_snapshot() + + +if __name__ == "__main__": + import sys + + import pytest + + sys.exit(pytest.main(["-v", "-x", __file__])) diff --git a/venv/lib/python3.10/site-packages/ray/tune/impl/tuner_internal.py b/venv/lib/python3.10/site-packages/ray/tune/impl/tuner_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..4ddee22e366e83ab59616de5b6b8687f90721f9f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/impl/tuner_internal.py @@ -0,0 +1,674 @@ +import copy +import io +import logging +import math +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + Optional, + Tuple, + Type, + Union, +) + +import pyarrow.fs + +import ray.cloudpickle as pickle +import ray.train +import ray.tune +from ray.air._internal.uri_utils import URI +from ray.air._internal.usage import AirEntrypoint +from ray.train._internal.storage import StorageContext, get_fs_and_path +from ray.train.constants import ( + V2_MIGRATION_GUIDE_MESSAGE, + _v2_migration_warnings_enabled, +) +from ray.train.utils import _log_deprecation_warning +from ray.tune import ( + Experiment, + ExperimentAnalysis, + ResumeConfig, + RunConfig, + TuneConfig, + TuneError, +) +from ray.tune.registry import is_function_trainable +from ray.tune.result_grid import ResultGrid +from ray.tune.trainable import Trainable +from ray.tune.tune import _Config, run +from ray.tune.utils import flatten_dict +from ray.util import inspect_serializability + +if TYPE_CHECKING: + from ray.train.trainer import BaseTrainer + from ray.util.queue import Queue + + +_TUNER_PKL = "tuner.pkl" +_TRAINABLE_KEY = "_trainable" +_CONVERTED_TRAINABLE_KEY = "_converted_trainable" +_PARAM_SPACE_KEY = "_param_space" +_EXPERIMENT_ANALYSIS_KEY = "_experiment_analysis" + +logger = logging.getLogger(__name__) + +TrainableType = Union[str, Callable, Type[Trainable]] +TrainableTypeOrTrainer = Union[TrainableType, "BaseTrainer"] + + +class TunerInternal: + """The real implementation behind external facing ``Tuner``. + + The external facing ``Tuner`` multiplexes between local Tuner and remote Tuner + depending on whether in Ray client mode. + + In Ray client mode, external ``Tuner`` wraps ``TunerInternal`` into a remote actor, + which is guaranteed to be placed on head node. + + ``TunerInternal`` can be constructed from fresh, in which case, ``trainable`` needs + to be provided, together with optional ``param_space``, ``tune_config`` and + ``run_config``. + + It can also be restored from a previous failed run (given ``restore_path``). + + Args: + restore_path: The path from where the Tuner can be restored. If provided, None + of the rest args are needed. + resume_config: Resume config to configure which trials to continue. + trainable: The trainable to be tuned. + param_space: Search space of the tuning job. + One thing to note is that both preprocessor and dataset can be tuned here. + tune_config: Tuning algorithm specific configs. + Refer to ray.tune.tune_config.TuneConfig for more info. + run_config: Runtime configuration that is specific to individual trials. + If passed, this will overwrite the run config passed to the Trainer, + if applicable. Refer to ray.tune.RunConfig for more info. + """ + + def __init__( + self, + restore_path: str = None, + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + resume_config: Optional[ResumeConfig] = None, + trainable: Optional[TrainableTypeOrTrainer] = None, + param_space: Optional[Dict[str, Any]] = None, + tune_config: Optional[TuneConfig] = None, + run_config: Optional[RunConfig] = None, + _tuner_kwargs: Optional[Dict] = None, + _entrypoint: AirEntrypoint = AirEntrypoint.TUNER, + ): + from ray.train.trainer import BaseTrainer + + if isinstance(trainable, BaseTrainer): + if _v2_migration_warnings_enabled(): + _log_deprecation_warning( + "The Ray Train + Ray Tune integration has been reworked. " + "Passing a Trainer to the Tuner is deprecated and will be removed " + "in a future release. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" + ) + + run_config = self._choose_run_config( + tuner_run_config=run_config, + trainer=trainable, + param_space=param_space, + ) + + self._tune_config = tune_config or TuneConfig() + self._run_config = copy.copy(run_config) or RunConfig() + self._entrypoint = _entrypoint + + # Restore from Tuner checkpoint. + if restore_path: + self._restore_from_path_or_uri( + path_or_uri=restore_path, + trainable=trainable, + overwrite_param_space=param_space, + resume_config=resume_config, + storage_filesystem=storage_filesystem, + ) + return + + # Start from fresh + if not trainable: + raise TuneError("You need to provide a trainable to tune.") + + if self._entrypoint == AirEntrypoint.TUNER and not isinstance( + self._run_config, ray.tune.RunConfig + ): + if _v2_migration_warnings_enabled(): + _log_deprecation_warning( + "The `RunConfig` class should be imported from `ray.tune` " + "when passing it to the Tuner. Please update your imports. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" + ) + + self.trainable = trainable + assert self.converted_trainable + self._validate_trainable(self.converted_trainable) + + self.param_space = param_space + + self._resume_config = None + self._is_restored = False + self._tuner_kwargs = copy.deepcopy(_tuner_kwargs) or {} + self._experiment_analysis = None + + self._run_config.name = ( + self._run_config.name + or StorageContext.get_experiment_dir_name(self.converted_trainable) + ) + # The storage context here is only used to access the resolved + # storage fs and experiment path, in order to avoid duplicating that logic. + # This is NOT the storage context object that gets passed to remote workers. + storage = StorageContext( + storage_path=self._run_config.storage_path, + experiment_dir_name=self._run_config.name, + storage_filesystem=self._run_config.storage_filesystem, + ) + + fs = storage.storage_filesystem + fs.create_dir(storage.experiment_fs_path) + with fs.open_output_stream( + Path(storage.experiment_fs_path, _TUNER_PKL).as_posix() + ) as f: + f.write(pickle.dumps(self.__getstate__())) + + def get_run_config(self) -> RunConfig: + return self._run_config + + # For Jupyter output with Ray Client + def set_run_config_and_remote_string_queue( + self, run_config: RunConfig, string_queue: "Queue" + ): + self._run_config = run_config + self._tuner_kwargs["_remote_string_queue"] = string_queue + + def clear_remote_string_queue(self): + self._tuner_kwargs.pop("_remote_string_queue", None) + + def _expected_utilization(self, cpus_per_trial, cpus_total): + num_samples = self._tune_config.num_samples + if num_samples < 0: # TODO: simplify this in Tune + num_samples = math.inf + concurrent_trials = self._tune_config.max_concurrent_trials or 0 + if concurrent_trials < 1: # TODO: simplify this in Tune + concurrent_trials = math.inf + + actual_concurrency = min( + ( + (cpus_total // cpus_per_trial) if cpus_per_trial else 0, + num_samples, + concurrent_trials, + ) + ) + return (actual_concurrency * cpus_per_trial) / (cpus_total + 0.001) + + def _validate_trainable( + self, trainable: TrainableType, required_trainable_name: Optional[str] = None + ): + """Determines whether or not the trainable is valid. + + This includes checks on the serializability of the trainable, as well + asserting that the trainable name is as expected on restoration. + + This trainable name validation is needed due to an implementation detail + where the trainable name (which is differently generated depending on + the trainable type) is saved in the Trial metadata and needs to match + upon restoration. This does not affect the typical path, since `Tuner.restore` + expects the exact same trainable (which will have the same name). + + Raises: + ValueError: if the trainable name does not match or if the trainable + is not serializable. + """ + try: + pickle.dumps(trainable) + except TypeError as e: + sio = io.StringIO() + inspect_serializability(trainable, print_file=sio) + msg = ( + "The provided trainable is not serializable, which is a requirement " + "since the trainable is serialized and deserialized when transferred " + "to remote workers. See below for a trace of the non-serializable " + "objects that were found in your trainable:\n" + f"{sio.getvalue()}" + ) + raise TypeError(msg) from e + + if not required_trainable_name: + return + + trainable_name = Experiment.get_trainable_name(trainable) + + if trainable_name != required_trainable_name: + raise ValueError( + "Invalid `trainable` input to `Tuner.restore()`. To fix this error, " + "pass in the same trainable that was used to initialize the Tuner. " + "Got a trainable with identifier " + f"'{trainable_name}' but expected '{required_trainable_name}'." + ) + + def _set_trainable_on_restore( + self, trainable: TrainableType, old_trainable_name: Optional[str] + ): + from ray.train.base_trainer import BaseTrainer + + self.trainable = trainable + assert self.converted_trainable + self._validate_trainable( + trainable=self.converted_trainable, + required_trainable_name=old_trainable_name, + ) + + if isinstance(self.trainable, BaseTrainer): + # Log a warning in case the user tries to modify the + # `RunConfig` from the Trainer + trainer: BaseTrainer = self.trainable + + # Only log if the Trainer has a non-default RunConfig + if trainer.run_config != RunConfig(): + logger.warning( + "The Tune experiment will restore using the original run's " + "`RunConfig`. If you made any changes to the `RunConfig` " + "within the Trainer you passed into `Tuner.restore`, " + "they will be ignored in the resumed run." + ) + + trainer.run_config = self._run_config + + def _validate_param_space_on_restore( + self, + new_param_space: Dict[str, Any], + flattened_param_space_keys: Optional[List[str]], + ): + """Determines whether the (optionally) re-specified `param_space` is valid. + + This method performs very loose validation on the new param_space to + prevent users from trying to specify new hyperparameters to tune over. + + Raises: + ValueError: if not all keys match the original param_space. + """ + if flattened_param_space_keys is None: + # Backwards compatibility: skip validation + return + + keys = sorted(flatten_dict(new_param_space).keys()) + if keys != flattened_param_space_keys: + raise ValueError( + "Invalid `param_space` input to `Tuner.restore()`. To fix this error, " + "pass in the same `param_space` that was used to initialize the Tuner. " + "Only re-specify the `param_space` to refresh Ray object references " + "that no longer exist due to restoring from a new Ray cluster session. " + "It should not be used to introduce new hyperparameters to tune." + f"\n\nGot: {keys}\nExpected: {flattened_param_space_keys}" + ) + + def _set_param_space_on_restore( + self, + param_space: Optional[Dict[str, Any]], + flattened_param_space_keys: Optional[List[str]], + ): + self.param_space = param_space + + if self.param_space is not None: + # param_space = None -> use the original param_space + self._validate_param_space_on_restore( + new_param_space=self.param_space, + flattened_param_space_keys=flattened_param_space_keys, + ) + + def _load_tuner_state( + self, tuner_state: Dict[str, Any] + ) -> Tuple[Optional[str], Optional[List[str]]]: + """Loads Tuner state from the previously saved `tuner.pkl`. + + Args: + tuner_pkl_path: pathlib.Path of the `tuner.pkl` file saved during the + original Tuner initialization. + + Returns: + tuple: of `(old_trainable_name, flattened_param_space_keys)` used for + validating the re-specified `trainable` and `param_space`. + """ + # NOTE: These are magic keys used for validating restore args. + old_trainable_name = tuner_state.pop("__trainable_name", None) + flattened_param_space_keys = tuner_state.pop( + "__flattened_param_space_keys", None + ) + + self.__setstate__(tuner_state) + + return old_trainable_name, flattened_param_space_keys + + def _restore_from_path_or_uri( + self, + path_or_uri: str, + trainable: TrainableTypeOrTrainer, + overwrite_param_space: Optional[Dict[str, Any]], + resume_config: ResumeConfig, + storage_filesystem: Optional[pyarrow.fs.FileSystem], + ): + fs, fs_path = get_fs_and_path(path_or_uri, storage_filesystem) + with fs.open_input_file(Path(fs_path, _TUNER_PKL).as_posix()) as f: + tuner_state = pickle.loads(f.readall()) + + old_trainable_name, flattened_param_space_keys = self._load_tuner_state( + tuner_state + ) + + # Perform validation and set the re-specified `trainable` and `param_space` + self._set_trainable_on_restore( + trainable=trainable, old_trainable_name=old_trainable_name + ) + self._set_param_space_on_restore( + param_space=overwrite_param_space, + flattened_param_space_keys=flattened_param_space_keys, + ) + + # Update RunConfig to reflect changes in the experiment directory + path_or_uri_obj = URI(path_or_uri) + + # Infer the `storage_path` and run `name` of the restored run using the + # experiment directory. + # Ex: ~/ray_results/exp_name -> ~/ray_results, exp_name + # Ex: s3://bucket/exp_name -> s3://bucket, exp_name + self._run_config.name = path_or_uri_obj.name + self._run_config.storage_path = str(path_or_uri_obj.parent) + # Update the storage_filesystem with the one passed in on restoration, if any. + self._run_config.storage_filesystem = storage_filesystem + + # Load the experiment results at the point where it left off. + try: + self._experiment_analysis = ExperimentAnalysis( + experiment_checkpoint_path=path_or_uri, + default_metric=self._tune_config.metric, + default_mode=self._tune_config.mode, + storage_filesystem=storage_filesystem, + ) + except Exception: + self._experiment_analysis = None + + self._resume_config = resume_config + self._is_restored = True + + def _choose_run_config( + self, + tuner_run_config: Optional[RunConfig], + trainer: "BaseTrainer", + param_space: Optional[Dict[str, Any]], + ) -> RunConfig: + """Chooses which `RunConfig` to use when multiple can be passed in + through a Trainer or the Tuner itself. + + Args: + tuner_run_config: The run config passed into the Tuner constructor. + trainer: The Trainer instance to use with Tune, which may have + a RunConfig specified by the user. + param_space: The param space passed to the Tuner. + + Raises: + ValueError: if the `run_config` is specified as a hyperparameter. + """ + if param_space and "run_config" in param_space: + raise ValueError( + "`RunConfig` cannot be tuned as part of the `param_space`! " + "Move the run config to be a parameter of the `Tuner`: " + "Tuner(..., run_config=RunConfig(...))" + ) + + # Both Tuner RunConfig + Trainer RunConfig --> prefer Tuner RunConfig + if tuner_run_config and trainer.run_config != ray.train.RunConfig(): + logger.info( + "A `RunConfig` was passed to both the `Tuner` and the " + f"`{trainer.__class__.__name__}`. The run config passed to " + "the `Tuner` is the one that will be used." + ) + return tuner_run_config + + # No Tuner RunConfig -> pass the Trainer config through + # This returns either a user-specified config, or the default RunConfig + # if nothing was provided to both the Trainer or Tuner. + if not tuner_run_config: + return trainer.run_config + + # Tuner RunConfig + No Trainer RunConfig --> Use the Tuner config + return tuner_run_config + + def _process_scaling_config(self) -> None: + """Converts ``self._param_space["scaling_config"]`` to a dict. + + The dict is converted back to a dataclass by the Trainer, after the + Tune search specification is resolved. + """ + # TODO: introduce `ray.tune.sample.TuneableDataclass` and allow Tune to + # natively resolve specs with dataclasses. + scaling_config = self._param_space.get("scaling_config") + if not isinstance(scaling_config, ray.train.ScalingConfig): + return + self._param_space["scaling_config"] = scaling_config.__dict__.copy() + + @property + def trainable(self) -> TrainableTypeOrTrainer: + return self._trainable + + @property + def converted_trainable(self) -> TrainableType: + return self._converted_trainable + + @trainable.setter + def trainable(self, trainable: TrainableTypeOrTrainer): + self._trainable = trainable + self._converted_trainable = self._convert_trainable(trainable) + + @property + def param_space(self) -> Optional[Dict[str, Any]]: + return self._param_space + + @param_space.setter + def param_space(self, param_space: Optional[Dict[str, Any]]): + # Handle any configs that adhere to the `to_dict` interface. + # Ex: AlgorithmConfig from RLlib + if isinstance(param_space, _Config): + param_space = param_space.to_dict() + + if not isinstance(param_space, dict) and param_space is not None: + raise ValueError( + "The `param_space` passed to the `Tuner` must be a dict. " + f"Got '{type(param_space)}' instead." + ) + + self._param_space = param_space + + if param_space: + self._process_scaling_config() + + def _convert_trainable(self, trainable: TrainableTypeOrTrainer) -> TrainableType: + """Converts a Trainer to a Tune trainable and saves the converted + trainable. If not using a Trainer, this leaves the trainable as is.""" + from ray.train.trainer import BaseTrainer + + return ( + trainable.as_trainable() + if isinstance(trainable, BaseTrainer) + else trainable + ) + + def fit(self) -> ResultGrid: + trainable = self.converted_trainable + param_space = copy.deepcopy(self.param_space) + if not self._is_restored: + analysis = self._fit_internal(trainable, param_space) + else: + analysis = self._fit_resume(trainable, param_space) + + self._experiment_analysis = analysis + + return ResultGrid(self._experiment_analysis) + + def get_results(self) -> ResultGrid: + if not self._experiment_analysis: + raise RuntimeError( + "Can't return results as experiment has not been run, yet. " + "Call `Tuner.fit()` to run the experiment first." + ) + return ResultGrid(self._experiment_analysis) + + def _get_tune_run_arguments(self, trainable: TrainableType) -> Dict[str, Any]: + """Get tune.run arguments common for both new and resumed runs.""" + # Avoid overwriting the originally configured checkpoint config. + checkpoint_config = copy.deepcopy(self._run_config.checkpoint_config) + + if checkpoint_config.checkpoint_frequency: + # Function trainables (and thus most of our trainers) usually don't handle + # this argument. + handle_checkpoint_freq = getattr( + trainable, "_handles_checkpoint_freq", None + ) + if handle_checkpoint_freq is False: + # If we specifically know this trainable doesn't support the + # argument, raise an error + raise ValueError( + "You passed `checkpoint_frequency=" + f"{checkpoint_config.checkpoint_frequency}` to your " + "CheckpointConfig, but this trainer does not support " + "this argument. If you passed in a Trainer that takes in a " + "custom training loop, you will need to " + "report a checkpoint every `checkpoint_frequency` iterations " + "within your training loop using " + "`ray.tune.report(metrics=..., checkpoint=...)` " + "to get this behavior." + ) + elif handle_checkpoint_freq is True: + # If we specifically support it, it's handled in the training loop, + # so we disable tune's bookkeeping. + checkpoint_config.checkpoint_frequency = 0 + # Otherwise, the trainable is not a Trainer and we just keep the + # user-supplied value. + # Function trainables will raise a runtime error later if set > 0 + if checkpoint_config.checkpoint_at_end is not None: + # Again, function trainables usually don't handle this argument. + handle_cp_at_end = getattr(trainable, "_handles_checkpoint_at_end", None) + if handle_cp_at_end is False: + # If we specifically know we don't support it, raise an error. + raise ValueError( + "You passed `checkpoint_at_end=" + f"{checkpoint_config.checkpoint_at_end}` " + "to your CheckpointConfig, but this trainer does not support " + "this argument. If you passed in a Trainer that takes in a " + "custom training loop, you should include one last call to " + "`ray.tune.report(metrics=..., checkpoint=...)` " + "at the end of your training loop to get this behavior." + ) + elif handle_cp_at_end is True: + # If we specifically support it, it's handled in the training loop, + # so we disable tune's internal bookkeeping. + checkpoint_config.checkpoint_at_end = False + # If this is a user-defined trainable, just keep the value + # Function trainables will raise a runtime error later if set to True + else: + # Set default to False for function trainables and True for everything else + if is_function_trainable(trainable): + checkpoint_config.checkpoint_at_end = False + else: + checkpoint_config.checkpoint_at_end = True + + return dict( + storage_path=self._run_config.storage_path, + storage_filesystem=self._run_config.storage_filesystem, + name=self._run_config.name, + mode=self._tune_config.mode, + metric=self._tune_config.metric, + callbacks=self._run_config.callbacks, + sync_config=self._run_config.sync_config, + stop=self._run_config.stop, + max_failures=self._run_config.failure_config.max_failures, + checkpoint_config=checkpoint_config, + raise_on_failed_trial=False, + fail_fast=(self._run_config.failure_config.fail_fast), + progress_reporter=self._run_config.progress_reporter, + verbose=self._run_config.verbose, + reuse_actors=self._tune_config.reuse_actors, + max_concurrent_trials=self._tune_config.max_concurrent_trials, + time_budget_s=self._tune_config.time_budget_s, + trial_name_creator=self._tune_config.trial_name_creator, + trial_dirname_creator=self._tune_config.trial_dirname_creator, + _entrypoint=self._entrypoint, + # Deprecated + chdir_to_trial_dir=self._tune_config.chdir_to_trial_dir, + ) + + def _fit_internal( + self, trainable: TrainableType, param_space: Optional[Dict[str, Any]] + ) -> ExperimentAnalysis: + """Fitting for a fresh Tuner.""" + args = { + **self._get_tune_run_arguments(trainable), + **dict( + run_or_experiment=trainable, + config=param_space, + num_samples=self._tune_config.num_samples, + search_alg=self._tune_config.search_alg, + scheduler=self._tune_config.scheduler, + log_to_file=self._run_config.log_to_file, + ), + **self._tuner_kwargs, + } + analysis = run( + **args, + ) + self.clear_remote_string_queue() + return analysis + + def _fit_resume( + self, trainable: TrainableType, param_space: Optional[Dict[str, Any]] + ) -> ExperimentAnalysis: + """Fitting for a restored Tuner.""" + assert self._resume_config + + args = { + **self._get_tune_run_arguments(trainable), + **dict( + run_or_experiment=trainable, + config=param_space, + resume_config=self._resume_config, + search_alg=self._tune_config.search_alg, + scheduler=self._tune_config.scheduler, + ), + **self._tuner_kwargs, + } + analysis = run(**args) + self.clear_remote_string_queue() + return analysis + + def __getstate__(self): + state = self.__dict__.copy() + state["_tuner_kwargs"] = state["_tuner_kwargs"].copy() + state["_tuner_kwargs"].pop("_remote_string_queue", None) + state.pop(_TRAINABLE_KEY, None) + trainable = state.pop(_CONVERTED_TRAINABLE_KEY, None) + param_space = state.pop(_PARAM_SPACE_KEY, None) + state.pop(_EXPERIMENT_ANALYSIS_KEY, None) + + state["__trainable_name"] = ( + Experiment.get_trainable_name(trainable) if trainable else None + ) + state["__flattened_param_space_keys"] = ( + sorted(flatten_dict(param_space).keys()) + if param_space is not None + else None + ) + + return state + + def __setstate__(self, state): + # Make sure the magic metadata gets removed first. + state.pop("__flattened_param_space_keys", None) + state.pop("__trainable_name", None) + + self.__dict__.update(state) diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64ef0cc8defbec0dafeb86551b8ed1c330f4805f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/keras.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/keras.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9899e3e0e711a9dc3fe02a05c877349c1be66b98 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/keras.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/lightgbm.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/lightgbm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c64da8aed94e68c96d7a894b1de2ef3da6361f4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/lightgbm.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/pytorch_lightning.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/pytorch_lightning.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7692c5575b8307811ec3359abbb3298bef66305f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/pytorch_lightning.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/ray_train.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/ray_train.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6b3794f8a1602f56c9b270d5b0fe15634e0c1ff Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/ray_train.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/xgboost.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/xgboost.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb69ed31494d5f8c6ca7050ef0783d9d43064956 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/integration/__pycache__/xgboost.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/keras.py b/venv/lib/python3.10/site-packages/ray/tune/integration/keras.py new file mode 100644 index 0000000000000000000000000000000000000000..8733f0205005d60c4c1321b0cabb09dd1315b88b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/integration/keras.py @@ -0,0 +1,28 @@ +_DEPRECATION_MESSAGE = ( + "The `ray.tune.integration.keras` module is deprecated in favor of " + "`ray.train.tensorflow.keras.ReportCheckpointCallback`." +) + + +class TuneReportCallback: + """Deprecated. + Use :class:`ray.train.tensorflow.keras.ReportCheckpointCallback` instead.""" + + def __new__(cls, *args, **kwargs): + raise DeprecationWarning(_DEPRECATION_MESSAGE) + + +class _TuneCheckpointCallback: + """Deprecated. + Use :class:`ray.train.tensorflow.keras.ReportCheckpointCallback` instead.""" + + def __new__(cls, *args, **kwargs): + raise DeprecationWarning(_DEPRECATION_MESSAGE) + + +class TuneReportCheckpointCallback: + """Deprecated. + Use :class:`ray.train.tensorflow.keras.ReportCheckpointCallback` instead.""" + + def __new__(cls, *args, **kwargs): + raise DeprecationWarning(_DEPRECATION_MESSAGE) diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/lightgbm.py b/venv/lib/python3.10/site-packages/ray/tune/integration/lightgbm.py new file mode 100644 index 0000000000000000000000000000000000000000..778ba5ee2318bf57dc463953b36175ad94374e59 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/integration/lightgbm.py @@ -0,0 +1,14 @@ +from ray.train.lightgbm import ( # noqa: F401 + RayTrainReportCallback as TuneReportCheckpointCallback, +) +from ray.util.annotations import Deprecated + + +@Deprecated +class TuneReportCallback: + def __new__(cls: type, *args, **kwargs): + # TODO(justinvyu): [code_removal] Remove in 2.11. + raise DeprecationWarning( + "`TuneReportCallback` is deprecated. " + "Use `ray.tune.integration.lightgbm.TuneReportCheckpointCallback` instead." + ) diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/pytorch_lightning.py b/venv/lib/python3.10/site-packages/ray/tune/integration/pytorch_lightning.py new file mode 100644 index 0000000000000000000000000000000000000000..2ab98368150e974abe1d4248cd2f1f50411d39a1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/integration/pytorch_lightning.py @@ -0,0 +1,206 @@ +import inspect +import logging +import os +import tempfile +import warnings +from contextlib import contextmanager +from typing import Dict, List, Optional, Type, Union + +import ray.tune +from ray.tune import Checkpoint +from ray.util import log_once +from ray.util.annotations import Deprecated, PublicAPI + +try: + from lightning import Callback, LightningModule, Trainer +except ModuleNotFoundError: + from pytorch_lightning import Callback, LightningModule, Trainer + + +logger = logging.getLogger(__name__) + +# Get all Pytorch Lightning Callback hooks based on whatever PTL version is being used. +_allowed_hooks = { + name + for name, fn in inspect.getmembers(Callback, predicate=inspect.isfunction) + if name.startswith("on_") +} + + +def _override_ptl_hooks(callback_cls: Type["TuneCallback"]) -> Type["TuneCallback"]: + """Overrides all allowed PTL Callback hooks with our custom handle logic.""" + + def generate_overridden_hook(fn_name): + def overridden_hook( + self, + trainer: Trainer, + *args, + pl_module: Optional[LightningModule] = None, + **kwargs, + ): + if fn_name in self._on: + self._handle(trainer=trainer, pl_module=pl_module) + + return overridden_hook + + # Set the overridden hook to all the allowed hooks in TuneCallback. + for fn_name in _allowed_hooks: + setattr(callback_cls, fn_name, generate_overridden_hook(fn_name)) + + return callback_cls + + +@_override_ptl_hooks +class TuneCallback(Callback): + """Base class for Tune's PyTorch Lightning callbacks. + + Args: + on: When to trigger checkpoint creations. Must be one of + the PyTorch Lightning event hooks (less the ``on_``), e.g. + "train_batch_start", or "train_end". Defaults to "validation_end" + """ + + def __init__(self, on: Union[str, List[str]] = "validation_end"): + if not isinstance(on, list): + on = [on] + + for hook in on: + if f"on_{hook}" not in _allowed_hooks: + raise ValueError( + f"Invalid hook selected: {hook}. Must be one of " + f"{_allowed_hooks}" + ) + + # Add back the "on_" prefix for internal consistency. + on = [f"on_{hook}" for hook in on] + + self._on = on + + def _handle(self, trainer: Trainer, pl_module: Optional[LightningModule]): + raise NotImplementedError + + +@PublicAPI +class TuneReportCheckpointCallback(TuneCallback): + """PyTorch Lightning report and checkpoint callback + + Saves checkpoints after each validation step. Also reports metrics to Tune, + which is needed for checkpoint registration. + + Args: + metrics: Metrics to report to Tune. If this is a list, + each item describes the metric key reported to PyTorch Lightning, + and it will reported under the same name to Tune. If this is a + dict, each key will be the name reported to Tune and the respective + value will be the metric key reported to PyTorch Lightning. + filename: Filename of the checkpoint within the checkpoint + directory. Defaults to "checkpoint". + save_checkpoints: If True (default), checkpoints will be saved and + reported to Ray. If False, only metrics will be reported. + on: When to trigger checkpoint creations and metric reports. Must be one of + the PyTorch Lightning event hooks (less the ``on_``), e.g. + "train_batch_start", or "train_end". Defaults to "validation_end". + + + Example: + + .. code-block:: python + + import pytorch_lightning as pl + from ray.tune.integration.pytorch_lightning import ( + TuneReportCheckpointCallback) + + # Save checkpoint after each training batch and after each + # validation epoch. + trainer = pl.Trainer(callbacks=[TuneReportCheckpointCallback( + metrics={"loss": "val_loss", "mean_accuracy": "val_acc"}, + filename="trainer.ckpt", on="validation_end")]) + + + """ + + def __init__( + self, + metrics: Optional[Union[str, List[str], Dict[str, str]]] = None, + filename: str = "checkpoint", + save_checkpoints: bool = True, + on: Union[str, List[str]] = "validation_end", + ): + super(TuneReportCheckpointCallback, self).__init__(on=on) + if isinstance(metrics, str): + metrics = [metrics] + self._save_checkpoints = save_checkpoints + self._filename = filename + self._metrics = metrics + + def _get_report_dict(self, trainer: Trainer, pl_module: LightningModule): + # Don't report if just doing initial validation sanity checks. + if trainer.sanity_checking: + return + if not self._metrics: + report_dict = {k: v.item() for k, v in trainer.callback_metrics.items()} + else: + report_dict = {} + for key in self._metrics: + if isinstance(self._metrics, dict): + metric = self._metrics[key] + else: + metric = key + if metric in trainer.callback_metrics: + report_dict[key] = trainer.callback_metrics[metric].item() + else: + logger.warning( + f"Metric {metric} does not exist in " + "`trainer.callback_metrics." + ) + + return report_dict + + @contextmanager + def _get_checkpoint(self, trainer: Trainer) -> Optional[Checkpoint]: + if not self._save_checkpoints: + yield None + return + + with tempfile.TemporaryDirectory() as checkpoint_dir: + trainer.save_checkpoint(os.path.join(checkpoint_dir, self._filename)) + checkpoint = Checkpoint.from_directory(checkpoint_dir) + yield checkpoint + + def _handle(self, trainer: Trainer, pl_module: LightningModule): + if trainer.sanity_checking: + return + + report_dict = self._get_report_dict(trainer, pl_module) + if not report_dict: + return + + with self._get_checkpoint(trainer) as checkpoint: + ray.tune.report(report_dict, checkpoint=checkpoint) + + +class _TuneCheckpointCallback(TuneCallback): + def __init__(self, *args, **kwargs): + raise DeprecationWarning( + "`ray.tune.integration.pytorch_lightning._TuneCheckpointCallback` " + "is deprecated." + ) + + +@Deprecated +class TuneReportCallback(TuneReportCheckpointCallback): + def __init__( + self, + metrics: Optional[Union[str, List[str], Dict[str, str]]] = None, + on: Union[str, List[str]] = "validation_end", + ): + if log_once("tune_ptl_report_deprecated"): + warnings.warn( + "`ray.tune.integration.pytorch_lightning.TuneReportCallback` " + "is deprecated. Use " + "`ray.tune.integration.pytorch_lightning.TuneReportCheckpointCallback`" + " instead." + ) + super(TuneReportCallback, self).__init__( + metrics=metrics, save_checkpoints=False, on=on + ) diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/ray_train.py b/venv/lib/python3.10/site-packages/ray/tune/integration/ray_train.py new file mode 100644 index 0000000000000000000000000000000000000000..f8dfc60d3abf09d9116569ded88f09ce11882f80 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/integration/ray_train.py @@ -0,0 +1,32 @@ +from typing import Any, Dict, List, Optional + +import ray.tune +from ray.train import Checkpoint as RayTrainCheckpoint +from ray.train.v2._internal.execution.context import TrainRunContext +from ray.train.v2.api.callback import UserCallback +from ray.util.annotations import DeveloperAPI + +CHECKPOINT_PATH_KEY = "checkpoint_path" + + +@DeveloperAPI +class TuneReportCallback(UserCallback): + """Propagate metrics and checkpoint paths from Ray Train workers to Ray Tune.""" + + def after_report( + self, + run_context: TrainRunContext, + metrics: List[Dict[str, Any]], + checkpoint: Optional[RayTrainCheckpoint], + ): + # TODO: This can be changed to aggregate the metrics from all workers. + # For now, just achieve feature parity with the old Tune+Train integration. + metrics = metrics[0].copy() + + # If a checkpoint is provided, add the checkpoint path to the metrics. + # Don't report the checkpoint again since it's already been uploaded + # to storage. + if checkpoint: + metrics[CHECKPOINT_PATH_KEY] = checkpoint.path + + ray.tune.report(metrics=metrics) diff --git a/venv/lib/python3.10/site-packages/ray/tune/integration/xgboost.py b/venv/lib/python3.10/site-packages/ray/tune/integration/xgboost.py new file mode 100644 index 0000000000000000000000000000000000000000..fadb64ec4be1353b0f722c37406c5ba1a048a096 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/integration/xgboost.py @@ -0,0 +1,14 @@ +from ray.train.xgboost import ( # noqa: F401 + RayTrainReportCallback as TuneReportCheckpointCallback, +) +from ray.util.annotations import Deprecated + + +@Deprecated +class TuneReportCallback: + def __new__(cls: type, *args, **kwargs): + # TODO(justinvyu): [code_removal] Remove in 2.11. + raise DeprecationWarning( + "`TuneReportCallback` is deprecated. " + "Use `ray.tune.integration.xgboost.TuneReportCheckpointCallback` instead." + ) diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/logger/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fd315308bab32e576eeaaf3f4af10efc4fe6bf2e --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/logger/__init__.py @@ -0,0 +1,32 @@ +from ray.tune.logger.csv import CSVLogger, CSVLoggerCallback +from ray.tune.logger.json import JsonLogger, JsonLoggerCallback +from ray.tune.logger.logger import ( + LegacyLoggerCallback, + Logger, + LoggerCallback, + pretty_print, +) +from ray.tune.logger.noop import NoopLogger +from ray.tune.logger.tensorboardx import TBXLogger, TBXLoggerCallback + +DEFAULT_LOGGERS = (JsonLogger, CSVLogger, TBXLogger) + +# isort: off +from ray.tune.logger.unified import UnifiedLogger # noqa: E402 + +# isort: on + +__all__ = [ + "Logger", + "LoggerCallback", + "LegacyLoggerCallback", + "pretty_print", + "CSVLogger", + "CSVLoggerCallback", + "JsonLogger", + "JsonLoggerCallback", + "NoopLogger", + "TBXLogger", + "TBXLoggerCallback", + "UnifiedLogger", +] diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11a5e22bd49ac72a382c6caaf3b80408209753b9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/aim.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/aim.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3451984738702a67af9b326417b063b0b98f8351 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/aim.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/comet.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/comet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..470e51783ed0f839a19d2533761989f3cdd70d0b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/comet.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/csv.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/csv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69891bab9c9fff26d799de379f79e15c2966652b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/csv.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/json.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/json.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9490e905d5b668d5f43c5fa6d1c43cf482f16c68 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/json.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/logger.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e59b2a68b154ce650cb4f4c24dd86fd37058ef22 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/logger.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/mlflow.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/mlflow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23d5d98ef249121551ffc9783517bf52d0eb7250 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/mlflow.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/noop.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/noop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87f892e1e69893a22ae74fd07ee82bea07c37c3f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/noop.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/tensorboardx.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/tensorboardx.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..963f71062894bad1bfceae80e9e592f02943b45c Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/tensorboardx.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/unified.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/unified.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cd0459c6fdd67cd67984f43adccff23ce800fc0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/unified.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/wandb.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/wandb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9990e3b78391dc383ec0e4f238cf58e6808864ef Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/logger/__pycache__/wandb.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/aim.py b/venv/lib/python3.10/site-packages/ray/tune/logger/aim.py new file mode 100644 index 0000000000000000000000000000000000000000..863df7f46fe1f17793ad4afe04f0fe87806f3913 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/logger/aim.py @@ -0,0 +1,187 @@ +import logging +from typing import TYPE_CHECKING, Dict, List, Optional, Union + +import numpy as np + +from ray.air.constants import TRAINING_ITERATION +from ray.tune.logger.logger import LoggerCallback +from ray.tune.result import TIME_TOTAL_S, TIMESTEPS_TOTAL +from ray.tune.utils import flatten_dict +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.tune.experiment.trial import Trial + +try: + from aim.sdk import Repo, Run +except ImportError: + Repo, Run = None, None + +logger = logging.getLogger(__name__) + +VALID_SUMMARY_TYPES = [int, float, np.float32, np.float64, np.int32, np.int64] + + +@PublicAPI +class AimLoggerCallback(LoggerCallback): + """Aim Logger: logs metrics in Aim format. + + Aim is an open-source, self-hosted ML experiment tracking tool. + It's good at tracking lots (thousands) of training runs, and it allows you to + compare them with a performant and well-designed UI. + + Source: https://github.com/aimhubio/aim + + Args: + repo: Aim repository directory or a `Repo` object that the Run object will + log results to. If not provided, a default repo will be set up in the + experiment directory (one level above trial directories). + experiment: Sets the `experiment` property of each Run object, which is the + experiment name associated with it. Can be used later to query + runs/sequences. + If not provided, the default will be the Tune experiment name set + by `RunConfig(name=...)`. + metrics: List of metric names (out of the metrics reported by Tune) to + track in Aim. If no metric are specified, log everything that + is reported. + aim_run_kwargs: Additional arguments that will be passed when creating the + individual `Run` objects for each trial. For the full list of arguments, + please see the Aim documentation: + https://aimstack.readthedocs.io/en/latest/refs/sdk.html + """ + + VALID_HPARAMS = (str, bool, int, float, list, type(None)) + VALID_NP_HPARAMS = (np.bool_, np.float32, np.float64, np.int32, np.int64) + + def __init__( + self, + repo: Optional[Union[str, "Repo"]] = None, + experiment_name: Optional[str] = None, + metrics: Optional[List[str]] = None, + **aim_run_kwargs, + ): + """ + See help(AimLoggerCallback) for more information about parameters. + """ + assert Run is not None, ( + "aim must be installed!. You can install aim with" + " the command: `pip install aim`." + ) + self._repo_path = repo + self._experiment_name = experiment_name + if not (bool(metrics) or metrics is None): + raise ValueError( + "`metrics` must either contain at least one metric name, or be None, " + "in which case all reported metrics will be logged to the aim repo." + ) + self._metrics = metrics + self._aim_run_kwargs = aim_run_kwargs + self._trial_to_run: Dict["Trial", Run] = {} + + def _create_run(self, trial: "Trial") -> Run: + """Initializes an Aim Run object for a given trial. + + Args: + trial: The Tune trial that aim will track as a Run. + + Returns: + Run: The created aim run for a specific trial. + """ + experiment_dir = trial.local_experiment_path + run = Run( + repo=self._repo_path or experiment_dir, + experiment=self._experiment_name or trial.experiment_dir_name, + **self._aim_run_kwargs, + ) + # Attach a few useful trial properties + run["trial_id"] = trial.trial_id + run["trial_log_dir"] = trial.path + trial_ip = trial.get_ray_actor_ip() + if trial_ip: + run["trial_ip"] = trial_ip + return run + + def log_trial_start(self, trial: "Trial"): + if trial in self._trial_to_run: + # Cleanup an existing run if the trial has been restarted + self._trial_to_run[trial].close() + + trial.init_local_path() + self._trial_to_run[trial] = self._create_run(trial) + + if trial.evaluated_params: + self._log_trial_hparams(trial) + + def log_trial_result(self, iteration: int, trial: "Trial", result: Dict): + tmp_result = result.copy() + + step = result.get(TIMESTEPS_TOTAL, None) or result[TRAINING_ITERATION] + + for k in ["config", "pid", "timestamp", TIME_TOTAL_S, TRAINING_ITERATION]: + tmp_result.pop(k, None) # not useful to log these + + # `context` and `epoch` are special keys that users can report, + # which are treated as special aim metrics/configurations. + context = tmp_result.pop("context", None) + epoch = tmp_result.pop("epoch", None) + + trial_run = self._trial_to_run[trial] + path = ["ray", "tune"] + + flat_result = flatten_dict(tmp_result, delimiter="/") + valid_result = {} + + for attr, value in flat_result.items(): + if self._metrics and attr not in self._metrics: + continue + + full_attr = "/".join(path + [attr]) + if isinstance(value, tuple(VALID_SUMMARY_TYPES)) and not ( + np.isnan(value) or np.isinf(value) + ): + valid_result[attr] = value + trial_run.track( + value=value, + name=full_attr, + epoch=epoch, + step=step, + context=context, + ) + elif (isinstance(value, (list, tuple, set)) and len(value) > 0) or ( + isinstance(value, np.ndarray) and value.size > 0 + ): + valid_result[attr] = value + + def log_trial_end(self, trial: "Trial", failed: bool = False): + trial_run = self._trial_to_run.pop(trial) + trial_run.close() + + def _log_trial_hparams(self, trial: "Trial"): + params = flatten_dict(trial.evaluated_params, delimiter="/") + flat_params = flatten_dict(params) + + scrubbed_params = { + k: v for k, v in flat_params.items() if isinstance(v, self.VALID_HPARAMS) + } + + np_params = { + k: v.tolist() + for k, v in flat_params.items() + if isinstance(v, self.VALID_NP_HPARAMS) + } + + scrubbed_params.update(np_params) + removed = { + k: v + for k, v in flat_params.items() + if not isinstance(v, self.VALID_HPARAMS + self.VALID_NP_HPARAMS) + } + if removed: + logger.info( + "Removed the following hyperparameter values when " + "logging to aim: %s", + str(removed), + ) + + run = self._trial_to_run[trial] + run["hparams"] = scrubbed_params diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/comet.py b/venv/lib/python3.10/site-packages/ray/tune/logger/comet.py new file mode 100644 index 0000000000000000000000000000000000000000..31dfeafe670d70aa811db7152448390b7109b4d6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/logger/comet.py @@ -0,0 +1,3 @@ +from ray.air.integrations.comet import CometLoggerCallback + +CometLoggerCallback.__module__ = "ray.tune.logger.comet" diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/csv.py b/venv/lib/python3.10/site-packages/ray/tune/logger/csv.py new file mode 100644 index 0000000000000000000000000000000000000000..5802b43f893d4240ad878787dca8398e75db0c2c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/logger/csv.py @@ -0,0 +1,135 @@ +import csv +import logging +from pathlib import Path +from typing import TYPE_CHECKING, Dict, TextIO + +from ray.air.constants import EXPR_PROGRESS_FILE +from ray.tune.logger.logger import _LOGGER_DEPRECATION_WARNING, Logger, LoggerCallback +from ray.tune.utils import flatten_dict +from ray.util.annotations import Deprecated, PublicAPI + +if TYPE_CHECKING: + from ray.tune.experiment.trial import Trial # noqa: F401 + +logger = logging.getLogger(__name__) + + +@Deprecated( + message=_LOGGER_DEPRECATION_WARNING.format( + old="CSVLogger", new="ray.tune.csv.CSVLoggerCallback" + ), + warning=True, +) +@PublicAPI +class CSVLogger(Logger): + """Logs results to progress.csv under the trial directory. + + Automatically flattens nested dicts in the result dict before writing + to csv: + + {"a": {"b": 1, "c": 2}} -> {"a/b": 1, "a/c": 2} + + """ + + def _init(self): + self._initialized = False + + def _maybe_init(self): + """CSV outputted with Headers as first set of results.""" + if not self._initialized: + progress_file = Path(self.logdir, EXPR_PROGRESS_FILE) + self._continuing = ( + progress_file.exists() and progress_file.stat().st_size > 0 + ) + self._file = progress_file.open("a") + self._csv_out = None + self._initialized = True + + def on_result(self, result: Dict): + self._maybe_init() + + tmp = result.copy() + if "config" in tmp: + del tmp["config"] + result = flatten_dict(tmp, delimiter="/") + if self._csv_out is None: + self._csv_out = csv.DictWriter(self._file, result.keys()) + if not self._continuing: + self._csv_out.writeheader() + self._csv_out.writerow( + {k: v for k, v in result.items() if k in self._csv_out.fieldnames} + ) + self._file.flush() + + def flush(self): + if self._initialized and not self._file.closed: + self._file.flush() + + def close(self): + if self._initialized: + self._file.close() + + +@PublicAPI +class CSVLoggerCallback(LoggerCallback): + """Logs results to progress.csv under the trial directory. + + Automatically flattens nested dicts in the result dict before writing + to csv: + + {"a": {"b": 1, "c": 2}} -> {"a/b": 1, "a/c": 2} + + """ + + _SAVED_FILE_TEMPLATES = [EXPR_PROGRESS_FILE] + + def __init__(self): + self._trial_continue: Dict["Trial", bool] = {} + self._trial_files: Dict["Trial", TextIO] = {} + self._trial_csv: Dict["Trial", csv.DictWriter] = {} + + def _setup_trial(self, trial: "Trial"): + if trial in self._trial_files: + self._trial_files[trial].close() + + # Make sure logdir exists + trial.init_local_path() + local_file_path = Path(trial.local_path, EXPR_PROGRESS_FILE) + + # Resume the file from remote storage. + self._restore_from_remote(EXPR_PROGRESS_FILE, trial) + + self._trial_continue[trial] = ( + local_file_path.exists() and local_file_path.stat().st_size > 0 + ) + + self._trial_files[trial] = local_file_path.open("at") + self._trial_csv[trial] = None + + def log_trial_result(self, iteration: int, trial: "Trial", result: Dict): + if trial not in self._trial_files: + self._setup_trial(trial) + + tmp = result.copy() + tmp.pop("config", None) + result = flatten_dict(tmp, delimiter="/") + + if not self._trial_csv[trial]: + self._trial_csv[trial] = csv.DictWriter( + self._trial_files[trial], result.keys() + ) + if not self._trial_continue[trial]: + self._trial_csv[trial].writeheader() + + self._trial_csv[trial].writerow( + {k: v for k, v in result.items() if k in self._trial_csv[trial].fieldnames} + ) + self._trial_files[trial].flush() + + def log_trial_end(self, trial: "Trial", failed: bool = False): + if trial not in self._trial_files: + return + + del self._trial_csv[trial] + self._trial_files[trial].close() + del self._trial_files[trial] diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/json.py b/venv/lib/python3.10/site-packages/ray/tune/logger/json.py new file mode 100644 index 0000000000000000000000000000000000000000..d248a40802967b376f6e489dd268800642599f30 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/logger/json.py @@ -0,0 +1,128 @@ +import json +import logging +from pathlib import Path +from typing import TYPE_CHECKING, Dict, TextIO + +import numpy as np + +import ray.cloudpickle as cloudpickle +from ray.air.constants import EXPR_PARAM_FILE, EXPR_PARAM_PICKLE_FILE, EXPR_RESULT_FILE +from ray.tune.logger.logger import _LOGGER_DEPRECATION_WARNING, Logger, LoggerCallback +from ray.tune.utils.util import SafeFallbackEncoder +from ray.util.annotations import Deprecated, PublicAPI + +if TYPE_CHECKING: + from ray.tune.experiment.trial import Trial # noqa: F401 + +logger = logging.getLogger(__name__) + +tf = None +VALID_SUMMARY_TYPES = [int, float, np.float32, np.float64, np.int32, np.int64] + + +@Deprecated( + message=_LOGGER_DEPRECATION_WARNING.format( + old="JsonLogger", new="ray.tune.json.JsonLoggerCallback" + ), + warning=True, +) +@PublicAPI +class JsonLogger(Logger): + """Logs trial results in json format. + + Also writes to a results file and param.json file when results or + configurations are updated. Experiments must be executed with the + JsonLogger to be compatible with the ExperimentAnalysis tool. + """ + + def _init(self): + self.update_config(self.config) + local_file = Path(self.logdir, EXPR_RESULT_FILE) + self.local_out = local_file.open("a") + + def on_result(self, result: Dict): + json.dump(result, self, cls=SafeFallbackEncoder) + self.write("\n") + self.local_out.flush() + + def write(self, b): + self.local_out.write(b) + + def flush(self): + if not self.local_out.closed: + self.local_out.flush() + + def close(self): + self.local_out.close() + + def update_config(self, config: Dict): + self.config = config + config_out = Path(self.logdir, EXPR_PARAM_FILE) + with open(config_out, "w") as f: + json.dump(self.config, f, indent=2, sort_keys=True, cls=SafeFallbackEncoder) + config_pkl = Path(self.logdir, EXPR_PARAM_PICKLE_FILE) + with config_pkl.open("wb") as f: + cloudpickle.dump(self.config, f) + + +@PublicAPI +class JsonLoggerCallback(LoggerCallback): + """Logs trial results in json format. + + Also writes to a results file and param.json file when results or + configurations are updated. Experiments must be executed with the + JsonLoggerCallback to be compatible with the ExperimentAnalysis tool. + """ + + _SAVED_FILE_TEMPLATES = [EXPR_RESULT_FILE, EXPR_PARAM_FILE, EXPR_PARAM_PICKLE_FILE] + + def __init__(self): + self._trial_configs: Dict["Trial", Dict] = {} + self._trial_files: Dict["Trial", TextIO] = {} + + def log_trial_start(self, trial: "Trial"): + if trial in self._trial_files: + self._trial_files[trial].close() + + # Update config + self.update_config(trial, trial.config) + + # Make sure logdir exists + trial.init_local_path() + local_file = Path(trial.local_path, EXPR_RESULT_FILE) + + # Resume the file from remote storage. + self._restore_from_remote(EXPR_RESULT_FILE, trial) + + self._trial_files[trial] = local_file.open("at") + + def log_trial_result(self, iteration: int, trial: "Trial", result: Dict): + if trial not in self._trial_files: + self.log_trial_start(trial) + json.dump(result, self._trial_files[trial], cls=SafeFallbackEncoder) + self._trial_files[trial].write("\n") + self._trial_files[trial].flush() + + def log_trial_end(self, trial: "Trial", failed: bool = False): + if trial not in self._trial_files: + return + + self._trial_files[trial].close() + del self._trial_files[trial] + + def update_config(self, trial: "Trial", config: Dict): + self._trial_configs[trial] = config + + config_out = Path(trial.local_path, EXPR_PARAM_FILE) + with config_out.open("w") as f: + json.dump( + self._trial_configs[trial], + f, + indent=2, + sort_keys=True, + cls=SafeFallbackEncoder, + ) + + config_pkl = Path(trial.local_path, EXPR_PARAM_PICKLE_FILE) + with config_pkl.open("wb") as f: + cloudpickle.dump(self._trial_configs[trial], f) diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/logger.py b/venv/lib/python3.10/site-packages/ray/tune/logger/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..ad14069c3c20e8f17f5a5275ccb7e89758dcd7d4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/logger/logger.py @@ -0,0 +1,259 @@ +import abc +import json +import logging +from pathlib import Path +from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Set, Type + +import pyarrow +import yaml + +from ray.air._internal.json import SafeFallbackEncoder +from ray.tune.callback import Callback +from ray.util.annotations import Deprecated, DeveloperAPI, PublicAPI + +if TYPE_CHECKING: + from ray.tune.experiment.trial import Trial # noqa: F401 + +logger = logging.getLogger(__name__) + + +# Apply flow style for sequences of this length +_SEQUENCE_LEN_FLOW_STYLE = 3 + +_LOGGER_DEPRECATION_WARNING = ( + "The `{old} interface is deprecated in favor of the " + "`{new}` interface and will be removed in Ray 2.7." +) + + +@Deprecated( + message=_LOGGER_DEPRECATION_WARNING.format( + old="Logger", new="ray.tune.logger.LoggerCallback" + ), +) +@DeveloperAPI +class Logger(abc.ABC): + """Logging interface for ray.tune. + + By default, the UnifiedLogger implementation is used which logs results in + multiple formats (TensorBoard, rllab/viskit, plain json, custom loggers) + at once. + + Arguments: + config: Configuration passed to all logger creators. + logdir: Directory for all logger creators to log to. + trial: Trial object for the logger to access. + """ + + def __init__(self, config: Dict, logdir: str, trial: Optional["Trial"] = None): + self.config = config + self.logdir = logdir + self.trial = trial + self._init() + + def _init(self): + pass + + def on_result(self, result): + """Given a result, appends it to the existing log.""" + + raise NotImplementedError + + def update_config(self, config): + """Updates the config for logger.""" + + pass + + def close(self): + """Releases all resources used by this logger.""" + + pass + + def flush(self): + """Flushes all disk writes to storage.""" + + pass + + +@PublicAPI +class LoggerCallback(Callback): + """Base class for experiment-level logger callbacks + + This base class defines a general interface for logging events, + like trial starts, restores, ends, checkpoint saves, and receiving + trial results. + + Callbacks implementing this interface should make sure that logging + utilities are cleaned up properly on trial termination, i.e. when + ``log_trial_end`` is received. This includes e.g. closing files. + """ + + def log_trial_start(self, trial: "Trial"): + """Handle logging when a trial starts. + + Args: + trial: Trial object. + """ + pass + + def log_trial_restore(self, trial: "Trial"): + """Handle logging when a trial restores. + + Args: + trial: Trial object. + """ + pass + + def log_trial_save(self, trial: "Trial"): + """Handle logging when a trial saves a checkpoint. + + Args: + trial: Trial object. + """ + pass + + def log_trial_result(self, iteration: int, trial: "Trial", result: Dict): + """Handle logging when a trial reports a result. + + Args: + trial: Trial object. + result: Result dictionary. + """ + pass + + def log_trial_end(self, trial: "Trial", failed: bool = False): + """Handle logging when a trial ends. + + Args: + trial: Trial object. + failed: True if the Trial finished gracefully, False if + it failed (e.g. when it raised an exception). + """ + pass + + def on_trial_result( + self, + iteration: int, + trials: List["Trial"], + trial: "Trial", + result: Dict, + **info, + ): + self.log_trial_result(iteration, trial, result) + + def on_trial_start( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + self.log_trial_start(trial) + + def on_trial_restore( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + self.log_trial_restore(trial) + + def on_trial_save( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + self.log_trial_save(trial) + + def on_trial_complete( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + self.log_trial_end(trial, failed=False) + + def on_trial_error( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + self.log_trial_end(trial, failed=True) + + def _restore_from_remote(self, file_name: str, trial: "Trial") -> None: + if not trial.checkpoint: + # If there's no checkpoint, there's no logging artifacts to restore + # since we're starting from scratch. + return + + local_file = Path(trial.local_path, file_name).as_posix() + remote_file = Path(trial.storage.trial_fs_path, file_name).as_posix() + + try: + pyarrow.fs.copy_files( + remote_file, + local_file, + source_filesystem=trial.storage.storage_filesystem, + ) + logger.debug(f"Copied {remote_file} to {local_file}") + except FileNotFoundError: + logger.warning(f"Remote file not found: {remote_file}") + except Exception: + logger.exception(f"Error downloading {remote_file}") + + +@DeveloperAPI +class LegacyLoggerCallback(LoggerCallback): + """Supports logging to trial-specific `Logger` classes. + + Previously, Ray Tune logging was handled via `Logger` classes that have + been instantiated per-trial. This callback is a fallback to these + `Logger`-classes, instantiating each `Logger` class for each trial + and logging to them. + + Args: + logger_classes: Logger classes that should + be instantiated for each trial. + + """ + + def __init__(self, logger_classes: Iterable[Type[Logger]]): + self.logger_classes = list(logger_classes) + self._class_trial_loggers: Dict[Type[Logger], Dict["Trial", Logger]] = {} + + def log_trial_start(self, trial: "Trial"): + trial.init_local_path() + + for logger_class in self.logger_classes: + trial_loggers = self._class_trial_loggers.get(logger_class, {}) + if trial not in trial_loggers: + logger = logger_class(trial.config, trial.local_path, trial) + trial_loggers[trial] = logger + self._class_trial_loggers[logger_class] = trial_loggers + + def log_trial_restore(self, trial: "Trial"): + for logger_class, trial_loggers in self._class_trial_loggers.items(): + if trial in trial_loggers: + trial_loggers[trial].flush() + + def log_trial_save(self, trial: "Trial"): + for logger_class, trial_loggers in self._class_trial_loggers.items(): + if trial in trial_loggers: + trial_loggers[trial].flush() + + def log_trial_result(self, iteration: int, trial: "Trial", result: Dict): + for logger_class, trial_loggers in self._class_trial_loggers.items(): + if trial in trial_loggers: + trial_loggers[trial].on_result(result) + + def log_trial_end(self, trial: "Trial", failed: bool = False): + for logger_class, trial_loggers in self._class_trial_loggers.items(): + if trial in trial_loggers: + trial_loggers[trial].close() + + +class _RayDumper(yaml.SafeDumper): + def represent_sequence(self, tag, sequence, flow_style=None): + if len(sequence) > _SEQUENCE_LEN_FLOW_STYLE: + return super().represent_sequence(tag, sequence, flow_style=True) + return super().represent_sequence(tag, sequence, flow_style=flow_style) + + +@DeveloperAPI +def pretty_print(result, exclude: Optional[Set[str]] = None): + result = result.copy() + result.update(config=None) # drop config from pretty print + result.update(hist_stats=None) # drop hist_stats from pretty print + out = {} + for k, v in result.items(): + if v is not None and (exclude is None or k not in exclude): + out[k] = v + + cleaned = json.dumps(out, cls=SafeFallbackEncoder) + return yaml.dump(json.loads(cleaned), Dumper=_RayDumper, default_flow_style=False) diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/mlflow.py b/venv/lib/python3.10/site-packages/ray/tune/logger/mlflow.py new file mode 100644 index 0000000000000000000000000000000000000000..ac00b3d5155441988e84c69a38ed5e2444e48b78 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/logger/mlflow.py @@ -0,0 +1,3 @@ +from ray.air.integrations.mlflow import MLflowLoggerCallback + +MLflowLoggerCallback.__module__ = "ray.tune.logger.mlflow" diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/noop.py b/venv/lib/python3.10/site-packages/ray/tune/logger/noop.py new file mode 100644 index 0000000000000000000000000000000000000000..a9bae96b7cd7209cf61e8b2219c721e0eec88bcd --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/logger/noop.py @@ -0,0 +1,9 @@ +from ray.tune.logger.logger import Logger +from ray.util.annotations import Deprecated, PublicAPI + + +@Deprecated(message="`NoopLogger` will be removed in Ray 2.7.") +@PublicAPI +class NoopLogger(Logger): + def on_result(self, result): + pass diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/tensorboardx.py b/venv/lib/python3.10/site-packages/ray/tune/logger/tensorboardx.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b626ae5053c66693ea22bea56db0b57a9f689f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/logger/tensorboardx.py @@ -0,0 +1,328 @@ +import logging +from typing import TYPE_CHECKING, Dict + +import numpy as np + +from ray.air.constants import TRAINING_ITERATION +from ray.tune.logger.logger import _LOGGER_DEPRECATION_WARNING, Logger, LoggerCallback +from ray.tune.result import TIME_TOTAL_S, TIMESTEPS_TOTAL +from ray.tune.utils import flatten_dict +from ray.util.annotations import Deprecated, PublicAPI +from ray.util.debug import log_once + +if TYPE_CHECKING: + from ray.tune.experiment.trial import Trial # noqa: F401 + +logger = logging.getLogger(__name__) + +VALID_SUMMARY_TYPES = [int, float, np.float32, np.float64, np.int32, np.int64] + + +@Deprecated( + message=_LOGGER_DEPRECATION_WARNING.format( + old="TBXLogger", new="ray.tune.tensorboardx.TBXLoggerCallback" + ), + warning=True, +) +@PublicAPI +class TBXLogger(Logger): + """TensorBoardX Logger. + + Note that hparams will be written only after a trial has terminated. + This logger automatically flattens nested dicts to show on TensorBoard: + + {"a": {"b": 1, "c": 2}} -> {"a/b": 1, "a/c": 2} + """ + + VALID_HPARAMS = (str, bool, int, float, list, type(None)) + VALID_NP_HPARAMS = (np.bool_, np.float32, np.float64, np.int32, np.int64) + + def _init(self): + try: + from tensorboardX import SummaryWriter + except ImportError: + if log_once("tbx-install"): + logger.info('pip install "ray[tune]" to see TensorBoard files.') + raise + self._file_writer = SummaryWriter(self.logdir, flush_secs=30) + self.last_result = None + + def on_result(self, result: Dict): + step = result.get(TIMESTEPS_TOTAL) or result[TRAINING_ITERATION] + + tmp = result.copy() + for k in ["config", "pid", "timestamp", TIME_TOTAL_S, TRAINING_ITERATION]: + if k in tmp: + del tmp[k] # not useful to log these + + flat_result = flatten_dict(tmp, delimiter="/") + path = ["ray", "tune"] + valid_result = {} + + for attr, value in flat_result.items(): + full_attr = "/".join(path + [attr]) + if isinstance(value, tuple(VALID_SUMMARY_TYPES)) and not np.isnan(value): + valid_result[full_attr] = value + self._file_writer.add_scalar(full_attr, value, global_step=step) + elif (isinstance(value, list) and len(value) > 0) or ( + isinstance(value, np.ndarray) and value.size > 0 + ): + valid_result[full_attr] = value + + # Must be a single image. + if isinstance(value, np.ndarray) and value.ndim == 3: + self._file_writer.add_image( + full_attr, + value, + global_step=step, + ) + continue + + # Must be a batch of images. + if isinstance(value, np.ndarray) and value.ndim == 4: + self._file_writer.add_images( + full_attr, + value, + global_step=step, + ) + continue + + # Must be video + if isinstance(value, np.ndarray) and value.ndim == 5: + self._file_writer.add_video( + full_attr, value, global_step=step, fps=20 + ) + continue + + try: + self._file_writer.add_histogram(full_attr, value, global_step=step) + # In case TensorboardX still doesn't think it's a valid value + # (e.g. `[[]]`), warn and move on. + except (ValueError, TypeError): + if log_once("invalid_tbx_value"): + logger.warning( + "You are trying to log an invalid value ({}={}) " + "via {}!".format(full_attr, value, type(self).__name__) + ) + + self.last_result = valid_result + self._file_writer.flush() + + def flush(self): + if self._file_writer is not None: + self._file_writer.flush() + + def close(self): + if self._file_writer is not None: + if self.trial and self.trial.evaluated_params and self.last_result: + flat_result = flatten_dict(self.last_result, delimiter="/") + scrubbed_result = { + k: value + for k, value in flat_result.items() + if isinstance(value, tuple(VALID_SUMMARY_TYPES)) + } + self._try_log_hparams(scrubbed_result) + self._file_writer.close() + + def _try_log_hparams(self, result): + # TBX currently errors if the hparams value is None. + flat_params = flatten_dict(self.trial.evaluated_params) + scrubbed_params = { + k: v for k, v in flat_params.items() if isinstance(v, self.VALID_HPARAMS) + } + + np_params = { + k: v.tolist() + for k, v in flat_params.items() + if isinstance(v, self.VALID_NP_HPARAMS) + } + + scrubbed_params.update(np_params) + + removed = { + k: v + for k, v in flat_params.items() + if not isinstance(v, self.VALID_HPARAMS + self.VALID_NP_HPARAMS) + } + if removed: + logger.info( + "Removed the following hyperparameter values when " + "logging to tensorboard: %s", + str(removed), + ) + + from tensorboardX.summary import hparams + + try: + experiment_tag, session_start_tag, session_end_tag = hparams( + hparam_dict=scrubbed_params, metric_dict=result + ) + self._file_writer.file_writer.add_summary(experiment_tag) + self._file_writer.file_writer.add_summary(session_start_tag) + self._file_writer.file_writer.add_summary(session_end_tag) + except Exception: + logger.exception( + "TensorboardX failed to log hparams. " + "This may be due to an unsupported type " + "in the hyperparameter values." + ) + + +@PublicAPI +class TBXLoggerCallback(LoggerCallback): + """TensorBoardX Logger. + + Note that hparams will be written only after a trial has terminated. + This logger automatically flattens nested dicts to show on TensorBoard: + + {"a": {"b": 1, "c": 2}} -> {"a/b": 1, "a/c": 2} + """ + + _SAVED_FILE_TEMPLATES = ["events.out.tfevents.*"] + + VALID_HPARAMS = (str, bool, int, float, list, type(None)) + VALID_NP_HPARAMS = (np.bool_, np.float32, np.float64, np.int32, np.int64) + + def __init__(self): + try: + from tensorboardX import SummaryWriter + + self._summary_writer_cls = SummaryWriter + except ImportError: + if log_once("tbx-install"): + logger.info('pip install "ray[tune]" to see TensorBoard files.') + raise + self._trial_writer: Dict["Trial", SummaryWriter] = {} + self._trial_result: Dict["Trial", Dict] = {} + + def log_trial_start(self, trial: "Trial"): + if trial in self._trial_writer: + self._trial_writer[trial].close() + trial.init_local_path() + self._trial_writer[trial] = self._summary_writer_cls( + trial.local_path, flush_secs=30 + ) + self._trial_result[trial] = {} + + def log_trial_result(self, iteration: int, trial: "Trial", result: Dict): + if trial not in self._trial_writer: + self.log_trial_start(trial) + + step = result.get(TIMESTEPS_TOTAL) or result[TRAINING_ITERATION] + + tmp = result.copy() + for k in ["config", "pid", "timestamp", TIME_TOTAL_S, TRAINING_ITERATION]: + if k in tmp: + del tmp[k] # not useful to log these + + flat_result = flatten_dict(tmp, delimiter="/") + path = ["ray", "tune"] + valid_result = {} + + for attr, value in flat_result.items(): + full_attr = "/".join(path + [attr]) + if isinstance(value, tuple(VALID_SUMMARY_TYPES)) and not np.isnan(value): + valid_result[full_attr] = value + self._trial_writer[trial].add_scalar(full_attr, value, global_step=step) + elif (isinstance(value, list) and len(value) > 0) or ( + isinstance(value, np.ndarray) and value.size > 0 + ): + valid_result[full_attr] = value + + # Must be a single image. + if isinstance(value, np.ndarray) and value.ndim == 3: + self._trial_writer[trial].add_image( + full_attr, + value, + global_step=step, + ) + continue + + # Must be a batch of images. + if isinstance(value, np.ndarray) and value.ndim == 4: + self._trial_writer[trial].add_images( + full_attr, + value, + global_step=step, + ) + continue + + # Must be video + if isinstance(value, np.ndarray) and value.ndim == 5: + self._trial_writer[trial].add_video( + full_attr, value, global_step=step, fps=20 + ) + continue + + try: + self._trial_writer[trial].add_histogram( + full_attr, value, global_step=step + ) + # In case TensorboardX still doesn't think it's a valid value + # (e.g. `[[]]`), warn and move on. + except (ValueError, TypeError): + if log_once("invalid_tbx_value"): + logger.warning( + "You are trying to log an invalid value ({}={}) " + "via {}!".format(full_attr, value, type(self).__name__) + ) + + self._trial_result[trial] = valid_result + self._trial_writer[trial].flush() + + def log_trial_end(self, trial: "Trial", failed: bool = False): + if trial in self._trial_writer: + if trial and trial.evaluated_params and self._trial_result[trial]: + flat_result = flatten_dict(self._trial_result[trial], delimiter="/") + scrubbed_result = { + k: value + for k, value in flat_result.items() + if isinstance(value, tuple(VALID_SUMMARY_TYPES)) + } + self._try_log_hparams(trial, scrubbed_result) + self._trial_writer[trial].close() + del self._trial_writer[trial] + del self._trial_result[trial] + + def _try_log_hparams(self, trial: "Trial", result: Dict): + # TBX currently errors if the hparams value is None. + flat_params = flatten_dict(trial.evaluated_params) + scrubbed_params = { + k: v for k, v in flat_params.items() if isinstance(v, self.VALID_HPARAMS) + } + + np_params = { + k: v.tolist() + for k, v in flat_params.items() + if isinstance(v, self.VALID_NP_HPARAMS) + } + + scrubbed_params.update(np_params) + + removed = { + k: v + for k, v in flat_params.items() + if not isinstance(v, self.VALID_HPARAMS + self.VALID_NP_HPARAMS) + } + if removed: + logger.info( + "Removed the following hyperparameter values when " + "logging to tensorboard: %s", + str(removed), + ) + + from tensorboardX.summary import hparams + + try: + experiment_tag, session_start_tag, session_end_tag = hparams( + hparam_dict=scrubbed_params, metric_dict=result + ) + self._trial_writer[trial].file_writer.add_summary(experiment_tag) + self._trial_writer[trial].file_writer.add_summary(session_start_tag) + self._trial_writer[trial].file_writer.add_summary(session_end_tag) + except Exception: + logger.exception( + "TensorboardX failed to log hparams. " + "This may be due to an unsupported type " + "in the hyperparameter values." + ) diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/unified.py b/venv/lib/python3.10/site-packages/ray/tune/logger/unified.py new file mode 100644 index 0000000000000000000000000000000000000000..91af70cbd86c12044e012dd75302733fb4056c33 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/logger/unified.py @@ -0,0 +1,74 @@ +import logging +from typing import TYPE_CHECKING, Dict, List, Optional, Type + +from ray.tune.logger import DEFAULT_LOGGERS +from ray.tune.logger.json import JsonLogger +from ray.tune.logger.logger import Logger +from ray.util import log_once +from ray.util.annotations import Deprecated, PublicAPI + +logger = logging.getLogger(__name__) + + +if TYPE_CHECKING: + from ray.tune.experiment.trial import Trial # noqa: F401 + + +@Deprecated(message="`UnifiedLogger` will be removed in Ray 2.7.", warning=True) +@PublicAPI +class UnifiedLogger(Logger): + """Unified result logger for TensorBoard, rllab/viskit, plain json. + + Arguments: + config: Configuration passed to all logger creators. + logdir: Directory for all logger creators to log to. + loggers: List of logger creators. Defaults to CSV, Tensorboard, + and JSON loggers. + """ + + def __init__( + self, + config: Dict, + logdir: str, + trial: Optional["Trial"] = None, + loggers: Optional[List[Type[Logger]]] = None, + ): + if loggers is None: + self._logger_cls_list = DEFAULT_LOGGERS + else: + self._logger_cls_list = loggers + if JsonLogger not in self._logger_cls_list: + if log_once("JsonLogger"): + logger.warning( + "JsonLogger not provided. The ExperimentAnalysis tool is " + "disabled." + ) + + super(UnifiedLogger, self).__init__(config, logdir, trial) + + def _init(self): + self._loggers = [] + for cls in self._logger_cls_list: + try: + self._loggers.append(cls(self.config, self.logdir, self.trial)) + except Exception as exc: + if log_once(f"instantiate:{cls.__name__}"): + logger.warning( + "Could not instantiate %s: %s.", cls.__name__, str(exc) + ) + + def on_result(self, result): + for _logger in self._loggers: + _logger.on_result(result) + + def update_config(self, config): + for _logger in self._loggers: + _logger.update_config(config) + + def close(self): + for _logger in self._loggers: + _logger.close() + + def flush(self): + for _logger in self._loggers: + _logger.flush() diff --git a/venv/lib/python3.10/site-packages/ray/tune/logger/wandb.py b/venv/lib/python3.10/site-packages/ray/tune/logger/wandb.py new file mode 100644 index 0000000000000000000000000000000000000000..85e80b60bfe8ce0bfa187d0b29dd4caec39eb725 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/logger/wandb.py @@ -0,0 +1,3 @@ +from ray.air.integrations.wandb import WandbLoggerCallback + +WandbLoggerCallback.__module__ = "ray.tune.logger.wandb" diff --git a/venv/lib/python3.10/site-packages/ray/tune/progress_reporter.py b/venv/lib/python3.10/site-packages/ray/tune/progress_reporter.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1c642fbe5f7c3c5bd18b1818fef74008659da1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/progress_reporter.py @@ -0,0 +1,1596 @@ +from __future__ import print_function + +import collections +import datetime +import numbers +import sys +import textwrap +import time +import warnings +from pathlib import Path +from typing import Any, Callable, Collection, Dict, List, Optional, Tuple, Union + +import numpy as np +import pandas as pd + +import ray +from ray._private.dict import flatten_dict +from ray._private.thirdparty.tabulate.tabulate import tabulate +from ray.air.constants import EXPR_ERROR_FILE, TRAINING_ITERATION +from ray.air.util.node import _force_on_current_node +from ray.experimental.tqdm_ray import safe_print +from ray.tune.callback import Callback +from ray.tune.experiment.trial import DEBUG_PRINT_INTERVAL, Trial, _Location +from ray.tune.logger import pretty_print +from ray.tune.result import ( + AUTO_RESULT_KEYS, + DEFAULT_METRIC, + DONE, + EPISODE_REWARD_MEAN, + EXPERIMENT_TAG, + MEAN_ACCURACY, + MEAN_LOSS, + NODE_IP, + PID, + TIME_TOTAL_S, + TIMESTEPS_TOTAL, + TRIAL_ID, +) +from ray.tune.trainable import Trainable +from ray.tune.utils import unflattened_lookup +from ray.tune.utils.log import Verbosity, has_verbosity, set_verbosity +from ray.util.annotations import DeveloperAPI, PublicAPI +from ray.util.queue import Empty, Queue +from ray.widgets import Template + +try: + from collections.abc import Mapping, MutableMapping +except ImportError: + from collections import Mapping, MutableMapping + + +IS_NOTEBOOK = ray.widgets.util.in_notebook() + +SKIP_RESULTS_IN_REPORT = {"config", TRIAL_ID, EXPERIMENT_TAG, DONE} + + +@PublicAPI +class ProgressReporter: + """Abstract class for experiment progress reporting. + + `should_report()` is called to determine whether or not `report()` should + be called. Tune will call these functions after trial state transitions, + receiving training results, and so on. + """ + + def setup( + self, + start_time: Optional[float] = None, + total_samples: Optional[int] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + **kwargs, + ): + """Setup progress reporter for a new Ray Tune run. + + This function is used to initialize parameters that are set on runtime. + It will be called before any of the other methods. + + Defaults to no-op. + + Args: + start_time: Timestamp when the Ray Tune run is started. + total_samples: Number of samples the Ray Tune run will run. + metric: Metric to optimize. + mode: Must be one of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. + **kwargs: Keyword arguments for forward-compatibility. + """ + pass + + def should_report(self, trials: List[Trial], done: bool = False): + """Returns whether or not progress should be reported. + + Args: + trials: Trials to report on. + done: Whether this is the last progress report attempt. + """ + raise NotImplementedError + + def report(self, trials: List[Trial], done: bool, *sys_info: Dict): + """Reports progress across trials. + + Args: + trials: Trials to report on. + done: Whether this is the last progress report attempt. + sys_info: System info. + """ + raise NotImplementedError + + +@DeveloperAPI +class TuneReporterBase(ProgressReporter): + """Abstract base class for the default Tune reporters. + + If metric_columns is not overridden, Tune will attempt to automatically + infer the metrics being outputted, up to 'infer_limit' number of + metrics. + + Args: + metric_columns: Names of metrics to + include in progress table. If this is a dict, the keys should + be metric names and the values should be the displayed names. + If this is a list, the metric name is used directly. + parameter_columns: Names of parameters to + include in progress table. If this is a dict, the keys should + be parameter names and the values should be the displayed names. + If this is a list, the parameter name is used directly. If empty, + defaults to all available parameters. + max_progress_rows: Maximum number of rows to print + in the progress table. The progress table describes the + progress of each trial. Defaults to 20. + max_error_rows: Maximum number of rows to print in the + error table. The error table lists the error file, if any, + corresponding to each trial. Defaults to 20. + max_column_length: Maximum column length (in characters). Column + headers and values longer than this will be abbreviated. + max_report_frequency: Maximum report frequency in seconds. + Defaults to 5s. + infer_limit: Maximum number of metrics to automatically infer + from tune results. + print_intermediate_tables: Print intermediate result + tables. If None (default), will be set to True for verbosity + levels above 3, otherwise False. If True, intermediate tables + will be printed with experiment progress. If False, tables + will only be printed at then end of the tuning run for verbosity + levels greater than 2. + metric: Metric used to determine best current trial. + mode: One of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. + sort_by_metric: Sort terminated trials by metric in the + intermediate table. Defaults to False. + """ + + # Truncated representations of column names (to accommodate small screens). + DEFAULT_COLUMNS = collections.OrderedDict( + { + MEAN_ACCURACY: "acc", + MEAN_LOSS: "loss", + TRAINING_ITERATION: "iter", + TIME_TOTAL_S: "total time (s)", + TIMESTEPS_TOTAL: "ts", + EPISODE_REWARD_MEAN: "reward", + } + ) + VALID_SUMMARY_TYPES = { + int, + float, + np.float32, + np.float64, + np.int32, + np.int64, + type(None), + } + + def __init__( + self, + *, + metric_columns: Optional[Union[List[str], Dict[str, str]]] = None, + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + total_samples: Optional[int] = None, + max_progress_rows: int = 20, + max_error_rows: int = 20, + max_column_length: int = 20, + max_report_frequency: int = 5, + infer_limit: int = 3, + print_intermediate_tables: Optional[bool] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, + ): + self._total_samples = total_samples + self._metrics_override = metric_columns is not None + self._inferred_metrics = {} + self._metric_columns = metric_columns or self.DEFAULT_COLUMNS.copy() + self._parameter_columns = parameter_columns or [] + self._max_progress_rows = max_progress_rows + self._max_error_rows = max_error_rows + self._max_column_length = max_column_length + self._infer_limit = infer_limit + + if print_intermediate_tables is None: + self._print_intermediate_tables = has_verbosity(Verbosity.V3_TRIAL_DETAILS) + else: + self._print_intermediate_tables = print_intermediate_tables + + self._max_report_freqency = max_report_frequency + self._last_report_time = 0 + + self._start_time = time.time() + + self._metric = metric + self._mode = mode + self._sort_by_metric = sort_by_metric + + def setup( + self, + start_time: Optional[float] = None, + total_samples: Optional[int] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + **kwargs, + ): + self.set_start_time(start_time) + self.set_total_samples(total_samples) + self.set_search_properties(metric=metric, mode=mode) + + def set_search_properties(self, metric: Optional[str], mode: Optional[str]): + if (self._metric and metric) or (self._mode and mode): + raise ValueError( + "You passed a `metric` or `mode` argument to `tune.TuneConfig()`, but " + "the reporter you are using was already instantiated with their " + "own `metric` and `mode` parameters. Either remove the arguments " + "from your reporter or from your call to `tune.TuneConfig()`" + ) + + if metric: + self._metric = metric + if mode: + self._mode = mode + + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + return True + + def set_total_samples(self, total_samples: int): + self._total_samples = total_samples + + def set_start_time(self, timestamp: Optional[float] = None): + if timestamp is not None: + self._start_time = time.time() + else: + self._start_time = timestamp + + def should_report(self, trials: List[Trial], done: bool = False): + if time.time() - self._last_report_time > self._max_report_freqency: + self._last_report_time = time.time() + return True + return done + + def add_metric_column(self, metric: str, representation: Optional[str] = None): + """Adds a metric to the existing columns. + + Args: + metric: Metric to add. This must be a metric being returned + in training step results. + representation: Representation to use in table. Defaults to + `metric`. + """ + self._metrics_override = True + if metric in self._metric_columns: + raise ValueError("Column {} already exists.".format(metric)) + + if isinstance(self._metric_columns, MutableMapping): + representation = representation or metric + self._metric_columns[metric] = representation + else: + if representation is not None and representation != metric: + raise ValueError( + "`representation` cannot differ from `metric` " + "if this reporter was initialized with a list " + "of metric columns." + ) + self._metric_columns.append(metric) + + def add_parameter_column( + self, parameter: str, representation: Optional[str] = None + ): + """Adds a parameter to the existing columns. + + Args: + parameter: Parameter to add. This must be a parameter + specified in the configuration. + representation: Representation to use in table. Defaults to + `parameter`. + """ + if parameter in self._parameter_columns: + raise ValueError("Column {} already exists.".format(parameter)) + + if isinstance(self._parameter_columns, MutableMapping): + representation = representation or parameter + self._parameter_columns[parameter] = representation + else: + if representation is not None and representation != parameter: + raise ValueError( + "`representation` cannot differ from `parameter` " + "if this reporter was initialized with a list " + "of metric columns." + ) + self._parameter_columns.append(parameter) + + def _progress_str( + self, + trials: List[Trial], + done: bool, + *sys_info: Dict, + fmt: str = "psql", + delim: str = "\n", + ): + """Returns full progress string. + + This string contains a progress table and error table. The progress + table describes the progress of each trial. The error table lists + the error file, if any, corresponding to each trial. The latter only + exists if errors have occurred. + + Args: + trials: Trials to report on. + done: Whether this is the last progress report attempt. + fmt: Table format. See `tablefmt` in tabulate API. + delim: Delimiter between messages. + """ + if self._sort_by_metric and (self._metric is None or self._mode is None): + self._sort_by_metric = False + warnings.warn( + "Both 'metric' and 'mode' must be set to be able " + "to sort by metric. No sorting is performed." + ) + if not self._metrics_override: + user_metrics = self._infer_user_metrics(trials, self._infer_limit) + self._metric_columns.update(user_metrics) + messages = [ + "== Status ==", + _time_passed_str(self._start_time, time.time()), + *sys_info, + ] + if done: + max_progress = None + max_error = None + else: + max_progress = self._max_progress_rows + max_error = self._max_error_rows + + current_best_trial, metric = self._current_best_trial(trials) + if current_best_trial: + messages.append( + _best_trial_str(current_best_trial, metric, self._parameter_columns) + ) + + if has_verbosity(Verbosity.V1_EXPERIMENT): + # Will filter the table in `trial_progress_str` + messages.append( + _trial_progress_str( + trials, + metric_columns=self._metric_columns, + parameter_columns=self._parameter_columns, + total_samples=self._total_samples, + force_table=self._print_intermediate_tables, + fmt=fmt, + max_rows=max_progress, + max_column_length=self._max_column_length, + done=done, + metric=self._metric, + mode=self._mode, + sort_by_metric=self._sort_by_metric, + ) + ) + messages.append(_trial_errors_str(trials, fmt=fmt, max_rows=max_error)) + + return delim.join(messages) + delim + + def _infer_user_metrics(self, trials: List[Trial], limit: int = 4): + """Try to infer the metrics to print out.""" + if len(self._inferred_metrics) >= limit: + return self._inferred_metrics + self._inferred_metrics = {} + for t in trials: + if not t.last_result: + continue + for metric, value in t.last_result.items(): + if metric not in self.DEFAULT_COLUMNS: + if metric not in AUTO_RESULT_KEYS: + if type(value) in self.VALID_SUMMARY_TYPES: + self._inferred_metrics[metric] = metric + + if len(self._inferred_metrics) >= limit: + return self._inferred_metrics + return self._inferred_metrics + + def _current_best_trial(self, trials: List[Trial]): + if not trials: + return None, None + + metric, mode = self._metric, self._mode + # If no metric has been set, see if exactly one has been reported + # and use that one. `mode` must still be set. + if not metric: + if len(self._inferred_metrics) == 1: + metric = list(self._inferred_metrics.keys())[0] + + if not metric or not mode: + return None, metric + + metric_op = 1.0 if mode == "max" else -1.0 + best_metric = float("-inf") + best_trial = None + for t in trials: + if not t.last_result: + continue + metric_value = unflattened_lookup(metric, t.last_result, default=None) + if pd.isnull(metric_value): + continue + if not best_trial or metric_value * metric_op > best_metric: + best_metric = metric_value * metric_op + best_trial = t + return best_trial, metric + + +@DeveloperAPI +class RemoteReporterMixin: + """Remote reporter abstract mixin class. + + Subclasses of this class will use a Ray Queue to display output + on the driver side when running Ray Client.""" + + @property + def output_queue(self) -> Queue: + return getattr(self, "_output_queue", None) + + @output_queue.setter + def output_queue(self, value: Queue): + self._output_queue = value + + def display(self, string: str) -> None: + """Display the progress string. + + Args: + string: String to display. + """ + raise NotImplementedError + + +@PublicAPI +class JupyterNotebookReporter(TuneReporterBase, RemoteReporterMixin): + """Jupyter notebook-friendly Reporter that can update display in-place. + + Args: + overwrite: Flag for overwriting the cell contents before initialization. + metric_columns: Names of metrics to + include in progress table. If this is a dict, the keys should + be metric names and the values should be the displayed names. + If this is a list, the metric name is used directly. + parameter_columns: Names of parameters to + include in progress table. If this is a dict, the keys should + be parameter names and the values should be the displayed names. + If this is a list, the parameter name is used directly. If empty, + defaults to all available parameters. + max_progress_rows: Maximum number of rows to print + in the progress table. The progress table describes the + progress of each trial. Defaults to 20. + max_error_rows: Maximum number of rows to print in the + error table. The error table lists the error file, if any, + corresponding to each trial. Defaults to 20. + max_column_length: Maximum column length (in characters). Column + headers and values longer than this will be abbreviated. + max_report_frequency: Maximum report frequency in seconds. + Defaults to 5s. + infer_limit: Maximum number of metrics to automatically infer + from tune results. + print_intermediate_tables: Print intermediate result + tables. If None (default), will be set to True for verbosity + levels above 3, otherwise False. If True, intermediate tables + will be printed with experiment progress. If False, tables + will only be printed at then end of the tuning run for verbosity + levels greater than 2. + metric: Metric used to determine best current trial. + mode: One of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. + sort_by_metric: Sort terminated trials by metric in the + intermediate table. Defaults to False. + """ + + def __init__( + self, + *, + overwrite: bool = True, + metric_columns: Optional[Union[List[str], Dict[str, str]]] = None, + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + total_samples: Optional[int] = None, + max_progress_rows: int = 20, + max_error_rows: int = 20, + max_column_length: int = 20, + max_report_frequency: int = 5, + infer_limit: int = 3, + print_intermediate_tables: Optional[bool] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, + ): + super(JupyterNotebookReporter, self).__init__( + metric_columns=metric_columns, + parameter_columns=parameter_columns, + total_samples=total_samples, + max_progress_rows=max_progress_rows, + max_error_rows=max_error_rows, + max_column_length=max_column_length, + max_report_frequency=max_report_frequency, + infer_limit=infer_limit, + print_intermediate_tables=print_intermediate_tables, + metric=metric, + mode=mode, + sort_by_metric=sort_by_metric, + ) + + if not IS_NOTEBOOK: + warnings.warn( + "You are using the `JupyterNotebookReporter`, but not " + "IPython/Jupyter-compatible environment was detected. " + "If this leads to unformatted output (e.g. like " + "), consider passing " + "a `CLIReporter` as the `progress_reporter` argument " + "to `tune.RunConfig()` instead." + ) + + self._overwrite = overwrite + self._display_handle = None + self.display("") # initialize empty display to update later + + def report(self, trials: List[Trial], done: bool, *sys_info: Dict): + progress = self._progress_html(trials, done, *sys_info) + + if self.output_queue is not None: + # If an output queue is set, send string + self.output_queue.put(progress) + else: + # Else, output directly + self.display(progress) + + def display(self, string: str) -> None: + from IPython.display import HTML, clear_output, display + + if not self._display_handle: + if self._overwrite: + clear_output(wait=True) + self._display_handle = display(HTML(string), display_id=True) + else: + self._display_handle.update(HTML(string)) + + def _progress_html(self, trials: List[Trial], done: bool, *sys_info) -> str: + """Generate an HTML-formatted progress update. + + Args: + trials: List of trials for which progress should be + displayed + done: True if the trials are finished, False otherwise + *sys_info: System information to be displayed + + Returns: + Progress update to be rendered in a notebook, including HTML + tables and formatted error messages. Includes + - Duration of the tune job + - Memory consumption + - Trial progress table, with information about each experiment + """ + if not self._metrics_override: + user_metrics = self._infer_user_metrics(trials, self._infer_limit) + self._metric_columns.update(user_metrics) + + current_time, running_for = _get_time_str(self._start_time, time.time()) + used_gb, total_gb, memory_message = _get_memory_usage() + + status_table = tabulate( + [ + ("Current time:", current_time), + ("Running for:", running_for), + ("Memory:", f"{used_gb}/{total_gb} GiB"), + ], + tablefmt="html", + ) + trial_progress_data = _trial_progress_table( + trials=trials, + metric_columns=self._metric_columns, + parameter_columns=self._parameter_columns, + fmt="html", + max_rows=None if done else self._max_progress_rows, + metric=self._metric, + mode=self._mode, + sort_by_metric=self._sort_by_metric, + max_column_length=self._max_column_length, + ) + + trial_progress = trial_progress_data[0] + trial_progress_messages = trial_progress_data[1:] + trial_errors = _trial_errors_str( + trials, fmt="html", max_rows=None if done else self._max_error_rows + ) + + if any([memory_message, trial_progress_messages, trial_errors]): + msg = Template("tune_status_messages.html.j2").render( + memory_message=memory_message, + trial_progress_messages=trial_progress_messages, + trial_errors=trial_errors, + ) + else: + msg = None + + return Template("tune_status.html.j2").render( + status_table=status_table, + sys_info_message=_generate_sys_info_str(*sys_info), + trial_progress=trial_progress, + messages=msg, + ) + + +@PublicAPI +class CLIReporter(TuneReporterBase): + """Command-line reporter + + Args: + metric_columns: Names of metrics to + include in progress table. If this is a dict, the keys should + be metric names and the values should be the displayed names. + If this is a list, the metric name is used directly. + parameter_columns: Names of parameters to + include in progress table. If this is a dict, the keys should + be parameter names and the values should be the displayed names. + If this is a list, the parameter name is used directly. If empty, + defaults to all available parameters. + max_progress_rows: Maximum number of rows to print + in the progress table. The progress table describes the + progress of each trial. Defaults to 20. + max_error_rows: Maximum number of rows to print in the + error table. The error table lists the error file, if any, + corresponding to each trial. Defaults to 20. + max_column_length: Maximum column length (in characters). Column + headers and values longer than this will be abbreviated. + max_report_frequency: Maximum report frequency in seconds. + Defaults to 5s. + infer_limit: Maximum number of metrics to automatically infer + from tune results. + print_intermediate_tables: Print intermediate result + tables. If None (default), will be set to True for verbosity + levels above 3, otherwise False. If True, intermediate tables + will be printed with experiment progress. If False, tables + will only be printed at then end of the tuning run for verbosity + levels greater than 2. + metric: Metric used to determine best current trial. + mode: One of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. + sort_by_metric: Sort terminated trials by metric in the + intermediate table. Defaults to False. + """ + + def __init__( + self, + *, + metric_columns: Optional[Union[List[str], Dict[str, str]]] = None, + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + total_samples: Optional[int] = None, + max_progress_rows: int = 20, + max_error_rows: int = 20, + max_column_length: int = 20, + max_report_frequency: int = 5, + infer_limit: int = 3, + print_intermediate_tables: Optional[bool] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, + ): + super(CLIReporter, self).__init__( + metric_columns=metric_columns, + parameter_columns=parameter_columns, + total_samples=total_samples, + max_progress_rows=max_progress_rows, + max_error_rows=max_error_rows, + max_column_length=max_column_length, + max_report_frequency=max_report_frequency, + infer_limit=infer_limit, + print_intermediate_tables=print_intermediate_tables, + metric=metric, + mode=mode, + sort_by_metric=sort_by_metric, + ) + + def _print(self, msg: str): + safe_print(msg) + + def report(self, trials: List[Trial], done: bool, *sys_info: Dict): + self._print(self._progress_str(trials, done, *sys_info)) + + +def _get_memory_usage() -> Tuple[float, float, Optional[str]]: + """Get the current memory consumption. + + Returns: + Memory used, memory available, and optionally a warning + message to be shown to the user when memory consumption is higher + than 90% or if `psutil` is not installed + """ + try: + import ray # noqa F401 + + import psutil + + total_gb = psutil.virtual_memory().total / (1024**3) + used_gb = total_gb - psutil.virtual_memory().available / (1024**3) + if used_gb > total_gb * 0.9: + message = ( + ": ***LOW MEMORY*** less than 10% of the memory on " + "this node is available for use. This can cause " + "unexpected crashes. Consider " + "reducing the memory used by your application " + "or reducing the Ray object store size by setting " + "`object_store_memory` when calling `ray.init`." + ) + else: + message = None + + return round(used_gb, 1), round(total_gb, 1), message + except ImportError: + return ( + np.nan, + np.nan, + "Unknown memory usage. Please run `pip install psutil` to resolve", + ) + + +def _get_time_str(start_time: float, current_time: float) -> Tuple[str, str]: + """Get strings representing the current and elapsed time. + + Args: + start_time: POSIX timestamp of the start of the tune run + current_time: POSIX timestamp giving the current time + + Returns: + Current time and elapsed time for the current run + """ + current_time_dt = datetime.datetime.fromtimestamp(current_time) + start_time_dt = datetime.datetime.fromtimestamp(start_time) + delta: datetime.timedelta = current_time_dt - start_time_dt + + rest = delta.total_seconds() + days = rest // (60 * 60 * 24) + + rest -= days * (60 * 60 * 24) + hours = rest // (60 * 60) + + rest -= hours * (60 * 60) + minutes = rest // 60 + + seconds = rest - minutes * 60 + + if days > 0: + running_for_str = f"{days:.0f} days, " + else: + running_for_str = "" + + running_for_str += f"{hours:02.0f}:{minutes:02.0f}:{seconds:05.2f}" + + return f"{current_time_dt:%Y-%m-%d %H:%M:%S}", running_for_str + + +def _time_passed_str(start_time: float, current_time: float) -> str: + """Generate a message describing the current and elapsed time in the run. + + Args: + start_time: POSIX timestamp of the start of the tune run + current_time: POSIX timestamp giving the current time + + Returns: + Message with the current and elapsed time for the current tune run, + formatted to be displayed to the user + """ + current_time_str, running_for_str = _get_time_str(start_time, current_time) + return f"Current time: {current_time_str} " f"(running for {running_for_str})" + + +def _get_trials_by_state(trials: List[Trial]): + trials_by_state = collections.defaultdict(list) + for t in trials: + trials_by_state[t.status].append(t) + return trials_by_state + + +def _trial_progress_str( + trials: List[Trial], + metric_columns: Union[List[str], Dict[str, str]], + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + total_samples: int = 0, + force_table: bool = False, + fmt: str = "psql", + max_rows: Optional[int] = None, + max_column_length: int = 20, + done: bool = False, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, +): + """Returns a human readable message for printing to the console. + + This contains a table where each row represents a trial, its parameters + and the current values of its metrics. + + Args: + trials: List of trials to get progress string for. + metric_columns: Names of metrics to include. + If this is a dict, the keys are metric names and the values are + the names to use in the message. If this is a list, the metric + name is used in the message directly. + parameter_columns: Names of parameters to + include. If this is a dict, the keys are parameter names and the + values are the names to use in the message. If this is a list, + the parameter name is used in the message directly. If this is + empty, all parameters are used in the message. + total_samples: Total number of trials that will be generated. + force_table: Force printing a table. If False, a table will + be printed only at the end of the training for verbosity levels + above `Verbosity.V2_TRIAL_NORM`. + fmt: Output format (see tablefmt in tabulate API). + max_rows: Maximum number of rows in the trial table. Defaults to + unlimited. + max_column_length: Maximum column length (in characters). + done: True indicates that the tuning run finished. + metric: Metric used to sort trials. + mode: One of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. + sort_by_metric: Sort terminated trials by metric in the + intermediate table. Defaults to False. + """ + messages = [] + delim = "
" if fmt == "html" else "\n" + if len(trials) < 1: + return delim.join(messages) + + num_trials = len(trials) + trials_by_state = _get_trials_by_state(trials) + + for local_dir in sorted({t.local_experiment_path for t in trials}): + messages.append("Result logdir: {}".format(local_dir)) + + num_trials_strs = [ + "{} {}".format(len(trials_by_state[state]), state) + for state in sorted(trials_by_state) + ] + + if total_samples and total_samples >= sys.maxsize: + total_samples = "infinite" + + messages.append( + "Number of trials: {}{} ({})".format( + num_trials, + f"/{total_samples}" if total_samples else "", + ", ".join(num_trials_strs), + ) + ) + + if force_table or (has_verbosity(Verbosity.V2_TRIAL_NORM) and done): + messages += _trial_progress_table( + trials=trials, + metric_columns=metric_columns, + parameter_columns=parameter_columns, + fmt=fmt, + max_rows=max_rows, + metric=metric, + mode=mode, + sort_by_metric=sort_by_metric, + max_column_length=max_column_length, + ) + + return delim.join(messages) + + +def _max_len( + value: Any, max_len: int = 20, add_addr: bool = False, wrap: bool = False +) -> Any: + """Abbreviate a string representation of an object to `max_len` characters. + + For numbers, booleans and None, the original value will be returned for + correct rendering in the table formatting tool. + + Args: + value: Object to be represented as a string. + max_len: Maximum return string length. + add_addr: If True, will add part of the object address to the end of the + string, e.g. to identify different instances of the same class. If + False, three dots (``...``) will be used instead. + """ + if value is None or isinstance(value, (int, float, numbers.Number, bool)): + return value + + string = str(value) + if len(string) <= max_len: + return string + + if wrap: + # Maximum two rows. + # Todo: Make this configurable in the refactor + if len(value) > max_len * 2: + value = "..." + string[(3 - (max_len * 2)) :] + + wrapped = textwrap.wrap(value, width=max_len) + return "\n".join(wrapped) + + if add_addr and not isinstance(value, (int, float, bool)): + result = f"{string[: (max_len - 5)]}_{hex(id(value))[-4:]}" + return result + + result = "..." + string[(3 - max_len) :] + return result + + +def _get_progress_table_data( + trials: List[Trial], + metric_columns: Union[List[str], Dict[str, str]], + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + max_rows: Optional[int] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, + max_column_length: int = 20, +) -> Tuple[List, List[str], Tuple[bool, str]]: + """Generate a table showing the current progress of tuning trials. + + Args: + trials: List of trials for which progress is to be shown. + metric_columns: Metrics to be displayed in the table. + parameter_columns: List of parameters to be included in the data + max_rows: Maximum number of rows to show. If there's overflow, a + message will be shown to the user indicating that some rows + are not displayed + metric: Metric which is being tuned + mode: Sort the table in descending order if mode is "max"; + ascending otherwise + sort_by_metric: If true, the table will be sorted by the metric + max_column_length: Max number of characters in each column + + Returns: + - Trial data + - List of column names + - Overflow tuple: + - boolean indicating whether the table has rows which are hidden + - string with info about the overflowing rows + """ + num_trials = len(trials) + trials_by_state = _get_trials_by_state(trials) + + # Sort terminated trials by metric and mode, descending if mode is "max" + if sort_by_metric: + trials_by_state[Trial.TERMINATED] = sorted( + trials_by_state[Trial.TERMINATED], + reverse=(mode == "max"), + key=lambda t: unflattened_lookup(metric, t.last_result, default=None), + ) + + state_tbl_order = [ + Trial.RUNNING, + Trial.PAUSED, + Trial.PENDING, + Trial.TERMINATED, + Trial.ERROR, + ] + max_rows = max_rows or float("inf") + if num_trials > max_rows: + # TODO(ujvl): suggestion for users to view more rows. + trials_by_state_trunc = _fair_filter_trials( + trials_by_state, max_rows, sort_by_metric + ) + trials = [] + overflow_strs = [] + for state in state_tbl_order: + if state not in trials_by_state: + continue + trials += trials_by_state_trunc[state] + num = len(trials_by_state[state]) - len(trials_by_state_trunc[state]) + if num > 0: + overflow_strs.append("{} {}".format(num, state)) + # Build overflow string. + overflow = num_trials - max_rows + overflow_str = ", ".join(overflow_strs) + else: + overflow = False + overflow_str = "" + trials = [] + for state in state_tbl_order: + if state not in trials_by_state: + continue + trials += trials_by_state[state] + + # Pre-process trials to figure out what columns to show. + if isinstance(metric_columns, Mapping): + metric_keys = list(metric_columns.keys()) + else: + metric_keys = metric_columns + + metric_keys = [ + k + for k in metric_keys + if any( + unflattened_lookup(k, t.last_result, default=None) is not None + for t in trials + ) + ] + + if not parameter_columns: + parameter_keys = sorted(set().union(*[t.evaluated_params for t in trials])) + elif isinstance(parameter_columns, Mapping): + parameter_keys = list(parameter_columns.keys()) + else: + parameter_keys = parameter_columns + + # Build trial rows. + trial_table = [ + _get_trial_info( + trial, parameter_keys, metric_keys, max_column_length=max_column_length + ) + for trial in trials + ] + # Format column headings + if isinstance(metric_columns, Mapping): + formatted_metric_columns = [ + _max_len( + metric_columns[k], max_len=max_column_length, add_addr=False, wrap=True + ) + for k in metric_keys + ] + else: + formatted_metric_columns = [ + _max_len(k, max_len=max_column_length, add_addr=False, wrap=True) + for k in metric_keys + ] + if isinstance(parameter_columns, Mapping): + formatted_parameter_columns = [ + _max_len( + parameter_columns[k], + max_len=max_column_length, + add_addr=False, + wrap=True, + ) + for k in parameter_keys + ] + else: + formatted_parameter_columns = [ + _max_len(k, max_len=max_column_length, add_addr=False, wrap=True) + for k in parameter_keys + ] + columns = ( + ["Trial name", "status", "loc"] + + formatted_parameter_columns + + formatted_metric_columns + ) + + return trial_table, columns, (overflow, overflow_str) + + +def _trial_progress_table( + trials: List[Trial], + metric_columns: Union[List[str], Dict[str, str]], + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + fmt: str = "psql", + max_rows: Optional[int] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, + max_column_length: int = 20, +) -> List[str]: + """Generate a list of trial progress table messages. + + Args: + trials: List of trials for which progress is to be shown. + metric_columns: Metrics to be displayed in the table. + parameter_columns: List of parameters to be included in the data + fmt: Format of the table; passed to tabulate as the fmtstr argument + max_rows: Maximum number of rows to show. If there's overflow, a + message will be shown to the user indicating that some rows + are not displayed + metric: Metric which is being tuned + mode: Sort the table in descenting order if mode is "max"; + ascending otherwise + sort_by_metric: If true, the table will be sorted by the metric + max_column_length: Max number of characters in each column + + Returns: + Messages to be shown to the user containing progress tables + """ + data, columns, (overflow, overflow_str) = _get_progress_table_data( + trials, + metric_columns, + parameter_columns, + max_rows, + metric, + mode, + sort_by_metric, + max_column_length, + ) + messages = [tabulate(data, headers=columns, tablefmt=fmt, showindex=False)] + if overflow: + messages.append(f"... {overflow} more trials not shown ({overflow_str})") + return messages + + +def _generate_sys_info_str(*sys_info) -> str: + """Format system info into a string. + *sys_info: System info strings to be included. + + Returns: + Formatted string containing system information. + """ + if sys_info: + return "
".join(sys_info).replace("\n", "
") + return "" + + +def _trial_errors_str( + trials: List[Trial], fmt: str = "psql", max_rows: Optional[int] = None +): + """Returns a readable message regarding trial errors. + + Args: + trials: List of trials to get progress string for. + fmt: Output format (see tablefmt in tabulate API). + max_rows: Maximum number of rows in the error table. Defaults to + unlimited. + """ + messages = [] + failed = [t for t in trials if t.error_file] + num_failed = len(failed) + if num_failed > 0: + messages.append("Number of errored trials: {}".format(num_failed)) + if num_failed > (max_rows or float("inf")): + messages.append( + "Table truncated to {} rows ({} overflow)".format( + max_rows, num_failed - max_rows + ) + ) + + fail_header = ["Trial name", "# failures", "error file"] + fail_table_data = [ + [ + str(trial), + str(trial.run_metadata.num_failures) + + ("" if trial.status == Trial.ERROR else "*"), + trial.error_file, + ] + for trial in failed[:max_rows] + ] + messages.append( + tabulate( + fail_table_data, + headers=fail_header, + tablefmt=fmt, + showindex=False, + colalign=("left", "right", "left"), + ) + ) + if any(trial.status == Trial.TERMINATED for trial in failed[:max_rows]): + messages.append("* The trial terminated successfully after retrying.") + + delim = "
" if fmt == "html" else "\n" + return delim.join(messages) + + +def _best_trial_str( + trial: Trial, + metric: str, + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, +): + """Returns a readable message stating the current best trial.""" + val = unflattened_lookup(metric, trial.last_result, default=None) + config = trial.last_result.get("config", {}) + parameter_columns = parameter_columns or list(config.keys()) + if isinstance(parameter_columns, Mapping): + parameter_columns = parameter_columns.keys() + params = {p: unflattened_lookup(p, config) for p in parameter_columns} + return ( + f"Current best trial: {trial.trial_id} with {metric}={val} and " + f"parameters={params}" + ) + + +def _fair_filter_trials( + trials_by_state: Dict[str, List[Trial]], + max_trials: int, + sort_by_metric: bool = False, +): + """Filters trials such that each state is represented fairly. + + The oldest trials are truncated if necessary. + + Args: + trials_by_state: Maximum number of trials to return. + Returns: + Dict mapping state to List of fairly represented trials. + """ + num_trials_by_state = collections.defaultdict(int) + no_change = False + # Determine number of trials to keep per state. + while max_trials > 0 and not no_change: + no_change = True + for state in sorted(trials_by_state): + if num_trials_by_state[state] < len(trials_by_state[state]): + no_change = False + max_trials -= 1 + num_trials_by_state[state] += 1 + # Sort by start time, descending if the trails is not sorted by metric. + sorted_trials_by_state = dict() + for state in sorted(trials_by_state): + if state == Trial.TERMINATED and sort_by_metric: + sorted_trials_by_state[state] = trials_by_state[state] + else: + sorted_trials_by_state[state] = sorted( + trials_by_state[state], reverse=False, key=lambda t: t.trial_id + ) + # Truncate oldest trials. + filtered_trials = { + state: sorted_trials_by_state[state][: num_trials_by_state[state]] + for state in sorted(trials_by_state) + } + return filtered_trials + + +def _get_trial_location(trial: Trial, result: dict) -> _Location: + # we get the location from the result, as the one in trial will be + # reset when trial terminates + node_ip, pid = result.get(NODE_IP, None), result.get(PID, None) + if node_ip and pid: + location = _Location(node_ip, pid) + else: + # fallback to trial location if there hasn't been a report yet + location = trial.temporary_state.location + return location + + +def _get_trial_info( + trial: Trial, parameters: List[str], metrics: List[str], max_column_length: int = 20 +): + """Returns the following information about a trial: + + name | status | loc | params... | metrics... + + Args: + trial: Trial to get information for. + parameters: Names of trial parameters to include. + metrics: Names of metrics to include. + max_column_length: Maximum column length (in characters). + """ + result = trial.last_result + config = trial.config + location = _get_trial_location(trial, result) + trial_info = [str(trial), trial.status, str(location)] + trial_info += [ + _max_len( + unflattened_lookup(param, config, default=None), + max_len=max_column_length, + add_addr=True, + ) + for param in parameters + ] + trial_info += [ + _max_len( + unflattened_lookup(metric, result, default=None), + max_len=max_column_length, + add_addr=True, + ) + for metric in metrics + ] + return trial_info + + +@DeveloperAPI +class TrialProgressCallback(Callback): + """Reports (prints) intermediate trial progress. + + This callback is automatically added to the callback stack. When a + result is obtained, this callback will print the results according to + the specified verbosity level. + + For ``Verbosity.V3_TRIAL_DETAILS``, a full result list is printed. + + For ``Verbosity.V2_TRIAL_NORM``, only one line is printed per received + result. + + All other verbosity levels do not print intermediate trial progress. + + Result printing is throttled on a per-trial basis. Per default, results are + printed only once every 30 seconds. Results are always printed when a trial + finished or errored. + + """ + + def __init__( + self, metric: Optional[str] = None, progress_metrics: Optional[List[str]] = None + ): + self._last_print = collections.defaultdict(float) + self._last_print_iteration = collections.defaultdict(int) + self._completed_trials = set() + self._last_result_str = {} + self._metric = metric + self._progress_metrics = set(progress_metrics or []) + + # Only use progress metrics if at least two metrics are in there + if self._metric and self._progress_metrics: + self._progress_metrics.add(self._metric) + self._last_result = {} + self._display_handle = None + + def _print(self, msg: str): + safe_print(msg) + + def on_trial_result( + self, + iteration: int, + trials: List["Trial"], + trial: "Trial", + result: Dict, + **info, + ): + self.log_result(trial, result, error=False) + + def on_trial_error( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + self.log_result(trial, trial.last_result, error=True) + + def on_trial_complete( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + # Only log when we never logged that a trial was completed + if trial not in self._completed_trials: + self._completed_trials.add(trial) + + print_result_str = self._print_result(trial.last_result) + last_result_str = self._last_result_str.get(trial, "") + # If this is a new result, print full result string + if print_result_str != last_result_str: + self.log_result(trial, trial.last_result, error=False) + else: + self._print(f"Trial {trial} completed. Last result: {print_result_str}") + + def log_result(self, trial: "Trial", result: Dict, error: bool = False): + done = result.get("done", False) is True + last_print = self._last_print[trial] + should_print = done or error or time.time() - last_print > DEBUG_PRINT_INTERVAL + + if done and trial not in self._completed_trials: + self._completed_trials.add(trial) + + if should_print: + if IS_NOTEBOOK: + self.display_result(trial, result, error, done) + else: + self.print_result(trial, result, error, done) + + self._last_print[trial] = time.time() + if TRAINING_ITERATION in result: + self._last_print_iteration[trial] = result[TRAINING_ITERATION] + + def print_result(self, trial: Trial, result: Dict, error: bool, done: bool): + """Print the most recent results for the given trial to stdout. + + Args: + trial: Trial for which results are to be printed + result: Result to be printed + error: True if an error has occurred, False otherwise + done: True if the trial is finished, False otherwise + """ + last_print_iteration = self._last_print_iteration[trial] + + if has_verbosity(Verbosity.V3_TRIAL_DETAILS): + if result.get(TRAINING_ITERATION) != last_print_iteration: + self._print(f"Result for {trial}:") + self._print(" {}".format(pretty_print(result).replace("\n", "\n "))) + if done: + self._print(f"Trial {trial} completed.") + + elif has_verbosity(Verbosity.V2_TRIAL_NORM): + metric_name = self._metric or "_metric" + metric_value = result.get(metric_name, -99.0) + error_file = Path(trial.local_path, EXPR_ERROR_FILE).as_posix() + + info = "" + if done: + info = " This trial completed." + + print_result_str = self._print_result(result) + + self._last_result_str[trial] = print_result_str + + if error: + message = ( + f"The trial {trial} errored with " + f"parameters={trial.config}. " + f"Error file: {error_file}" + ) + elif self._metric: + message = ( + f"Trial {trial} reported " + f"{metric_name}={metric_value:.2f} " + f"with parameters={trial.config}.{info}" + ) + else: + message = ( + f"Trial {trial} reported " + f"{print_result_str} " + f"with parameters={trial.config}.{info}" + ) + + self._print(message) + + def generate_trial_table( + self, trials: Dict[Trial, Dict], columns: List[str] + ) -> str: + """Generate an HTML table of trial progress info. + + Trials (rows) are sorted by name; progress stats (columns) are sorted + as well. + + Args: + trials: Trials and their associated latest results + columns: Columns to show in the table; must be a list of valid + keys for each Trial result + + Returns: + HTML template containing a rendered table of progress info + """ + data = [] + columns = sorted(columns) + + sorted_trials = collections.OrderedDict( + sorted(self._last_result.items(), key=lambda item: str(item[0])) + ) + for trial, result in sorted_trials.items(): + data.append([str(trial)] + [result.get(col, "") for col in columns]) + + return Template("trial_progress.html.j2").render( + table=tabulate( + data, tablefmt="html", headers=["Trial name"] + columns, showindex=False + ) + ) + + def display_result(self, trial: Trial, result: Dict, error: bool, done: bool): + """Display a formatted HTML table of trial progress results. + + Trial progress is only shown if verbosity is set to level 2 or 3. + + Args: + trial: Trial for which results are to be printed + result: Result to be printed + error: True if an error has occurred, False otherwise + done: True if the trial is finished, False otherwise + """ + from IPython.display import HTML, display + + self._last_result[trial] = result + if has_verbosity(Verbosity.V3_TRIAL_DETAILS): + ignored_keys = { + "config", + "hist_stats", + } + + elif has_verbosity(Verbosity.V2_TRIAL_NORM): + ignored_keys = { + "config", + "hist_stats", + "trial_id", + "experiment_tag", + "done", + } | set(AUTO_RESULT_KEYS) + else: + return + + table = self.generate_trial_table( + self._last_result, set(result.keys()) - ignored_keys + ) + if not self._display_handle: + self._display_handle = display(HTML(table), display_id=True) + else: + self._display_handle.update(HTML(table)) + + def _print_result(self, result: Dict): + if self._progress_metrics: + # If progress metrics are given, only report these + flat_result = flatten_dict(result) + + print_result = {} + for metric in self._progress_metrics: + print_result[metric] = flat_result.get(metric) + + else: + # Else, skip auto populated results + print_result = result.copy() + + for skip_result in SKIP_RESULTS_IN_REPORT: + print_result.pop(skip_result, None) + + for auto_result in AUTO_RESULT_KEYS: + print_result.pop(auto_result, None) + + print_result_str = ",".join( + [f"{k}={v}" for k, v in print_result.items() if v is not None] + ) + return print_result_str + + +def _detect_reporter(_trainer_api: bool = False, **kwargs) -> TuneReporterBase: + """Detect progress reporter class. + + Will return a :class:`JupyterNotebookReporter` if a IPython/Jupyter-like + session was detected, and a :class:`CLIReporter` otherwise. + + Keyword arguments are passed on to the reporter class. + """ + if IS_NOTEBOOK and not _trainer_api: + kwargs.setdefault("overwrite", not has_verbosity(Verbosity.V2_TRIAL_NORM)) + progress_reporter = JupyterNotebookReporter(**kwargs) + else: + progress_reporter = CLIReporter(**kwargs) + return progress_reporter + + +def _detect_progress_metrics( + trainable: Optional[Union["Trainable", Callable]] +) -> Optional[Collection[str]]: + """Detect progress metrics to report.""" + if not trainable: + return None + + return getattr(trainable, "_progress_metrics", None) + + +def _prepare_progress_reporter_for_ray_client( + progress_reporter: ProgressReporter, + verbosity: Union[int, Verbosity], + string_queue: Optional[Queue] = None, +) -> Tuple[ProgressReporter, Queue]: + """Prepares progress reported for Ray Client by setting the string queue. + + The string queue will be created if it's None.""" + set_verbosity(verbosity) + progress_reporter = progress_reporter or _detect_reporter() + + # JupyterNotebooks don't work with remote tune runs out of the box + # (e.g. via Ray client) as they don't have access to the main + # process stdout. So we introduce a queue here that accepts + # strings, which will then be displayed on the driver side. + if isinstance(progress_reporter, RemoteReporterMixin): + if string_queue is None: + string_queue = Queue( + actor_options={"num_cpus": 0, **_force_on_current_node(None)} + ) + progress_reporter.output_queue = string_queue + + return progress_reporter, string_queue + + +def _stream_client_output( + remote_future: ray.ObjectRef, + progress_reporter: ProgressReporter, + string_queue: Queue, +) -> Any: + """ + Stream items from string queue to progress_reporter until remote_future resolves + """ + if string_queue is None: + return + + def get_next_queue_item(): + try: + return string_queue.get(block=False) + except Empty: + return None + + def _handle_string_queue(): + string_item = get_next_queue_item() + while string_item is not None: + # This happens on the driver side + progress_reporter.display(string_item) + string_item = get_next_queue_item() + + # ray.wait(...)[1] returns futures that are not ready, yet + while ray.wait([remote_future], timeout=0.2)[1]: + # Check if we have items to execute + _handle_string_queue() + + # Handle queue one last time + _handle_string_queue() diff --git a/venv/lib/python3.10/site-packages/ray/tune/registry.py b/venv/lib/python3.10/site-packages/ray/tune/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..b713e2902151ee50dee5b2fc5358a5695a43e839 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/registry.py @@ -0,0 +1,319 @@ +import atexit +import logging +from functools import partial +from types import FunctionType +from typing import Callable, Optional, Type, Union + +import ray +import ray.cloudpickle as pickle +from ray.experimental.internal_kv import ( + _internal_kv_del, + _internal_kv_get, + _internal_kv_initialized, + _internal_kv_put, +) +from ray.tune.error import TuneError +from ray.util.annotations import DeveloperAPI + +TRAINABLE_CLASS = "trainable_class" +ENV_CREATOR = "env_creator" +RLLIB_MODEL = "rllib_model" +RLLIB_PREPROCESSOR = "rllib_preprocessor" +RLLIB_ACTION_DIST = "rllib_action_dist" +RLLIB_INPUT = "rllib_input" +RLLIB_CONNECTOR = "rllib_connector" +TEST = "__test__" +KNOWN_CATEGORIES = [ + TRAINABLE_CLASS, + ENV_CREATOR, + RLLIB_MODEL, + RLLIB_PREPROCESSOR, + RLLIB_ACTION_DIST, + RLLIB_INPUT, + RLLIB_CONNECTOR, + TEST, +] + +logger = logging.getLogger(__name__) + + +def _has_trainable(trainable_name): + return _global_registry.contains(TRAINABLE_CLASS, trainable_name) + + +@DeveloperAPI +def get_trainable_cls(trainable_name): + validate_trainable(trainable_name) + return _global_registry.get(TRAINABLE_CLASS, trainable_name) + + +@DeveloperAPI +def validate_trainable(trainable_name: str): + if not _has_trainable(trainable_name) and not _has_rllib_trainable(trainable_name): + raise TuneError(f"Unknown trainable: {trainable_name}") + + +def _has_rllib_trainable(trainable_name: str) -> bool: + try: + # Make sure everything rllib-related is registered. + from ray.rllib import _register_all + except (ImportError, ModuleNotFoundError): + return False + + _register_all() + return _has_trainable(trainable_name) + + +@DeveloperAPI +def is_function_trainable(trainable: Union[str, Callable, Type]) -> bool: + """Check if a given trainable is a function trainable. + Either the trainable has been wrapped as a FunctionTrainable class already, + or it's still a FunctionType/partial/callable.""" + from ray.tune.trainable import FunctionTrainable + + if isinstance(trainable, str): + trainable = get_trainable_cls(trainable) + + is_wrapped_func = isinstance(trainable, type) and issubclass( + trainable, FunctionTrainable + ) + return is_wrapped_func or ( + not isinstance(trainable, type) + and ( + isinstance(trainable, FunctionType) + or isinstance(trainable, partial) + or callable(trainable) + ) + ) + + +@DeveloperAPI +def register_trainable(name: str, trainable: Union[Callable, Type], warn: bool = True): + """Register a trainable function or class. + + This enables a class or function to be accessed on every Ray process + in the cluster. + + Args: + name: Name to register. + trainable: Function or tune.Trainable class. Functions must + take (config, status_reporter) as arguments and will be + automatically converted into a class during registration. + """ + + from ray.tune.trainable import Trainable, wrap_function + + if isinstance(trainable, type): + logger.debug("Detected class for trainable.") + elif isinstance(trainable, FunctionType) or isinstance(trainable, partial): + logger.debug("Detected function for trainable.") + trainable = wrap_function(trainable) + elif callable(trainable): + logger.info("Detected unknown callable for trainable. Converting to class.") + trainable = wrap_function(trainable) + + if not issubclass(trainable, Trainable): + raise TypeError("Second argument must be convertable to Trainable", trainable) + _global_registry.register(TRAINABLE_CLASS, name, trainable) + + +def _unregister_trainables(): + _global_registry.unregister_all(TRAINABLE_CLASS) + + +@DeveloperAPI +def register_env(name: str, env_creator: Callable): + """Register a custom environment for use with RLlib. + + This enables the environment to be accessed on every Ray process + in the cluster. + + Args: + name: Name to register. + env_creator: Callable that creates an env. + """ + + if not callable(env_creator): + raise TypeError("Second argument must be callable.", env_creator) + _global_registry.register(ENV_CREATOR, name, env_creator) + + +def _unregister_envs(): + _global_registry.unregister_all(ENV_CREATOR) + + +@DeveloperAPI +def register_input(name: str, input_creator: Callable): + """Register a custom input api for RLlib. + + Args: + name: Name to register. + input_creator: Callable that creates an + input reader. + """ + if not callable(input_creator): + raise TypeError("Second argument must be callable.", input_creator) + _global_registry.register(RLLIB_INPUT, name, input_creator) + + +def _unregister_inputs(): + _global_registry.unregister_all(RLLIB_INPUT) + + +@DeveloperAPI +def registry_contains_input(name: str) -> bool: + return _global_registry.contains(RLLIB_INPUT, name) + + +@DeveloperAPI +def registry_get_input(name: str) -> Callable: + return _global_registry.get(RLLIB_INPUT, name) + + +def _unregister_all(): + _unregister_inputs() + _unregister_envs() + _unregister_trainables() + + +def _check_serializability(key, value): + _global_registry.register(TEST, key, value) + + +def _make_key(prefix: str, category: str, key: str): + """Generate a binary key for the given category and key. + + Args: + prefix: Prefix + category: The category of the item + key: The unique identifier for the item + + Returns: + The key to use for storing a the value. + """ + return ( + b"TuneRegistry:" + + prefix.encode("ascii") + + b":" + + category.encode("ascii") + + b"/" + + key.encode("ascii") + ) + + +class _Registry: + def __init__(self, prefix: Optional[str] = None): + """If no prefix is given, use runtime context job ID.""" + self._to_flush = {} + self._prefix = prefix + self._registered = set() + self._atexit_handler_registered = False + + @property + def prefix(self): + if not self._prefix: + self._prefix = ray.get_runtime_context().get_job_id() + return self._prefix + + def _register_atexit(self): + if self._atexit_handler_registered: + # Already registered + return + + if ray._private.worker.global_worker.mode != ray.SCRIPT_MODE: + # Only cleanup on the driver + return + + atexit.register(_unregister_all) + self._atexit_handler_registered = True + + def register(self, category, key, value): + """Registers the value with the global registry. + + Args: + category: The category to register under. + key: The key to register under. + value: The value to register. + + Raises: + PicklingError: If unable to pickle to provided file. + """ + if category not in KNOWN_CATEGORIES: + from ray.tune import TuneError + + raise TuneError( + "Unknown category {} not among {}".format(category, KNOWN_CATEGORIES) + ) + self._to_flush[(category, key)] = pickle.dumps_debug(value) + if _internal_kv_initialized(): + self.flush_values() + + def unregister(self, category, key): + if _internal_kv_initialized(): + _internal_kv_del(_make_key(self.prefix, category, key)) + else: + self._to_flush.pop((category, key), None) + + def unregister_all(self, category: Optional[str] = None): + remaining = set() + for cat, key in self._registered: + if category and category == cat: + self.unregister(cat, key) + else: + remaining.add((cat, key)) + self._registered = remaining + + def contains(self, category, key): + if _internal_kv_initialized(): + value = _internal_kv_get(_make_key(self.prefix, category, key)) + return value is not None + else: + return (category, key) in self._to_flush + + def get(self, category, key): + if _internal_kv_initialized(): + value = _internal_kv_get(_make_key(self.prefix, category, key)) + if value is None: + raise ValueError( + "Registry value for {}/{} doesn't exist.".format(category, key) + ) + return pickle.loads(value) + else: + return pickle.loads(self._to_flush[(category, key)]) + + def flush_values(self): + self._register_atexit() + for (category, key), value in self._to_flush.items(): + _internal_kv_put( + _make_key(self.prefix, category, key), value, overwrite=True + ) + self._registered.add((category, key)) + self._to_flush.clear() + + +_global_registry = _Registry() +ray._private.worker._post_init_hooks.append(_global_registry.flush_values) + + +class _ParameterRegistry: + def __init__(self): + self.to_flush = {} + self.references = {} + + def put(self, k, v): + self.to_flush[k] = v + if ray.is_initialized(): + self.flush() + + def get(self, k): + if not ray.is_initialized(): + return self.to_flush[k] + return ray.get(self.references[k]) + + def flush(self): + for k, v in self.to_flush.items(): + if isinstance(v, ray.ObjectRef): + self.references[k] = v + else: + self.references[k] = ray.put(v) + self.to_flush.clear() diff --git a/venv/lib/python3.10/site-packages/ray/tune/resources.py b/venv/lib/python3.10/site-packages/ray/tune/resources.py new file mode 100644 index 0000000000000000000000000000000000000000..6c6113ceac03b8d554c8cdca962ddf23ec487c10 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/resources.py @@ -0,0 +1,92 @@ +import json +import logging +from collections import namedtuple + +# For compatibility under py2 to consider unicode as str +from typing import Optional + +from ray.tune.error import TuneError +from ray.tune.execution.placement_groups import ( + PlacementGroupFactory, + resource_dict_to_pg_factory, +) +from ray.tune.utils.resource_updater import _Resources +from ray.util.annotations import Deprecated, DeveloperAPI + +logger = logging.getLogger(__name__) + + +@Deprecated +class Resources( + namedtuple( + "Resources", + [ + "cpu", + "gpu", + "memory", + "object_store_memory", + "extra_cpu", + "extra_gpu", + "extra_memory", + "extra_object_store_memory", + "custom_resources", + "extra_custom_resources", + "has_placement_group", + ], + ) +): + __slots__ = () + + def __new__( + cls, + cpu: float, + gpu: float, + memory: float = 0, + object_store_memory: float = 0.0, + extra_cpu: float = 0.0, + extra_gpu: float = 0.0, + extra_memory: float = 0.0, + extra_object_store_memory: float = 0.0, + custom_resources: Optional[dict] = None, + extra_custom_resources: Optional[dict] = None, + has_placement_group: bool = False, + ): + raise DeprecationWarning( + "tune.Resources is depracted. Use tune.PlacementGroupFactory instead." + ) + + +@DeveloperAPI +def json_to_resources(data: Optional[str]) -> Optional[PlacementGroupFactory]: + if data is None or data == "null": + return None + if isinstance(data, str): + data = json.loads(data) + + for k in data: + if k in ["driver_cpu_limit", "driver_gpu_limit"]: + raise TuneError( + "The field `{}` is no longer supported. Use `extra_cpu` " + "or `extra_gpu` instead.".format(k) + ) + if k not in _Resources._fields: + raise ValueError( + "Unknown resource field {}, must be one of {}".format( + k, Resources._fields + ) + ) + resource_dict_to_pg_factory( + dict( + cpu=data.get("cpu", 1), + gpu=data.get("gpu", 0), + memory=data.get("memory", 0), + custom_resources=data.get("custom_resources"), + ) + ) + + +@Deprecated +def resources_to_json(*args, **kwargs): + raise DeprecationWarning( + "tune.Resources is depracted. Use tune.PlacementGroupFactory instead." + ) diff --git a/venv/lib/python3.10/site-packages/ray/tune/result.py b/venv/lib/python3.10/site-packages/ray/tune/result.py new file mode 100644 index 0000000000000000000000000000000000000000..b4e966386a12743df99f3bb9aa243a07ce8b1409 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/result.py @@ -0,0 +1,133 @@ +# Importing for Backward Compatibility +from ray.air.constants import ( # noqa: F401 + EXPR_ERROR_FILE, + EXPR_ERROR_PICKLE_FILE, + EXPR_PARAM_FILE, + EXPR_PARAM_PICKLE_FILE, + EXPR_PROGRESS_FILE, + EXPR_RESULT_FILE, + TIME_THIS_ITER_S, + TIMESTAMP, + TRAINING_ITERATION, +) + +# fmt: off +# __sphinx_doc_begin__ +# (Optional/Auto-filled) training is terminated. Filled only if not provided. +DONE = "done" + +# (Optional) Enum for user controlled checkpoint +SHOULD_CHECKPOINT = "should_checkpoint" + +# (Auto-filled) The hostname of the machine hosting the training process. +HOSTNAME = "hostname" + +# (Auto-filled) The auto-assigned id of the trial. +TRIAL_ID = "trial_id" + +# (Auto-filled) The auto-assigned id of the trial. +EXPERIMENT_TAG = "experiment_tag" + +# (Auto-filled) The node ip of the machine hosting the training process. +NODE_IP = "node_ip" + +# (Auto-filled) The pid of the training process. +PID = "pid" + +# (Optional) Default (anonymous) metric when using tune.report(x) +DEFAULT_METRIC = "_metric" + +# (Optional) Mean reward for current training iteration +EPISODE_REWARD_MEAN = "episode_reward_mean" + +# (Optional) Mean loss for training iteration +MEAN_LOSS = "mean_loss" + +# (Optional) Mean accuracy for training iteration +MEAN_ACCURACY = "mean_accuracy" + +# Number of episodes in this iteration. +EPISODES_THIS_ITER = "episodes_this_iter" + +# (Optional/Auto-filled) Accumulated number of episodes for this trial. +EPISODES_TOTAL = "episodes_total" + +# Number of timesteps in this iteration. +TIMESTEPS_THIS_ITER = "timesteps_this_iter" + +# (Auto-filled) Accumulated number of timesteps for this entire trial. +TIMESTEPS_TOTAL = "timesteps_total" + +# (Auto-filled) Accumulated time in seconds for this entire trial. +TIME_TOTAL_S = "time_total_s" + +# __sphinx_doc_end__ +# fmt: on + +DEFAULT_EXPERIMENT_INFO_KEYS = ("trainable_name", EXPERIMENT_TAG, TRIAL_ID) + +DEFAULT_RESULT_KEYS = ( + TRAINING_ITERATION, + TIME_TOTAL_S, + MEAN_ACCURACY, + MEAN_LOSS, +) + +# Metrics that don't require at least one iteration to complete +DEBUG_METRICS = ( + TRIAL_ID, + "experiment_id", + "date", + TIMESTAMP, + PID, + HOSTNAME, + NODE_IP, + "config", +) + +# Make sure this doesn't regress +AUTO_RESULT_KEYS = ( + TRAINING_ITERATION, + TIME_TOTAL_S, + EPISODES_TOTAL, + TIMESTEPS_TOTAL, + NODE_IP, + HOSTNAME, + PID, + TIME_TOTAL_S, + TIME_THIS_ITER_S, + TIMESTAMP, + "date", + "time_since_restore", + "timesteps_since_restore", + "iterations_since_restore", + "config", + # TODO(justinvyu): Move this stuff to train to avoid cyclical dependency. + "checkpoint_dir_name", +) + +# __duplicate__ is a magic keyword used internally to +# avoid double-logging results when using the Function API. +RESULT_DUPLICATE = "__duplicate__" + +# __trial_info__ is a magic keyword used internally to pass trial_info +# to the Trainable via the constructor. +TRIAL_INFO = "__trial_info__" + +# __stdout_file__/__stderr_file__ are magic keywords used internally +# to pass log file locations to the Trainable via the constructor. +STDOUT_FILE = "__stdout_file__" +STDERR_FILE = "__stderr_file__" + +DEFAULT_EXPERIMENT_NAME = "default" + +# Meta file about status under each experiment directory, can be +# parsed by automlboard if exists. +JOB_META_FILE = "job_status.json" + +# Meta file about status under each trial directory, can be parsed +# by automlboard if exists. +EXPR_META_FILE = "trial_status.json" + +# Config prefix when using ExperimentAnalysis. +CONFIG_PREFIX = "config" diff --git a/venv/lib/python3.10/site-packages/ray/tune/result_grid.py b/venv/lib/python3.10/site-packages/ray/tune/result_grid.py new file mode 100644 index 0000000000000000000000000000000000000000..07e236f06833670efe1e19fd001b5e147e75581b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/result_grid.py @@ -0,0 +1,283 @@ +from typing import Optional, Union + +import pandas as pd +import pyarrow + +from ray.air.result import Result +from ray.exceptions import RayTaskError +from ray.tune.analysis import ExperimentAnalysis +from ray.tune.error import TuneError +from ray.tune.experiment import Trial +from ray.util import PublicAPI + + +@PublicAPI(stability="beta") +class ResultGrid: + """A set of ``Result`` objects for interacting with Ray Tune results. + + You can use it to inspect the trials and obtain the best result. + + The constructor is a private API. This object can only be created as a result of + ``Tuner.fit()``. + + Example: + .. testcode:: + + import random + from ray import tune + def random_error_trainable(config): + if random.random() < 0.5: + return {"loss": 0.0} + else: + raise ValueError("This is an error") + tuner = tune.Tuner( + random_error_trainable, + run_config=tune.RunConfig(name="example-experiment"), + tune_config=tune.TuneConfig(num_samples=10), + ) + try: + result_grid = tuner.fit() + except ValueError: + pass + for i in range(len(result_grid)): + result = result_grid[i] + if not result.error: + print(f"Trial finishes successfully with metrics" + f"{result.metrics}.") + else: + print(f"Trial failed with error {result.error}.") + + .. testoutput:: + :hide: + + ... + + You can also use ``result_grid`` for more advanced analysis. + + >>> # Get the best result based on a particular metric. + >>> best_result = result_grid.get_best_result( # doctest: +SKIP + ... metric="loss", mode="min") + >>> # Get the best checkpoint corresponding to the best result. + >>> best_checkpoint = best_result.checkpoint # doctest: +SKIP + >>> # Get a dataframe for the last reported results of all of the trials + >>> df = result_grid.get_dataframe() # doctest: +SKIP + >>> # Get a dataframe for the minimum loss seen for each trial + >>> df = result_grid.get_dataframe(metric="loss", mode="min") # doctest: +SKIP + + Note that trials of all statuses are included in the final result grid. + If a trial is not in terminated state, its latest result and checkpoint as + seen by Tune will be provided. + + See :doc:`/tune/examples/tune_analyze_results` for more usage examples. + """ + + def __init__( + self, + experiment_analysis: ExperimentAnalysis, + ): + self._experiment_analysis = experiment_analysis + self._results = [ + self._trial_to_result(trial) for trial in self._experiment_analysis.trials + ] + + @property + def experiment_path(self) -> str: + """Path pointing to the experiment directory on persistent storage. + + This can point to a remote storage location (e.g. S3) or to a local + location (path on the head node).""" + return self._experiment_analysis.experiment_path + + @property + def filesystem(self) -> pyarrow.fs.FileSystem: + """Return the filesystem that can be used to access the experiment path. + + Returns: + pyarrow.fs.FileSystem implementation. + """ + return self._experiment_analysis._fs + + def get_best_result( + self, + metric: Optional[str] = None, + mode: Optional[str] = None, + scope: str = "last", + filter_nan_and_inf: bool = True, + ) -> Result: + """Get the best result from all the trials run. + + Args: + metric: Key for trial info to order on. Defaults to + the metric specified in your Tuner's ``TuneConfig``. + mode: One of [min, max]. Defaults to the mode specified + in your Tuner's ``TuneConfig``. + scope: One of [all, last, avg, last-5-avg, last-10-avg]. + If `scope=last`, only look at each trial's final step for + `metric`, and compare across trials based on `mode=[min,max]`. + If `scope=avg`, consider the simple average over all steps + for `metric` and compare across trials based on + `mode=[min,max]`. If `scope=last-5-avg` or `scope=last-10-avg`, + consider the simple average over the last 5 or 10 steps for + `metric` and compare across trials based on `mode=[min,max]`. + If `scope=all`, find each trial's min/max score for `metric` + based on `mode`, and compare trials based on `mode=[min,max]`. + filter_nan_and_inf: If True (default), NaN or infinite + values are disregarded and these trials are never selected as + the best trial. + """ + if len(self._experiment_analysis.trials) == 1: + return self._trial_to_result(self._experiment_analysis.trials[0]) + if not metric and not self._experiment_analysis.default_metric: + raise ValueError( + "No metric is provided. Either pass in a `metric` arg to " + "`get_best_result` or specify a metric in the " + "`TuneConfig` of your `Tuner`." + ) + if not mode and not self._experiment_analysis.default_mode: + raise ValueError( + "No mode is provided. Either pass in a `mode` arg to " + "`get_best_result` or specify a mode in the " + "`TuneConfig` of your `Tuner`." + ) + + best_trial = self._experiment_analysis.get_best_trial( + metric=metric, + mode=mode, + scope=scope, + filter_nan_and_inf=filter_nan_and_inf, + ) + if not best_trial: + error_msg = ( + "No best trial found for the given metric: " + f"{metric or self._experiment_analysis.default_metric}. " + "This means that no trial has reported this metric" + ) + error_msg += ( + ", or all values reported for this metric are NaN. To not ignore NaN " + "values, you can set the `filter_nan_and_inf` arg to False." + if filter_nan_and_inf + else "." + ) + raise RuntimeError(error_msg) + + return self._trial_to_result(best_trial) + + def get_dataframe( + self, + filter_metric: Optional[str] = None, + filter_mode: Optional[str] = None, + ) -> pd.DataFrame: + """Return dataframe of all trials with their configs and reported results. + + Per default, this returns the last reported results for each trial. + + If ``filter_metric`` and ``filter_mode`` are set, the results from each + trial are filtered for this metric and mode. For example, if + ``filter_metric="some_metric"`` and ``filter_mode="max"``, for each trial, + every received result is checked, and the one where ``some_metric`` is + maximal is returned. + + + Example: + + .. testcode:: + + import ray.tune + + def training_loop_per_worker(config): + ray.tune.report({"accuracy": 0.8}) + + result_grid = ray.tune.Tuner( + trainable=training_loop_per_worker, + run_config=ray.tune.RunConfig(name="my_tune_run") + ).fit() + + # Get last reported results per trial + df = result_grid.get_dataframe() + + # Get best ever reported accuracy per trial + df = result_grid.get_dataframe( + filter_metric="accuracy", filter_mode="max" + ) + + .. testoutput:: + :hide: + + ... + + Args: + filter_metric: Metric to filter best result for. + filter_mode: If ``filter_metric`` is given, one of ``["min", "max"]`` + to specify if we should find the minimum or maximum result. + + Returns: + Pandas DataFrame with each trial as a row and their results as columns. + """ + return self._experiment_analysis.dataframe( + metric=filter_metric, mode=filter_mode + ) + + def __len__(self) -> int: + return len(self._results) + + def __getitem__(self, i: int) -> Result: + """Returns the i'th result in the grid.""" + return self._results[i] + + @property + def errors(self): + """Returns the exceptions of errored trials.""" + return [result.error for result in self if result.error] + + @property + def num_errors(self): + """Returns the number of errored trials.""" + return len( + [t for t in self._experiment_analysis.trials if t.status == Trial.ERROR] + ) + + @property + def num_terminated(self): + """Returns the number of terminated (but not errored) trials.""" + return len( + [ + t + for t in self._experiment_analysis.trials + if t.status == Trial.TERMINATED + ] + ) + + @staticmethod + def _populate_exception(trial: Trial) -> Optional[Union[TuneError, RayTaskError]]: + if trial.status == Trial.TERMINATED: + return None + return trial.get_pickled_error() or trial.get_error() + + def _trial_to_result(self, trial: Trial) -> Result: + cpm = trial.run_metadata.checkpoint_manager + checkpoint = None + if cpm.latest_checkpoint_result: + checkpoint = cpm.latest_checkpoint_result.checkpoint + best_checkpoint_results = cpm.best_checkpoint_results + best_checkpoints = [ + (checkpoint_result.checkpoint, checkpoint_result.metrics) + for checkpoint_result in best_checkpoint_results + ] + + metrics_df = self._experiment_analysis.trial_dataframes.get(trial.trial_id) + + result = Result( + checkpoint=checkpoint, + metrics=trial.last_result.copy(), + error=self._populate_exception(trial), + path=trial.path, + _storage_filesystem=self._experiment_analysis._fs, + metrics_dataframe=metrics_df, + best_checkpoints=best_checkpoints, + ) + return result + + def __repr__(self) -> str: + all_results_repr = [result._repr(indent=2) for result in self] + all_results_repr = ",\n".join(all_results_repr) + return f"ResultGrid<[\n{all_results_repr}\n]>" diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d302d1319a145dba25d0547ea8486f49a167e417 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__init__.py @@ -0,0 +1,96 @@ +import inspect + +from ray._common.utils import get_function_args +from ray.tune.schedulers.async_hyperband import ASHAScheduler, AsyncHyperBandScheduler +from ray.tune.schedulers.hb_bohb import HyperBandForBOHB +from ray.tune.schedulers.hyperband import HyperBandScheduler +from ray.tune.schedulers.median_stopping_rule import MedianStoppingRule +from ray.tune.schedulers.pbt import ( + PopulationBasedTraining, + PopulationBasedTrainingReplay, +) +from ray.tune.schedulers.resource_changing_scheduler import ResourceChangingScheduler +from ray.tune.schedulers.trial_scheduler import FIFOScheduler, TrialScheduler +from ray.util import PublicAPI + + +def _pb2_importer(): + # PB2 introduces a GPy dependency which can be expensive, so we import + # lazily. + from ray.tune.schedulers.pb2 import PB2 + + return PB2 + + +# Values in this dictionary will be one two kinds: +# class of the scheduler object to create +# wrapper function to support a lazy import of the scheduler class +SCHEDULER_IMPORT = { + "fifo": FIFOScheduler, + "async_hyperband": AsyncHyperBandScheduler, + "asynchyperband": AsyncHyperBandScheduler, + "median_stopping_rule": MedianStoppingRule, + "medianstopping": MedianStoppingRule, + "hyperband": HyperBandScheduler, + "hb_bohb": HyperBandForBOHB, + "pbt": PopulationBasedTraining, + "pbt_replay": PopulationBasedTrainingReplay, + "pb2": _pb2_importer, + "resource_changing": ResourceChangingScheduler, +} + + +@PublicAPI(stability="beta") +def create_scheduler( + scheduler, + **kwargs, +): + """Instantiate a scheduler based on the given string. + + This is useful for swapping between different schedulers. + + Args: + scheduler: The scheduler to use. + **kwargs: Scheduler parameters. + These keyword arguments will be passed to the initialization + function of the chosen scheduler. + Returns: + ray.tune.schedulers.trial_scheduler.TrialScheduler: The scheduler. + Example: + >>> from ray import tune + >>> pbt_kwargs = {} + >>> scheduler = tune.create_scheduler('pbt', **pbt_kwargs) # doctest: +SKIP + """ + + scheduler = scheduler.lower() + if scheduler not in SCHEDULER_IMPORT: + raise ValueError( + f"The `scheduler` argument must be one of " + f"{list(SCHEDULER_IMPORT)}. " + f"Got: {scheduler}" + ) + + SchedulerClass = SCHEDULER_IMPORT[scheduler] + + if inspect.isfunction(SchedulerClass): + # invoke the wrapper function to retrieve class + SchedulerClass = SchedulerClass() + + scheduler_args = get_function_args(SchedulerClass) + trimmed_kwargs = {k: v for k, v in kwargs.items() if k in scheduler_args} + + return SchedulerClass(**trimmed_kwargs) + + +__all__ = [ + "TrialScheduler", + "HyperBandScheduler", + "AsyncHyperBandScheduler", + "ASHAScheduler", + "MedianStoppingRule", + "FIFOScheduler", + "PopulationBasedTraining", + "PopulationBasedTrainingReplay", + "HyperBandForBOHB", + "ResourceChangingScheduler", +] diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6728d182b5904b069346586c08c64c399d094f3b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/async_hyperband.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/async_hyperband.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e239ee73fa82167e12068c46be11f7f54034cafa Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/async_hyperband.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/hb_bohb.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/hb_bohb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1a30466fa205960d6ce67cf586cfd52e3086cab Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/hb_bohb.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/hyperband.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/hyperband.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..239676225af3d22f636e1aaff845b46114c43c5f Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/hyperband.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/median_stopping_rule.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/median_stopping_rule.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e6c7e34652bdf7f976d298018b048e791ccde92 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/median_stopping_rule.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/pb2.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/pb2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee277c98eb69ba39421dfdaea5a79fc89a8d4847 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/pb2.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/pb2_utils.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/pb2_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65084e4dcc60abf3e115d0e598d262da2af1a1d2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/pb2_utils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/pbt.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/pbt.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f07e8724b720dc6461324b4dec2f485ebc586f0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/pbt.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/resource_changing_scheduler.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/resource_changing_scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b20618318b0217d69b95a13592baf6e5f2d1a51 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/resource_changing_scheduler.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/trial_scheduler.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/trial_scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab1397b9f944ff9621dcb4fe8e400921f5113d04 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/trial_scheduler.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/util.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f655faacc5a8fb6f685a76a5c33e08cb5f8a1892 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/schedulers/__pycache__/util.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/async_hyperband.py b/venv/lib/python3.10/site-packages/ray/tune/schedulers/async_hyperband.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf8204592ba647ca723de54d14fe81e8b95e40f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/schedulers/async_hyperband.py @@ -0,0 +1,273 @@ +import logging +import pickle +from typing import TYPE_CHECKING, Dict, Optional, Union + +import numpy as np + +from ray.tune.experiment import Trial +from ray.tune.result import DEFAULT_METRIC +from ray.tune.schedulers.trial_scheduler import FIFOScheduler, TrialScheduler +from ray.util import PublicAPI + +if TYPE_CHECKING: + from ray.tune.execution.tune_controller import TuneController + +logger = logging.getLogger(__name__) + + +@PublicAPI +class AsyncHyperBandScheduler(FIFOScheduler): + """Implements the Async Successive Halving. + + This should provide similar theoretical performance as HyperBand but + avoid straggler issues that HyperBand faces. One implementation detail + is when using multiple brackets, trial allocation to bracket is done + randomly with over a softmax probability. + + See https://arxiv.org/abs/1810.05934 + + Args: + time_attr: A training result attr to use for comparing time. + Note that you can pass in something non-temporal such as + `training_iteration` as a measure of progress, the only requirement + is that the attribute should increase monotonically. + metric: The training result objective value attribute. Stopping + procedures will use this attribute. If None but a mode was passed, + the `ray.tune.result.DEFAULT_METRIC` will be used per default. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. + max_t: max time units per trial. Trials will be stopped after + max_t time units (determined by time_attr) have passed. + grace_period: Only stop trials at least this old in time. + The units are the same as the attribute named by `time_attr`. + reduction_factor: Used to set halving rate and amount. This + is simply a unit-less scalar. + brackets: Number of brackets. Each bracket has a different + halving rate, specified by the reduction factor. + stop_last_trials: Whether to terminate the trials after + reaching max_t. Defaults to True. + """ + + def __init__( + self, + time_attr: str = "training_iteration", + metric: Optional[str] = None, + mode: Optional[str] = None, + max_t: int = 100, + grace_period: int = 1, + reduction_factor: float = 4, + brackets: int = 1, + stop_last_trials: bool = True, + ): + assert max_t > 0, "Max (time_attr) not valid!" + assert max_t >= grace_period, "grace_period must be <= max_t!" + assert grace_period > 0, "grace_period must be positive!" + assert reduction_factor > 1, "Reduction Factor not valid!" + assert brackets > 0, "brackets must be positive!" + if mode: + assert mode in ["min", "max"], "`mode` must be 'min' or 'max'!" + + super().__init__() + self._reduction_factor = reduction_factor + self._max_t = max_t + + self._trial_info = {} # Stores Trial -> Bracket + + # Tracks state for new trial add + self._brackets = [ + _Bracket( + grace_period, + max_t, + reduction_factor, + s, + stop_last_trials=stop_last_trials, + ) + for s in range(brackets) + ] + self._counter = 0 # for + self._num_stopped = 0 + self._metric = metric + self._mode = mode + self._metric_op = None + if self._mode == "max": + self._metric_op = 1.0 + elif self._mode == "min": + self._metric_op = -1.0 + self._time_attr = time_attr + self._stop_last_trials = stop_last_trials + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], **spec + ) -> bool: + if self._metric and metric: + return False + if self._mode and mode: + return False + + if metric: + self._metric = metric + if mode: + self._mode = mode + + if self._mode == "max": + self._metric_op = 1.0 + elif self._mode == "min": + self._metric_op = -1.0 + + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + return True + + def on_trial_add(self, tune_controller: "TuneController", trial: Trial): + if not self._metric or not self._metric_op: + raise ValueError( + "{} has been instantiated without a valid `metric` ({}) or " + "`mode` ({}) parameter. Either pass these parameters when " + "instantiating the scheduler, or pass them as parameters " + "to `tune.TuneConfig()`".format( + self.__class__.__name__, self._metric, self._mode + ) + ) + + sizes = np.array([len(b._rungs) for b in self._brackets]) + probs = np.e ** (sizes - sizes.max()) + normalized = probs / probs.sum() + idx = np.random.choice(len(self._brackets), p=normalized) + self._trial_info[trial.trial_id] = self._brackets[idx] + + def on_trial_result( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ) -> str: + action = TrialScheduler.CONTINUE + if self._time_attr not in result or self._metric not in result: + return action + if result[self._time_attr] >= self._max_t and self._stop_last_trials: + action = TrialScheduler.STOP + else: + bracket = self._trial_info[trial.trial_id] + action = bracket.on_result( + trial, result[self._time_attr], self._metric_op * result[self._metric] + ) + if action == TrialScheduler.STOP: + self._num_stopped += 1 + return action + + def on_trial_complete( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ): + if self._time_attr not in result or self._metric not in result: + return + bracket = self._trial_info[trial.trial_id] + bracket.on_result( + trial, result[self._time_attr], self._metric_op * result[self._metric] + ) + del self._trial_info[trial.trial_id] + + def on_trial_remove(self, tune_controller: "TuneController", trial: Trial): + del self._trial_info[trial.trial_id] + + def debug_string(self) -> str: + out = "Using AsyncHyperBand: num_stopped={}".format(self._num_stopped) + out += "\n" + "\n".join([b.debug_str() for b in self._brackets]) + return out + + def save(self, checkpoint_path: str): + save_object = self.__dict__ + with open(checkpoint_path, "wb") as outputFile: + pickle.dump(save_object, outputFile) + + def restore(self, checkpoint_path: str): + with open(checkpoint_path, "rb") as inputFile: + save_object = pickle.load(inputFile) + self.__dict__.update(save_object) + + +class _Bracket: + """Bookkeeping system to track the cutoffs. + + Rungs are created in reversed order so that we can more easily find + the correct rung corresponding to the current iteration of the result. + + Example: + >>> trial1, trial2, trial3 = ... # doctest: +SKIP + >>> b = _Bracket(1, 10, 2, 0) # doctest: +SKIP + >>> # CONTINUE + >>> b.on_result(trial1, 1, 2) # doctest: +SKIP + >>> # CONTINUE + >>> b.on_result(trial2, 1, 4) # doctest: +SKIP + >>> # rungs are reversed + >>> b.cutoff(b._rungs[-1][1]) == 3.0 # doctest: +SKIP + # STOP + >>> b.on_result(trial3, 1, 1) # doctest: +SKIP + >>> b.cutoff(b._rungs[3][1]) == 2.0 # doctest: +SKIP + """ + + def __init__( + self, + min_t: int, + max_t: int, + reduction_factor: float, + s: int, + stop_last_trials: bool = True, + ): + self.rf = reduction_factor + MAX_RUNGS = int(np.log(max_t / min_t) / np.log(self.rf) - s + 1) + self._rungs = [ + (min_t * self.rf ** (k + s), {}) for k in reversed(range(MAX_RUNGS)) + ] + self._stop_last_trials = stop_last_trials + + def cutoff(self, recorded) -> Optional[Union[int, float, complex, np.ndarray]]: + if not recorded: + return None + return np.nanpercentile(list(recorded.values()), (1 - 1 / self.rf) * 100) + + def on_result(self, trial: Trial, cur_iter: int, cur_rew: Optional[float]) -> str: + action = TrialScheduler.CONTINUE + for milestone, recorded in self._rungs: + if ( + cur_iter >= milestone + and trial.trial_id in recorded + and not self._stop_last_trials + ): + # If our result has been recorded for this trial already, the + # decision to continue training has already been made. Thus we can + # skip new cutoff calculation and just continue training. + # We can also break as milestones are descending. + break + if cur_iter < milestone or trial.trial_id in recorded: + continue + else: + cutoff = self.cutoff(recorded) + if cutoff is not None and cur_rew < cutoff: + action = TrialScheduler.STOP + if cur_rew is None: + logger.warning( + "Reward attribute is None! Consider" + " reporting using a different field." + ) + else: + recorded[trial.trial_id] = cur_rew + break + return action + + def debug_str(self) -> str: + # TODO: fix up the output for this + iters = " | ".join( + [ + "Iter {:.3f}: {}".format(milestone, self.cutoff(recorded)) + for milestone, recorded in self._rungs + ] + ) + return "Bracket: " + iters + + +ASHAScheduler = AsyncHyperBandScheduler + +if __name__ == "__main__": + sched = AsyncHyperBandScheduler(grace_period=1, max_t=10, reduction_factor=2) + print(sched.debug_string()) + bracket = sched._brackets[0] + print(bracket.cutoff({str(i): i for i in range(20)})) diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/hb_bohb.py b/venv/lib/python3.10/site-packages/ray/tune/schedulers/hb_bohb.py new file mode 100644 index 0000000000000000000000000000000000000000..6c454d9efd35a52398fc183ab87ef007b1a59f21 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/schedulers/hb_bohb.py @@ -0,0 +1,176 @@ +import logging +from typing import TYPE_CHECKING, Dict, Optional + +from ray.tune.experiment import Trial +from ray.tune.schedulers.hyperband import HyperBandScheduler +from ray.tune.schedulers.trial_scheduler import TrialScheduler +from ray.util import PublicAPI + +if TYPE_CHECKING: + from ray.tune.execution.tune_controller import TuneController + +logger = logging.getLogger(__name__) + + +@PublicAPI +class HyperBandForBOHB(HyperBandScheduler): + """Extends HyperBand early stopping algorithm for BOHB. + + This implementation removes the ``HyperBandScheduler`` pipelining. This + class introduces key changes: + + 1. Trials are now placed so that the bracket with the largest size is + filled first. + + 2. Trials will be paused even if the bracket is not filled. This allows + BOHB to insert new trials into the training. + + See ray.tune.schedulers.HyperBandScheduler for parameter docstring. + """ + + def on_trial_add(self, tune_controller: "TuneController", trial: Trial): + """Adds new trial. + + On a new trial add, if current bracket is not filled, add to current + bracket. Else, if current band is not filled, create new bracket, add + to current bracket. Else, create new iteration, create new bracket, + add to bracket. + """ + if not self._metric or not self._metric_op: + raise ValueError( + "{} has been instantiated without a valid `metric` ({}) or " + "`mode` ({}) parameter. Either pass these parameters when " + "instantiating the scheduler, or pass them as parameters " + "to `tune.TuneConfig()`".format( + self.__class__.__name__, self._metric, self._mode + ) + ) + + cur_bracket = self._state["bracket"] + cur_band = self._hyperbands[self._state["band_idx"]] + if cur_bracket is None or cur_bracket.filled(): + retry = True + while retry: + # if current iteration is filled, create new iteration + if self._cur_band_filled(): + cur_band = [] + self._hyperbands.append(cur_band) + self._state["band_idx"] += 1 + + # MAIN CHANGE HERE - largest bracket first! + # cur_band will always be less than s_max_1 or else filled + s = self._s_max_1 - len(cur_band) - 1 + assert s >= 0, "Current band is filled!" + if self._get_r0(s) == 0: + logger.debug("BOHB: Bracket too small - Retrying...") + cur_bracket = None + else: + retry = False + cur_bracket = self._create_bracket(s) + cur_band.append(cur_bracket) + self._state["bracket"] = cur_bracket + + self._state["bracket"].add_trial(trial) + self._trial_info[trial] = cur_bracket, self._state["band_idx"] + + def on_trial_result( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ) -> str: + """If bracket is finished, all trials will be stopped. + + If a given trial finishes and bracket iteration is not done, + the trial will be paused and resources will be given up. + + This scheduler will not start trials but will stop trials. + The current running trial will not be handled, + as the trialrunner will be given control to handle it.""" + + result["hyperband_info"] = {} + bracket, _ = self._trial_info[trial] + bracket.update_trial_stats(trial, result) + + if bracket.continue_trial(trial): + return TrialScheduler.CONTINUE + + result["hyperband_info"]["budget"] = bracket._cumul_r + + # MAIN CHANGE HERE! + statuses = [(t, t.status) for t in bracket._live_trials] + if not bracket.filled() or any( + status != Trial.PAUSED for t, status in statuses if t is not trial + ): + # BOHB Specific. This hack existed in old Ray versions + # and was removed, but it needs to be brought back + # as otherwise the BOHB doesn't behave as intended. + # The default concurrency limiter works by discarding + # new suggestions if there are more running trials + # than the limit. That doesn't take into account paused + # trials. With BOHB, this leads to N trials finishing + # completely and then another N trials starting, + # instead of trials being paused and resumed in brackets + # as intended. + # There should be a better API for this. + # TODO(team-ml): Refactor alongside HyperBandForBOHB + tune_controller.search_alg.searcher.on_pause(trial.trial_id) + return TrialScheduler.PAUSE + + logger.debug(f"Processing bracket after trial {trial} result") + action = self._process_bracket(tune_controller, bracket) + if action == TrialScheduler.PAUSE: + tune_controller.search_alg.searcher.on_pause(trial.trial_id) + return action + + def _unpause_trial(self, tune_controller: "TuneController", trial: Trial): + # Hack. See comment in on_trial_result + tune_controller.search_alg.searcher.on_unpause(trial.trial_id) + + def choose_trial_to_run( + self, tune_controller: "TuneController", allow_recurse: bool = True + ) -> Optional[Trial]: + """Fair scheduling within iteration by completion percentage. + + List of trials not used since all trials are tracked as state + of scheduler. If iteration is occupied (ie, no trials to run), + then look into next iteration. + """ + + for hyperband in self._hyperbands: + # band will have None entries if no resources + # are to be allocated to that bracket. + scrubbed = [b for b in hyperband if b is not None] + for bracket in scrubbed: + for trial in bracket.current_trials(): + if ( + trial.status == Trial.PAUSED + and trial in bracket.trials_to_unpause + ) or trial.status == Trial.PENDING: + return trial + # MAIN CHANGE HERE! + if not any(t.status == Trial.RUNNING for t in tune_controller.get_trials()): + for hyperband in self._hyperbands: + for bracket in hyperband: + if bracket and any( + trial.status == Trial.PAUSED + for trial in bracket.current_trials() + ): + # This will change the trial state + logger.debug("Processing bracket since no trial is running.") + self._process_bracket(tune_controller, bracket) + + # If there are pending trials now, suggest one. + # This is because there might be both PENDING and + # PAUSED trials now, and PAUSED trials will raise + # an error before the trial runner tries again. + if allow_recurse and any( + ( + trial.status == Trial.PAUSED + and trial in bracket.trials_to_unpause + ) + or trial.status == Trial.PENDING + for trial in bracket.current_trials() + ): + return self.choose_trial_to_run( + tune_controller, allow_recurse=False + ) + # MAIN CHANGE HERE! + return None diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/hyperband.py b/venv/lib/python3.10/site-packages/ray/tune/schedulers/hyperband.py new file mode 100644 index 0000000000000000000000000000000000000000..57503d97ee34a1ede4b37ba4534860f9d06b27d7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/schedulers/hyperband.py @@ -0,0 +1,606 @@ +import collections +import logging +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple + +import numpy as np + +from ray.tune.error import TuneError +from ray.tune.experiment import Trial +from ray.tune.result import DEFAULT_METRIC +from ray.tune.schedulers.trial_scheduler import FIFOScheduler, TrialScheduler +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.tune.execution.tune_controller import TuneController + +logger = logging.getLogger(__name__) + + +# Implementation notes: +# This implementation contains 3 logical levels. +# Each HyperBand iteration is a "band". There can be multiple +# bands running at once, and there can be 1 band that is incomplete. +# +# In each band, there are at most `s` + 1 brackets. +# `s` is a value determined by given parameters, and assigned on +# a cyclic basis. +# +# In each bracket, there are at most `n(s)` trials, indicating that +# `n` is a function of `s`. These trials go through a series of +# halving procedures, dropping lowest performers. Multiple +# brackets are running at once. +# +# Trials added will be inserted into the most recent bracket +# and band and will spill over to new brackets/bands accordingly. +# +# This maintains the bracket size and max trial count per band +# to 5 and 117 respectively, which correspond to that of +# `max_attr=81, eta=3` from the blog post. Trials will fill up +# from smallest bracket to largest, with largest +# having the most rounds of successive halving. +@PublicAPI +class HyperBandScheduler(FIFOScheduler): + """Implements the HyperBand early stopping algorithm. + + HyperBandScheduler early stops trials using the HyperBand optimization + algorithm. It divides trials into brackets of varying sizes, and + periodically early stops low-performing trials within each bracket. + + To use this implementation of HyperBand with Tune, all you need + to do is specify the max length of time a trial can run `max_t`, the time + units `time_attr`, the name of the reported objective value `metric`, + and if `metric` is to be maximized or minimized (`mode`). + We automatically determine reasonable values for the other + HyperBand parameters based on the given values. + + For example, to limit trials to 10 minutes and early stop based on the + `episode_mean_reward` attr, construct: + + ``HyperBand('time_total_s', 'episode_reward_mean', max_t=600)`` + + Note that Tune's stopping criteria will be applied in conjunction with + HyperBand's early stopping mechanisms. + + See also: https://blog.ml.cmu.edu/2018/12/12/massively-parallel-hyperparameter-optimization/ + + Args: + time_attr: The training result attr to use for comparing time. + Note that you can pass in something non-temporal such as + `training_iteration` as a measure of progress, the only requirement + is that the attribute should increase monotonically. + metric: The training result objective value attribute. Stopping + procedures will use this attribute. If None but a mode was passed, + the `ray.tune.result.DEFAULT_METRIC` will be used per default. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. + max_t: max time units per trial. Trials will be stopped after + max_t time units (determined by time_attr) have passed. + The scheduler will terminate trials after this time has passed. + Note that this is different from the semantics of `max_t` as + mentioned in the original HyperBand paper. + reduction_factor: Same as `eta`. Determines how sharp + the difference is between bracket space-time allocation ratios. + stop_last_trials: Whether to terminate the trials after + reaching max_t. Defaults to True. + """ # noqa: E501 + + _supports_buffered_results = False + + def __init__( + self, + time_attr: str = "training_iteration", + metric: Optional[str] = None, + mode: Optional[str] = None, + max_t: int = 81, + reduction_factor: float = 3, + stop_last_trials: bool = True, + ): + assert max_t > 0, "Max (time_attr) not valid!" + if mode: + assert mode in ["min", "max"], "`mode` must be 'min' or 'max'!" + + super().__init__() + self._eta = reduction_factor + self._s_max_1 = int(np.round(np.log(max_t) / np.log(reduction_factor))) + 1 + self._max_t_attr = max_t + # bracket max trials + self._get_n0 = lambda s: int(np.ceil(self._s_max_1 / (s + 1) * self._eta**s)) + # bracket initial iterations + self._get_r0 = lambda s: int((max_t * self._eta ** (-s))) + self._hyperbands = [[]] # list of hyperband iterations + self._trial_info = {} # Stores Trial -> Bracket, Band Iteration + + # Tracks state for new trial add + self._state = {"bracket": None, "band_idx": 0} + self._num_stopped = 0 + self._metric = metric + self._mode = mode + self._metric_op = None + + if self._mode == "max": + self._metric_op = 1.0 + elif self._mode == "min": + self._metric_op = -1.0 + self._time_attr = time_attr + self._stop_last_trials = stop_last_trials + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], **spec + ) -> bool: + if self._metric and metric: + return False + if self._mode and mode: + return False + + if metric: + self._metric = metric + if mode: + self._mode = mode + + if self._mode == "max": + self._metric_op = 1.0 + elif self._mode == "min": + self._metric_op = -1.0 + + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + return True + + def on_trial_add(self, tune_controller: "TuneController", trial: Trial): + """Adds new trial. + + On a new trial add, if current bracket is not filled, + add to current bracket. Else, if current band is not filled, + create new bracket, add to current bracket. + Else, create new iteration, create new bracket, add to bracket.""" + if not self._metric or not self._metric_op: + raise ValueError( + "{} has been instantiated without a valid `metric` ({}) or " + "`mode` ({}) parameter. Either pass these parameters when " + "instantiating the scheduler, or pass them as parameters " + "to `tune.TuneConfig()`".format( + self.__class__.__name__, self._metric, self._mode + ) + ) + + cur_bracket = self._state["bracket"] + cur_band = self._hyperbands[self._state["band_idx"]] + if cur_bracket is None or cur_bracket.filled(): + retry = True + while retry: + # if current iteration is filled, create new iteration + if self._cur_band_filled(): + cur_band = [] + self._hyperbands.append(cur_band) + self._state["band_idx"] += 1 + + # cur_band will always be less than s_max_1 or else filled + s = len(cur_band) + assert s < self._s_max_1, "Current band is filled!" + if self._get_r0(s) == 0: + logger.info("Bracket too small - Retrying...") + cur_bracket = None + else: + retry = False + cur_bracket = self._create_bracket(s) + cur_band.append(cur_bracket) + self._state["bracket"] = cur_bracket + + self._state["bracket"].add_trial(trial) + self._trial_info[trial] = cur_bracket, self._state["band_idx"] + + def _create_bracket(self, s): + return _Bracket( + time_attr=self._time_attr, + max_trials=self._get_n0(s), + init_t_attr=self._get_r0(s), + max_t_attr=self._max_t_attr, + eta=self._eta, + s=s, + stop_last_trials=self._stop_last_trials, + ) + + def _cur_band_filled(self) -> bool: + """Checks if the current band is filled. + + The size of the current band should be equal to s_max_1""" + + cur_band = self._hyperbands[self._state["band_idx"]] + return len(cur_band) == self._s_max_1 + + def on_trial_result( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ): + """If bracket is finished, all trials will be stopped. + + If a given trial finishes and bracket iteration is not done, + the trial will be paused and resources will be given up. + + This scheduler will not start trials but will stop trials. + The current running trial will not be handled, + as the trialrunner will be given control to handle it.""" + + bracket, _ = self._trial_info[trial] + bracket.update_trial_stats(trial, result) + + if bracket.continue_trial(trial): + return TrialScheduler.CONTINUE + + logger.debug(f"Processing bracket after trial {trial} result") + action = self._process_bracket(tune_controller, bracket) + logger.debug( + f"{action} for {trial} on " + f"{self._time_attr}={result.get(self._time_attr)}" + ) + return action + + def _process_bracket( + self, tune_controller: "TuneController", bracket: "_Bracket" + ) -> str: + """This is called whenever a trial makes progress. + + When all live trials in the bracket have no more iterations left, + Trials will be successively halved. If bracket is done, all + non-running trials will be stopped and cleaned up, + and during each halving phase, bad trials will be stopped while good + trials will return to "PENDING". + + Note some implicit conditions here: In ``on_trial_result`` a trial is + either continued (e.g. if it didn't reach the time threshold for the bracket) + or this method (``_process_bracket``) is called. If there are other trials left + that still haven't reached the threshold, the trial is PAUSED. This means + that when the bracket is actually processed (``bracket.cur_iter_done``), there + is at most one RUNNING trial (which is the trial that is currently processed) + and the rest are either PAUSED (as explained above) or TERMINATED/ERRORED + (if they finish separately). + """ + + action = TrialScheduler.PAUSE + if bracket.cur_iter_done(): + if bracket.finished(): + bracket.cleanup_full(tune_controller) + return TrialScheduler.STOP + + bracket.is_being_processed = True + + good, bad = bracket.successive_halving(self._metric, self._metric_op) + + logger.debug( + f"Processing {len(good)} good and {len(bad)} bad trials in " + f"bracket {bracket}.\n" + f"Good: {good}\nBad: {bad}" + ) + + # kill bad trials + self._num_stopped += len(bad) + for t in bad: + if t.status == Trial.PAUSED or t.is_saving: + logger.debug(f"Stopping other trial {str(t)}") + tune_controller.stop_trial(t) + elif t.status == Trial.RUNNING: + # See the docstring: There can only be at most one RUNNING + # trial, which is the current trial. + logger.debug(f"Stopping current trial {str(t)}") + bracket.cleanup_trial(t) + action = TrialScheduler.STOP + else: + # Trials cannot be ERROR/TERMINATED, as then they would have + # been removed from the bracket (in `bracket.cleanup_trial`). + # Trials cannot be PENDING, as then they wouldn't have reported + # enough results to finish the bracket, and it wouldn't be + # processed. + raise TuneError( + f"Trial with unexpected bad status encountered: " + f"{str(t)} is {t.status}" + ) + + # ready the good trials - if trial is too far ahead, don't continue + for t in good: + if bracket.continue_trial(t): + # The scheduler should have cleaned up this trial already. + assert t.status not in (Trial.ERROR, Trial.TERMINATED), ( + f"Good trial {t.trial_id} is in an invalid state: {t.status}\n" + "Expected trial to be either PAUSED, PENDING, or RUNNING.\n" + "If you encounter this, please file an issue on the Ray Github." + ) + if t.status == Trial.PAUSED or t.is_saving: + logger.debug(f"Unpausing trial {str(t)}") + self._unpause_trial(tune_controller, t) + bracket.trials_to_unpause.add(t) + elif t.status == Trial.RUNNING: + # See the docstring: There can only be at most one RUNNING + # trial, which is the current trial. + logger.debug(f"Continuing current trial {str(t)}") + action = TrialScheduler.CONTINUE + # else: PENDING trial (from a previous unpause) should stay as is. + elif bracket.finished() and bracket.stop_last_trials: + # Scheduler decides to not continue trial because the bracket + # reached max_t. In this case, stop the trials + if t.status == Trial.PAUSED or t.is_saving: + logger.debug(f"Bracket finished. Stopping other trial {str(t)}") + tune_controller.stop_trial(t) + elif t.status == Trial.RUNNING: + # See the docstring: There can only be at most one RUNNING + # trial, which is the current trial. + logger.debug( + f"Bracket finished. Stopping current trial {str(t)}" + ) + bracket.cleanup_trial(t) + action = TrialScheduler.STOP + return action + + def _unpause_trial(self, tune_controller: "TuneController", trial: Trial): + """No-op by default.""" + return + + def on_trial_remove(self, tune_controller: "TuneController", trial: Trial): + """Notification when trial terminates. + + Trial info is removed from bracket. Triggers halving if bracket is + not finished.""" + bracket, _ = self._trial_info[trial] + bracket.cleanup_trial(trial) + if not bracket.finished() and not bracket.is_being_processed: + logger.debug(f"Processing bracket after trial {trial} removed") + self._process_bracket(tune_controller, bracket) + + def on_trial_complete( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ): + """Cleans up trial info from bracket if trial completed early.""" + self.on_trial_remove(tune_controller, trial) + + def on_trial_error(self, tune_controller: "TuneController", trial: Trial): + """Cleans up trial info from bracket if trial errored early.""" + self.on_trial_remove(tune_controller, trial) + + def choose_trial_to_run(self, tune_controller: "TuneController") -> Optional[Trial]: + """Fair scheduling within iteration by completion percentage. + + List of trials not used since all trials are tracked as state + of scheduler. If iteration is occupied (ie, no trials to run), + then look into next iteration. + """ + + for hyperband in self._hyperbands: + # band will have None entries if no resources + # are to be allocated to that bracket. + scrubbed = [b for b in hyperband if b is not None] + for bracket in sorted(scrubbed, key=lambda b: b.completion_percentage()): + for trial in bracket.current_trials(): + if ( + trial.status == Trial.PAUSED + and trial in bracket.trials_to_unpause + ) or trial.status == Trial.PENDING: + return trial + return None + + def debug_string(self) -> str: + """This provides a progress notification for the algorithm. + + For each bracket, the algorithm will output a string as follows: + + Bracket(Max Size (n)=5, Milestone (r)=33, completed=14.6%): + {PENDING: 2, RUNNING: 3, TERMINATED: 2} + + "Max Size" indicates the max number of pending/running experiments + set according to the Hyperband algorithm. + + "Milestone" indicates the iterations a trial will run for before + the next halving will occur. + + "Completed" indicates an approximate progress metric. Some brackets, + like ones that are unfilled, will not reach 100%. + """ + out = "Using HyperBand: " + out += "num_stopped={} total_brackets={}".format( + self._num_stopped, sum(len(band) for band in self._hyperbands) + ) + for i, band in enumerate(self._hyperbands): + out += "\nRound #{}:".format(i) + for bracket in band: + if bracket: + out += "\n {}".format(bracket) + return out + + def state(self) -> Dict[str, int]: + return { + "num_brackets": sum(len(band) for band in self._hyperbands), + "num_stopped": self._num_stopped, + } + + +class _Bracket: + """Logical object for tracking Hyperband bracket progress. Keeps track + of proper parameters as designated by HyperBand. + + Also keeps track of progress to ensure good scheduling. + """ + + def __init__( + self, + time_attr: str, + max_trials: int, + init_t_attr: int, + max_t_attr: int, + eta: float, + s: int, + stop_last_trials: bool = True, + ): + self._live_trials = {} # maps trial -> current result + self._all_trials = [] + self._time_attr = time_attr # attribute to + + self._n = self._n0 = max_trials + self._r = self._r0 = init_t_attr + self._max_t_attr = max_t_attr + self._cumul_r = self._r0 + + self._eta = eta + self._halves = s + + self._total_work = self._calculate_total_work(self._n0, self._r0, s) + self._completed_progress = 0 + self.stop_last_trials = stop_last_trials + self.is_being_processed = False + + self.trials_to_unpause = set() + + def add_trial(self, trial: Trial): + """Add trial to bracket assuming bracket is not filled. + + At a later iteration, a newly added trial will be given equal + opportunity to catch up.""" + assert not self.filled(), "Cannot add trial to filled bracket!" + self._live_trials[trial] = None + self._all_trials.append(trial) + + def cur_iter_done(self) -> bool: + """Checks if all iterations have completed. + + TODO(rliaw): also check that `t.iterations == self._r`""" + return all( + self._get_result_time(result) >= self._cumul_r + for result in self._live_trials.values() + ) + + def finished(self) -> bool: + if not self.stop_last_trials: + return False + return self._halves == 0 and self.cur_iter_done() + + def current_trials(self) -> List[Trial]: + return list(self._live_trials) + + def continue_trial(self, trial: Trial) -> bool: + result = self._live_trials[trial] + if not self.stop_last_trials and self._halves == 0: + return True + elif self._get_result_time(result) < self._cumul_r: + logger.debug( + f"Continuing trial {trial} as it hasn't reached the time threshold " + f"{self._cumul_r}, yet." + ) + return True + return False + + def filled(self) -> bool: + """Checks if bracket is filled. + + Only let new trials be added at current level minimizing the need + to backtrack and bookkeep previous medians.""" + + return len(self._live_trials) == self._n + + def successive_halving( + self, metric: str, metric_op: float + ) -> Tuple[List[Trial], List[Trial]]: + if self._halves == 0 and not self.stop_last_trials: + return self._live_trials, [] + assert self._halves > 0 + + # "Halving" is a misnomer. We're actually reducing by factor `eta`. + self._halves -= 1 + + # If we had 8 trials in the bracket and eta=2, we will keep 4. + # If we had 9 trials in the bracket and eta=3, we will keep 3. + self._n = int(np.ceil(self._n / self._eta)) + + # Likewise, we increase the number of iterations until we process the bracket + # again. + # Remember r0 = max_t * self._eta ** (-s) + # Let max_t=16, eta=2, s=1. Then r0=8, and we calculate r1=16. + # Let max_t=16, eta=2, s=2. Then r0=4, and we calculate r1=8, r2=16. + + # Let max_t=81, eta=3, s=1. Then r0=27, and we calculate r1=81. + # Let max_t=81, eta=3, s=2. Then r0=9, and we calculate r1=27, r2=81. + self._r *= self._eta + self._r = int(min(self._r, self._max_t_attr)) + self._cumul_r = self._r + sorted_trials = sorted( + self._live_trials, key=lambda t: metric_op * self._live_trials[t][metric] + ) + + good, bad = sorted_trials[-self._n :], sorted_trials[: -self._n] + return good, bad + + def update_trial_stats(self, trial: Trial, result: Dict): + """Update result for trial. Called after trial has finished + an iteration - will decrement iteration count. + + TODO(rliaw): The other alternative is to keep the trials + in and make sure they're not set as pending later.""" + + assert trial in self._live_trials + assert self._get_result_time(result) >= 0 + observed_time = self._get_result_time(result) + last_observed = self._get_result_time(self._live_trials[trial]) + + delta = observed_time - last_observed + if delta <= 0: + logger.info( + "Restoring from a previous point in time. " + "Previous={}; Now={}".format(last_observed, observed_time) + ) + self._completed_progress += delta + self._live_trials[trial] = result + self.trials_to_unpause.discard(trial) + + def cleanup_trial(self, trial: Trial): + """Clean up statistics tracking for terminated trials (either by force + or otherwise). + + This may cause bad trials to continue for a long time, in the case + where all the good trials finish early and there are only bad trials + left in a bracket with a large max-iteration.""" + self._live_trials.pop(trial, None) + + def cleanup_full(self, tune_controller: "TuneController"): + """Cleans up bracket after bracket is completely finished. + + Lets the last trial continue to run until termination condition + kicks in.""" + for trial in self.current_trials(): + if trial.status == Trial.PAUSED: + tune_controller.stop_trial(trial) + + def completion_percentage(self) -> float: + """Returns a progress metric. + + This will not be always finish with 100 since dead trials + are dropped.""" + if self.finished(): + return 1.0 + return min(self._completed_progress / self._total_work, 1.0) + + def _get_result_time(self, result: Dict) -> float: + if result is None: + return 0 + return result[self._time_attr] + + def _calculate_total_work(self, n: int, r: float, s: int): + work = 0 + cumulative_r = r + for _ in range(s + 1): + work += int(n) * int(r) + n /= self._eta + n = int(np.ceil(n)) + r *= self._eta + r = int(min(r, self._max_t_attr - cumulative_r)) + return work + + def __repr__(self) -> str: + status = ", ".join( + [ + "Max Size (n)={}".format(self._n), + "Milestone (r)={}".format(self._cumul_r), + "completed={:.1%}".format(self.completion_percentage()), + ] + ) + counts = collections.Counter([t.status for t in self._all_trials]) + trial_statuses = ", ".join( + sorted("{}: {}".format(k, v) for k, v in counts.items()) + ) + return "Bracket({}): {{{}}} ".format(status, trial_statuses) diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/median_stopping_rule.py b/venv/lib/python3.10/site-packages/ray/tune/schedulers/median_stopping_rule.py new file mode 100644 index 0000000000000000000000000000000000000000..9b5cb35f7a53eb456521893c76d4ab6964ddc2c9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/schedulers/median_stopping_rule.py @@ -0,0 +1,217 @@ +import collections +import logging +from typing import TYPE_CHECKING, Dict, List, Optional + +import numpy as np + +from ray.tune.experiment import Trial +from ray.tune.result import DEFAULT_METRIC +from ray.tune.schedulers.trial_scheduler import FIFOScheduler, TrialScheduler +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.tune.execution.tune_controller import TuneController + +logger = logging.getLogger(__name__) + + +@PublicAPI +class MedianStoppingRule(FIFOScheduler): + """Implements the median stopping rule as described in the Vizier paper: + + https://research.google.com/pubs/pub46180.html + + Args: + time_attr: The training result attr to use for comparing time. + Note that you can pass in something non-temporal such as + `training_iteration` as a measure of progress, the only requirement + is that the attribute should increase monotonically. + metric: The training result objective value attribute. Stopping + procedures will use this attribute. If None but a mode was passed, + the `ray.tune.result.DEFAULT_METRIC` will be used per default. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. + grace_period: Only stop trials at least this old in time. + The mean will only be computed from this time onwards. The units + are the same as the attribute named by `time_attr`. + min_samples_required: Minimum number of trials to compute median + over. + min_time_slice: Each trial runs at least this long before + yielding (assuming it isn't stopped). Note: trials ONLY yield if + there are not enough samples to evaluate performance for the + current result AND there are other trials waiting to run. + The units are the same as the attribute named by `time_attr`. + hard_stop: If False, pauses trials instead of stopping + them. When all other trials are complete, paused trials will be + resumed and allowed to run FIFO. + """ + + def __init__( + self, + time_attr: str = "time_total_s", + metric: Optional[str] = None, + mode: Optional[str] = None, + grace_period: float = 60.0, + min_samples_required: int = 3, + min_time_slice: int = 0, + hard_stop: bool = True, + ): + super().__init__() + self._stopped_trials = set() + self._grace_period = grace_period + self._min_samples_required = min_samples_required + self._min_time_slice = min_time_slice + self._metric = metric + self._worst = None + self._compare_op = None + + self._mode = mode + if mode: + assert mode in ["min", "max"], "`mode` must be 'min' or 'max'." + self._worst = float("-inf") if self._mode == "max" else float("inf") + self._compare_op = max if self._mode == "max" else min + + self._time_attr = time_attr + self._hard_stop = hard_stop + self._trial_state = {} + self._last_pause = collections.defaultdict(lambda: float("-inf")) + self._results = collections.defaultdict(list) + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], **spec + ) -> bool: + if self._metric and metric: + return False + if self._mode and mode: + return False + + if metric: + self._metric = metric + if mode: + self._mode = mode + + self._worst = float("-inf") if self._mode == "max" else float("inf") + self._compare_op = max if self._mode == "max" else min + + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + return True + + def on_trial_add(self, tune_controller: "TuneController", trial: Trial): + if not self._metric or not self._worst or not self._compare_op: + raise ValueError( + "{} has been instantiated without a valid `metric` ({}) or " + "`mode` ({}) parameter. Either pass these parameters when " + "instantiating the scheduler, or pass them as parameters " + "to `tune.TuneConfig()`".format( + self.__class__.__name__, self._metric, self._mode + ) + ) + + super(MedianStoppingRule, self).on_trial_add(tune_controller, trial) + + def on_trial_result( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ) -> str: + """Callback for early stopping. + + This stopping rule stops a running trial if the trial's best objective + value by step `t` is strictly worse than the median of the running + averages of all completed trials' objectives reported up to step `t`. + """ + if self._time_attr not in result or self._metric not in result: + return TrialScheduler.CONTINUE + + if trial in self._stopped_trials: + assert not self._hard_stop + # Fall back to FIFO + return TrialScheduler.CONTINUE + + time = result[self._time_attr] + self._results[trial].append(result) + + if time < self._grace_period: + return TrialScheduler.CONTINUE + + trials = self._trials_beyond_time(time) + trials.remove(trial) + + if len(trials) < self._min_samples_required: + action = self._on_insufficient_samples(tune_controller, trial, time) + if action == TrialScheduler.PAUSE: + self._last_pause[trial] = time + action_str = "Yielding time to other trials." + else: + action_str = "Continuing anyways." + logger.debug( + "MedianStoppingRule: insufficient samples={} to evaluate " + "trial {} at t={}. {}".format( + len(trials), trial.trial_id, time, action_str + ) + ) + return action + + median_result = self._median_result(trials, time) + best_result = self._best_result(trial) + logger.debug( + "Trial {} best res={} vs median res={} at t={}".format( + trial, best_result, median_result, time + ) + ) + + if self._compare_op(median_result, best_result) != best_result: + logger.debug("MedianStoppingRule: early stopping {}".format(trial)) + self._stopped_trials.add(trial) + if self._hard_stop: + return TrialScheduler.STOP + else: + return TrialScheduler.PAUSE + else: + return TrialScheduler.CONTINUE + + def on_trial_complete( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ): + self._results[trial].append(result) + + def debug_string(self) -> str: + return "Using MedianStoppingRule: num_stopped={}.".format( + len(self._stopped_trials) + ) + + def _on_insufficient_samples( + self, tune_controller: "TuneController", trial: Trial, time: float + ) -> str: + pause = time - self._last_pause[trial] > self._min_time_slice + pause = pause and [ + t + for t in tune_controller.get_live_trials() + if t.status in (Trial.PENDING, Trial.PAUSED) + ] + return TrialScheduler.PAUSE if pause else TrialScheduler.CONTINUE + + def _trials_beyond_time(self, time: float) -> List[Trial]: + trials = [ + trial + for trial in self._results + if self._results[trial][-1][self._time_attr] >= time + ] + return trials + + def _median_result(self, trials: List[Trial], time: float): + return np.median([self._running_mean(trial, time) for trial in trials]) + + def _running_mean(self, trial: Trial, time: float) -> np.ndarray: + results = self._results[trial] + # TODO(ekl) we could do interpolation to be more precise, but for now + # assume len(results) is large and the time diffs are roughly equal + scoped_results = [ + r for r in results if self._grace_period <= r[self._time_attr] <= time + ] + return np.mean([r[self._metric] for r in scoped_results]) + + def _best_result(self, trial): + results = self._results[trial] + return self._compare_op([r[self._metric] for r in results]) diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/pb2.py b/venv/lib/python3.10/site-packages/ray/tune/schedulers/pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..b80295d00ee4c5e4d3c7d16cb26ed45fceb2f5e3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/schedulers/pb2.py @@ -0,0 +1,507 @@ +import logging +from copy import deepcopy +from typing import TYPE_CHECKING, Callable, Dict, Optional, Tuple, Union + +import numpy as np +import pandas as pd + +from ray.tune import TuneError +from ray.tune.experiment import Trial +from ray.tune.schedulers import PopulationBasedTraining +from ray.tune.schedulers.pbt import _PBTTrialState +from ray.tune.utils.util import flatten_dict, unflatten_dict +from ray.util.debug import log_once + +if TYPE_CHECKING: + from ray.tune.execution.tune_controller import TuneController + + +def import_pb2_dependencies(): + try: + import GPy + except ImportError: + GPy = None + try: + import sklearn + except ImportError: + sklearn = None + return GPy, sklearn + + +GPy, has_sklearn = import_pb2_dependencies() + +if GPy and has_sklearn: + from ray.tune.schedulers.pb2_utils import ( + UCB, + TV_SquaredExp, + normalize, + optimize_acq, + select_length, + standardize, + ) + +logger = logging.getLogger(__name__) + + +def _fill_config( + config: Dict, hyperparam_bounds: Dict[str, Union[dict, list, tuple]] +) -> Dict: + """Fills missing hyperparameters in config by sampling uniformly from the + specified `hyperparam_bounds`. + Recursively fills the config if `hyperparam_bounds` is a nested dict. + + This is a helper used to set initial hyperparameter values if the user doesn't + specify them in the Tuner `param_space`. + + Returns the dict of filled hyperparameters. + """ + filled_hyperparams = {} + for param_name, bounds in hyperparam_bounds.items(): + if isinstance(bounds, dict): + if param_name not in config: + config[param_name] = {} + filled_hyperparams[param_name] = _fill_config(config[param_name], bounds) + elif isinstance(bounds, (list, tuple)) and param_name not in config: + if log_once(param_name + "-missing"): + logger.debug( + f"Cannot find {param_name} in config. Initializing by " + "sampling uniformly from the provided `hyperparam_bounds`." + ) + assert len(bounds) == 2 + low, high = bounds + config[param_name] = filled_hyperparams[param_name] = np.random.uniform( + low, high + ) + return filled_hyperparams + + +def _select_config( + Xraw: np.array, + yraw: np.array, + current: list, + newpoint: np.array, + bounds: dict, + num_f: int, +) -> np.ndarray: + """Selects the next hyperparameter config to try. + + This function takes the formatted data, fits the GP model and optimizes the + UCB acquisition function to select the next point. + + Args: + Xraw: The un-normalized array of hyperparams, Time and + Reward + yraw: The un-normalized vector of reward changes. + current: The hyperparams of trials currently running. This is + important so we do not select the same config twice. If there is + data here then we fit a second GP including it + (with fake y labels). The GP variance doesn't depend on the y + labels so it is ok. + newpoint: The Reward and Time for the new point. + We cannot change these as they are based on the *new weights*. + bounds: Bounds for the hyperparameters. Used to normalize. + num_f: The number of fixed params. Almost always 2 (reward+time) + + Return: + xt: A vector of new hyperparameters. + """ + length = select_length(Xraw, yraw, bounds, num_f) + + Xraw = Xraw[-length:, :] + yraw = yraw[-length:] + + base_vals = np.array(list(bounds.values())).T + oldpoints = Xraw[:, :num_f] + old_lims = np.concatenate( + (np.max(oldpoints, axis=0), np.min(oldpoints, axis=0)) + ).reshape(2, oldpoints.shape[1]) + limits = np.concatenate((old_lims, base_vals), axis=1) + + X = normalize(Xraw, limits) + y = standardize(yraw).reshape(yraw.size, 1) + + fixed = normalize(newpoint, oldpoints) + + kernel = TV_SquaredExp( + input_dim=X.shape[1], variance=1.0, lengthscale=1.0, epsilon=0.1 + ) + + try: + m = GPy.models.GPRegression(X, y, kernel) + except np.linalg.LinAlgError: + # add diagonal ** we would ideally make this something more robust... + X += np.eye(X.shape[0]) * 1e-3 + m = GPy.models.GPRegression(X, y, kernel) + + try: + m.optimize() + except np.linalg.LinAlgError: + # add diagonal ** we would ideally make this something more robust... + X += np.eye(X.shape[0]) * 1e-3 + m = GPy.models.GPRegression(X, y, kernel) + m.optimize() + + m.kern.lengthscale.fix(m.kern.lengthscale.clip(1e-5, 1)) + + if current is None: + m1 = deepcopy(m) + else: + # add the current trials to the dataset + padding = np.array([fixed for _ in range(current.shape[0])]) + current = normalize(current, base_vals) + current = np.hstack((padding, current)) + + Xnew = np.vstack((X, current)) + ypad = np.zeros(current.shape[0]) + ypad = ypad.reshape(-1, 1) + ynew = np.vstack((y, ypad)) + + # kernel = GPy.kern.RBF(input_dim=X.shape[1], variance=1., + # lengthscale=1.) + kernel = TV_SquaredExp( + input_dim=X.shape[1], variance=1.0, lengthscale=1.0, epsilon=0.1 + ) + m1 = GPy.models.GPRegression(Xnew, ynew, kernel) + m1.optimize() + + xt = optimize_acq(UCB, m, m1, fixed, num_f) + + # convert back... + xt = xt * (np.max(base_vals, axis=0) - np.min(base_vals, axis=0)) + np.min( + base_vals, axis=0 + ) + + xt = xt.astype(np.float32) + return xt + + +def _explore( + data: pd.DataFrame, + bounds: Dict[str, Tuple[float, float]], + current: list, + base: Trial, + old: Trial, + config: Dict[str, Tuple[float, float]], +) -> Tuple[Dict, pd.DataFrame]: + """Returns next hyperparameter configuration to use. + + This function primarily processes the data from completed trials + and then requests the next config from the select_config function. + It then adds the new trial to the dataframe, so that the reward change + can be computed using the new weights. + It returns the new point and the dataframe with the new entry. + """ + + df = data.sort_values(by="Time").reset_index(drop=True) + + # Group by trial ID and hyperparams. + # Compute change in timesteps and reward. + df["y"] = df.groupby(["Trial"] + list(bounds.keys()))["Reward"].diff() + df["t_change"] = df.groupby(["Trial"] + list(bounds.keys()))["Time"].diff() + + # Delete entries without positive change in t. + df = df[df["t_change"] > 0].reset_index(drop=True) + df["R_before"] = df.Reward - df.y + + # Normalize the reward change by the update size. + # For example if trials took diff lengths of time. + df["y"] = df.y / df.t_change + df = df[~df.y.isna()].reset_index(drop=True) + df = df.sort_values(by="Time").reset_index(drop=True) + + # Only use the last 1k datapoints, so the GP is not too slow. + df = df.iloc[-1000:, :].reset_index(drop=True) + + # We need this to know the T and Reward for the weights. + dfnewpoint = df[df["Trial"] == str(base)] + + if not dfnewpoint.empty: + # N ow specify the dataset for the GP. + y = np.array(df.y.values) + # Meta data we keep -> episodes and reward. + # (TODO: convert to curve) + t_r = df[["Time", "R_before"]] + hparams = df[bounds.keys()] + X = pd.concat([t_r, hparams], axis=1).values + newpoint = df[df["Trial"] == str(base)].iloc[-1, :][["Time", "R_before"]].values + new = _select_config(X, y, current, newpoint, bounds, num_f=len(t_r.columns)) + + new_config = config.copy() + values = [] + # Cast types for new hyperparameters. + for i, col in enumerate(hparams.columns): + # Use the type from the old config. Like this types + # should be passed on from the first config downwards. + type_ = type(config[col]) + new_config[col] = type_(new[i]) + values.append(type_(new[i])) + + new_T = df[df["Trial"] == str(base)].iloc[-1, :]["Time"] + new_Reward = df[df["Trial"] == str(base)].iloc[-1, :].Reward + + lst = [[str(old)] + [new_T] + values + [new_Reward]] + cols = ["Trial", "Time"] + list(bounds) + ["Reward"] + new_entry = pd.DataFrame(lst, columns=cols) + + # Create an entry for the new config, with the reward from the + # copied agent. + data = pd.concat([data, new_entry]).reset_index(drop=True) + + else: + new_config = config.copy() + + return new_config, data + + +class PB2(PopulationBasedTraining): + """Implements the Population Based Bandit (PB2) algorithm. + + PB2 trains a group of models (or agents) in parallel. Periodically, poorly + performing models clone the state of the top performers, and the hyper- + parameters are re-selected using GP-bandit optimization. The GP model is + trained to predict the improvement in the next training period. + + Like PBT, PB2 adapts hyperparameters during training time. This enables + very fast hyperparameter discovery and also automatically discovers + schedules. + + This Tune PB2 implementation is built on top of Tune's PBT implementation. + It considers all trials added as part of the PB2 population. If the number + of trials exceeds the cluster capacity, they will be time-multiplexed as to + balance training progress across the population. To run multiple trials, + use `tune.TuneConfig(num_samples=)`. + + In {LOG_DIR}/{MY_EXPERIMENT_NAME}/, all mutations are logged in + `pb2_global.txt` and individual policy perturbations are recorded + in pb2_policy_{i}.txt. Tune logs: [target trial tag, clone trial tag, + target trial iteration, clone trial iteration, old config, new config] + on each perturbation step. + + Args: + time_attr: The training result attr to use for comparing time. + Note that you can pass in something non-temporal such as + `training_iteration` as a measure of progress, the only requirement + is that the attribute should increase monotonically. + metric: The training result objective value attribute. Stopping + procedures will use this attribute. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. + perturbation_interval: Models will be considered for + perturbation at this interval of `time_attr`. Note that + perturbation incurs checkpoint overhead, so you shouldn't set this + to be too frequent. + hyperparam_bounds: Hyperparameters to mutate. The format is + as follows: for each key, enter a list of the form [min, max] + representing the minimum and maximum possible hyperparam values. + A key can also hold a dict for nested hyperparameters. + Tune will sample uniformly between the bounds provided by + `hyperparam_bounds` for the initial hyperparameter values if the + corresponding hyperparameters are not present in a trial's initial `config`. + quantile_fraction: Parameters are transferred from the top + `quantile_fraction` fraction of trials to the bottom + `quantile_fraction` fraction. Needs to be between 0 and 0.5. + Setting it to 0 essentially implies doing no exploitation at all. + custom_explore_fn: You can also specify a custom exploration + function. This function is invoked as `f(config)`, where the input + is the new config generated by Bayesian Optimization. This function + should return the `config` updated as needed. + log_config: Whether to log the ray config of each model to + local_dir at each exploit. Allows config schedule to be + reconstructed. + require_attrs: Whether to require time_attr and metric to appear + in result for every iteration. If True, error will be raised + if these values are not present in trial result. + synch: If False, will use asynchronous implementation of + PBT. Trial perturbations occur every perturbation_interval for each + trial independently. If True, will use synchronous implementation + of PBT. Perturbations will occur only after all trials are + synced at the same time_attr every perturbation_interval. + Defaults to False. See Appendix A.1 here + https://arxiv.org/pdf/1711.09846.pdf. + + Example: + + .. code-block:: python + + from ray import tune + from ray.tune.schedulers.pb2 import PB2 + from ray.tune.examples.pbt_function import pbt_function + # run "pip install gpy" to use PB2 + + pb2 = PB2( + metric="mean_accuracy", + mode="max", + perturbation_interval=20, + hyperparam_bounds={"lr": [0.0001, 0.1]}, + ) + tuner = tune.Tuner( + pbt_function, + tune_config=tune.TuneConfig( + scheduler=pb2, + num_samples=8, + ), + param_space={"lr": 0.0001}, + ) + tuner.fit() + + """ + + def __init__( + self, + time_attr: str = "time_total_s", + metric: Optional[str] = None, + mode: Optional[str] = None, + perturbation_interval: float = 60.0, + hyperparam_bounds: Dict[str, Union[dict, list, tuple]] = None, + quantile_fraction: float = 0.25, + log_config: bool = True, + require_attrs: bool = True, + synch: bool = False, + custom_explore_fn: Optional[Callable[[dict], dict]] = None, + ): + + gpy_available, sklearn_available = import_pb2_dependencies() + if not gpy_available: + raise RuntimeError("Please install GPy to use PB2.") + + if not sklearn_available: + raise RuntimeError("Please install scikit-learn to use PB2.") + + hyperparam_bounds = hyperparam_bounds or {} + + if not hyperparam_bounds: + raise TuneError( + "`hyperparam_bounds` must be specified to use PB2 scheduler." + ) + + super(PB2, self).__init__( + time_attr=time_attr, + metric=metric, + mode=mode, + perturbation_interval=perturbation_interval, + hyperparam_mutations=hyperparam_bounds, + quantile_fraction=quantile_fraction, + resample_probability=0, + custom_explore_fn=custom_explore_fn, + log_config=log_config, + require_attrs=require_attrs, + synch=synch, + ) + + self.last_exploration_time = 0 # when we last explored + self.data = pd.DataFrame() + + self._hyperparam_bounds = hyperparam_bounds + self._hyperparam_bounds_flat = flatten_dict( + hyperparam_bounds, prevent_delimiter=True + ) + self._validate_hyperparam_bounds(self._hyperparam_bounds_flat) + + # Current = trials running that have already re-started after reaching + # the checkpoint. When exploring we care if these trials + # are already in or scheduled to be in the next round. + self.current = None + + def on_trial_add(self, tune_controller: "TuneController", trial: Trial): + filled_hyperparams = _fill_config(trial.config, self._hyperparam_bounds) + # Make sure that the params we sampled show up in the CLI output + trial.evaluated_params.update(flatten_dict(filled_hyperparams)) + super().on_trial_add(tune_controller, trial) + + def _validate_hyperparam_bounds(self, hyperparam_bounds: dict): + """Check that each hyperparam bound is of the form [low, high]. + + Raises: + ValueError: if any of the hyperparam bounds are of an invalid format. + """ + for key, value in hyperparam_bounds.items(): + if not isinstance(value, (list, tuple)) or len(value) != 2: + raise ValueError( + "`hyperparam_bounds` values must either be " + f"a list or tuple of size 2, but got {value} " + f"instead for the param '{key}'" + ) + low, high = value + if low > high: + raise ValueError( + "`hyperparam_bounds` values must be of the form [low, high] " + f"where low <= high, but got {value} instead for param '{key}'." + ) + + def _save_trial_state( + self, state: _PBTTrialState, time: int, result: Dict, trial: Trial + ): + score = super(PB2, self)._save_trial_state(state, time, result, trial) + + # Data logging for PB2. + + # Collect hyperparams names and current values for this trial. + names = list(self._hyperparam_bounds_flat.keys()) + flattened_config = flatten_dict(trial.config) + values = [flattened_config[key] for key in names] + + # Store trial state and hyperparams in dataframe. + # this needs to be made more general. + lst = [[trial, result[self._time_attr]] + values + [score]] + cols = ["Trial", "Time"] + names + ["Reward"] + entry = pd.DataFrame(lst, columns=cols) + + self.data = pd.concat([self.data, entry]).reset_index(drop=True) + self.data.Trial = self.data.Trial.astype("str") + + def _get_new_config(self, trial: Trial, trial_to_clone: Trial) -> Tuple[Dict, Dict]: + """Gets new config for trial by exploring trial_to_clone's config using + Bayesian Optimization (BO) to choose the hyperparameter values to explore. + + Overrides `PopulationBasedTraining._get_new_config`. + + Args: + trial: The current trial that decided to exploit trial_to_clone. + trial_to_clone: The top-performing trial with a hyperparameter config + that the current trial will explore. + + Returns: + new_config: New hyperparameter configuration (after BO). + operations: Empty dict since PB2 doesn't explore in easily labeled ways + like PBT does. + """ + # If we are at a new timestep, we dont want to penalise for trials + # still going. + if self.data["Time"].max() > self.last_exploration_time: + self.current = None + + new_config_flat, data = _explore( + self.data, + self._hyperparam_bounds_flat, + self.current, + trial_to_clone, + trial, + flatten_dict(trial_to_clone.config), + ) + + # Important to replace the old values, since we are copying across + self.data = data.copy() + + # If the current guy being selecting is at a point that is already + # done, then append the data to the "current" which contains the + # points in the current batch. + new = [new_config_flat[key] for key in self._hyperparam_bounds_flat] + + new = np.array(new) + new = new.reshape(1, new.size) + if self.data["Time"].max() > self.last_exploration_time: + self.last_exploration_time = self.data["Time"].max() + self.current = new.copy() + else: + self.current = np.concatenate((self.current, new), axis=0) + logger.debug(self.current) + + new_config = unflatten_dict(new_config_flat) + + if self._custom_explore_fn: + new_config = self._custom_explore_fn(new_config) + assert ( + new_config is not None + ), "Custom explore function failed to return a new config" + + return new_config, {} diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/pb2_utils.py b/venv/lib/python3.10/site-packages/ray/tune/schedulers/pb2_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cdd06af9b4ef155a3cee6d99a200eaa8ad1e1438 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/schedulers/pb2_utils.py @@ -0,0 +1,183 @@ +import GPy +import numpy as np +from GPy.core import Param +from GPy.kern import Kern +from scipy.optimize import minimize +from sklearn.metrics import pairwise_distances +from sklearn.metrics.pairwise import euclidean_distances + + +class TV_SquaredExp(Kern): + """Time varying squared exponential kernel. + For more info see the TV-GP-UCB paper: + http://proceedings.mlr.press/v51/bogunovic16.pdf + """ + + def __init__( + self, input_dim, variance=1.0, lengthscale=1.0, epsilon=0.0, active_dims=None + ): + super().__init__(input_dim, active_dims, "time_se") + self.variance = Param("variance", variance) + self.lengthscale = Param("lengthscale", lengthscale) + self.epsilon = Param("epsilon", epsilon) + self.link_parameters(self.variance, self.lengthscale, self.epsilon) + + def K(self, X, X2): + # time must be in the far left column + if self.epsilon > 0.5: # 0.5 + self.epsilon = 0.5 + if X2 is None: + X2 = np.copy(X) + T1 = X[:, 0].reshape(-1, 1) + T2 = X2[:, 0].reshape(-1, 1) + dists = pairwise_distances(T1, T2, "cityblock") + timekernel = (1 - self.epsilon) ** (0.5 * dists) + + X = X[:, 1:] + X2 = X2[:, 1:] + + RBF = self.variance * np.exp( + -np.square(euclidean_distances(X, X2)) / self.lengthscale + ) + + return RBF * timekernel + + def Kdiag(self, X): + return self.variance * np.ones(X.shape[0]) + + def update_gradients_full(self, dL_dK, X, X2): + if X2 is None: + X2 = np.copy(X) + T1 = X[:, 0].reshape(-1, 1) + T2 = X2[:, 0].reshape(-1, 1) + + X = X[:, 1:] + X2 = X2[:, 1:] + dist2 = np.square(euclidean_distances(X, X2)) / self.lengthscale + + dvar = np.exp(-np.square((euclidean_distances(X, X2)) / self.lengthscale)) + dl = -( + 2 * euclidean_distances(X, X2) ** 2 * self.variance * np.exp(-dist2) + ) * self.lengthscale ** (-2) + n = pairwise_distances(T1, T2, "cityblock") / 2 + deps = -n * (1 - self.epsilon) ** (n - 1) + + self.variance.gradient = np.sum(dvar * dL_dK) + self.lengthscale.gradient = np.sum(dl * dL_dK) + self.epsilon.gradient = np.sum(deps * dL_dK) + + +def normalize(data, wrt): + """Normalize data to be in range (0,1), with respect to (wrt) boundaries, + which can be specified. + """ + return (data - np.min(wrt, axis=0)) / ( + np.max(wrt, axis=0) - np.min(wrt, axis=0) + 1e-8 + ) + + +def standardize(data): + """Standardize to be Gaussian N(0,1). Clip final values.""" + data = (data - np.mean(data, axis=0)) / (np.std(data, axis=0) + 1e-8) + return np.clip(data, -2, 2) + + +def UCB(m, m1, x, fixed, kappa=None): + """UCB acquisition function. Interesting points to note: + 1) We concat with the fixed points, because we are not optimizing wrt + these. This is the Reward and Time, which we can't change. We want + to find the best hyperparameters *given* the reward and time. + 2) We use m to get the mean and m1 to get the variance. If we already + have trials running, then m1 contains this information. This reduces + the variance at points currently running, even if we don't have + their label. + Ref: https://jmlr.org/papers/volume15/desautels14a/desautels14a.pdf + + """ + + c1 = 0.2 + c2 = 0.4 + beta_t = c1 + max(0, np.log(c2 * m.X.shape[0])) + kappa = np.sqrt(beta_t) if kappa is None else kappa + + xtest = np.concatenate((fixed.reshape(-1, 1), np.array(x).reshape(-1, 1))).T + + try: + preds = m.predict(xtest) + preds = m.predict(xtest) + mean = preds[0][0][0] + except ValueError: + mean = -9999 + + try: + preds = m1.predict(xtest) + var = preds[1][0][0] + except ValueError: + var = 0 + return mean + kappa * var + + +def optimize_acq(func, m, m1, fixed, num_f): + """Optimize acquisition function.""" + + opts = {"maxiter": 200, "maxfun": 200, "disp": False} + + T = 10 + best_value = -999 + best_theta = m1.X[0, :] + + bounds = [(0, 1) for _ in range(m.X.shape[1] - num_f)] + + for ii in range(T): + x0 = np.random.uniform(0, 1, m.X.shape[1] - num_f) + + res = minimize( + lambda x: -func(m, m1, x, fixed), + x0, + bounds=bounds, + method="L-BFGS-B", + options=opts, + ) + + val = func(m, m1, res.x, fixed) + if val > best_value: + best_value = val + best_theta = res.x + + return np.clip(best_theta, 0, 1) + + +def select_length(Xraw, yraw, bounds, num_f): + """Select the number of datapoints to keep, using cross validation""" + min_len = 200 + + if Xraw.shape[0] < min_len: + return Xraw.shape[0] + else: + length = min_len - 10 + scores = [] + while length + 10 <= Xraw.shape[0]: + length += 10 + + base_vals = np.array(list(bounds.values())).T + X_len = Xraw[-length:, :] + y_len = yraw[-length:] + oldpoints = X_len[:, :num_f] + old_lims = np.concatenate( + (np.max(oldpoints, axis=0), np.min(oldpoints, axis=0)) + ).reshape(2, oldpoints.shape[1]) + limits = np.concatenate((old_lims, base_vals), axis=1) + + X = normalize(X_len, limits) + y = standardize(y_len).reshape(y_len.size, 1) + + kernel = TV_SquaredExp( + input_dim=X.shape[1], variance=1.0, lengthscale=1.0, epsilon=0.1 + ) + m = GPy.models.GPRegression(X, y, kernel) + m.optimize(messages=True) + + scores.append(m.log_likelihood()) + idx = np.argmax(scores) + length = (idx + int((min_len / 10))) * 10 + return length diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/pbt.py b/venv/lib/python3.10/site-packages/ray/tune/schedulers/pbt.py new file mode 100644 index 0000000000000000000000000000000000000000..b58ebfcbba7dd5a35452bb45743713a0c966c1da --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/schedulers/pbt.py @@ -0,0 +1,1182 @@ +import copy +import json +import logging +import math +import os +import random +import shutil +import warnings +from pathlib import Path +from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Tuple, Union + +from ray.air.constants import TRAINING_ITERATION +from ray.train._internal.session import _FutureTrainingResult, _TrainingResult +from ray.tune import Checkpoint +from ray.tune.error import TuneError +from ray.tune.experiment import Trial +from ray.tune.result import DEFAULT_METRIC +from ray.tune.schedulers.trial_scheduler import FIFOScheduler, TrialScheduler +from ray.tune.search import SearchGenerator +from ray.tune.search.sample import Domain, Function +from ray.tune.search.variant_generator import format_vars +from ray.tune.utils.util import SafeFallbackEncoder +from ray.util import PublicAPI +from ray.util.debug import log_once + +if TYPE_CHECKING: + from ray.tune.execution.tune_controller import TuneController + +logger = logging.getLogger(__name__) + + +class _PBTTrialState: + """Internal PBT state tracked per-trial.""" + + def __init__(self, trial: Trial): + self.orig_tag = trial.experiment_tag + self.last_score = None + self.last_checkpoint = None + self.last_perturbation_time = 0 + self.last_train_time = 0 # Used for synchronous mode. + self.last_result = None # Used for synchronous mode. + + def __repr__(self) -> str: + return str( + ( + self.last_score, + self.last_checkpoint, + self.last_train_time, + self.last_perturbation_time, + ) + ) + + +def _explore( + config: Dict, + mutations: Dict, + resample_probability: float, + perturbation_factors: Tuple[float], + custom_explore_fn: Optional[Callable], +) -> Tuple[Dict, Dict]: + """Return a perturbed config and string descriptors of the operations performed + on the original config to produce the new config. + + Args: + config: Original hyperparameter configuration. + mutations: Specification of mutations to perform as documented + in the PopulationBasedTraining scheduler. + resample_probability: Probability of allowing resampling of a + particular variable. + perturbation_factors: Scaling factors to choose between when mutating + a continuous hyperparameter. + custom_explore_fn: Custom explore function applied after built-in + config perturbations. + + Returns: + new_config: New hyperparameter configuration (after random mutations). + operations: Map of hyperparams -> strings describing mutation operations + performed + """ + operations = {} + new_config = copy.deepcopy(config) + for key, distribution in mutations.items(): + if isinstance(distribution, dict): + # Handle nested hyperparameter configs by recursively perturbing them + nested_new_config, nested_ops = _explore( + config[key], + mutations[key], + resample_probability, + perturbation_factors, + custom_explore_fn=None, + ) + new_config.update({key: nested_new_config}) + operations.update({key: nested_ops}) + elif isinstance(distribution, (list, tuple)): + # Case 1: Hyperparameter resample distribution is a list/tuple + if ( + random.random() < resample_probability + or config[key] not in distribution + ): + # Resample a value from the list with `resample_probability` + new_config[key] = random.choice(distribution) + operations[key] = "resample" + else: + # Otherwise, perturb by shifting to the left or right of the list + shift = random.choice([-1, 1]) + old_idx = distribution.index(config[key]) + new_idx = old_idx + shift + new_idx = min(max(new_idx, 0), len(distribution) - 1) + new_config[key] = distribution[new_idx] + operations[key] = ( + f"shift {'left' if shift == -1 else 'right'}" + f"{' (noop)' if old_idx == new_idx else ''}" + ) + elif isinstance(distribution, (Domain, Callable)): + # Case 2: Hyperparameter resample distribution is: + # 1. a function (ex: lambda: np.random.uniform(0, 1)) + # 2. tune search Domain (ex: tune.uniform(0, 1)) + if random.random() < resample_probability: + # Resample a value from the function/domain with `resample_probability` + new_config[key] = ( + distribution.sample(None) + if isinstance(distribution, Domain) + else distribution() + ) + operations[key] = "resample" + else: + # Otherwise, perturb by multiplying the hyperparameter by one + # of the `perturbation_factors` + perturbation_factor = random.choice(perturbation_factors) + new_config[key] = config[key] * perturbation_factor + operations[key] = f"* {perturbation_factor}" + if isinstance(config[key], int): + # If this hyperparameter started out as an integer (ex: `batch_size`), + # convert the new value back + new_config[key] = int(new_config[key]) + else: + raise ValueError( + f"Unsupported hyperparameter distribution type: {type(distribution)}" + ) + if custom_explore_fn: + # The user can perform any additional hyperparameter exploration + # via `custom_explore_fn` + new_config = custom_explore_fn(new_config) + assert new_config is not None, "Custom explore fn failed to return new config" + return new_config, operations + + +def _make_experiment_tag(orig_tag: str, config: Dict, mutations: Dict) -> str: + """Appends perturbed params to the trial name to show in the console.""" + + resolved_vars = {} + for k in mutations.keys(): + resolved_vars[("config", k)] = config[k] + return "{}@perturbed[{}]".format(orig_tag, format_vars(resolved_vars)) + + +def _fill_config( + config: Dict, attr: str, search_space: Union[dict, list, tuple, Callable, Domain] +): + """Add attr to config by sampling from search_space. + + This is a helper used to set initial hyperparameter values if the user doesn't + specify them in the Tuner `param_space`. + """ + if isinstance(search_space, Callable): + config[attr] = search_space() + elif isinstance(search_space, Domain): + config[attr] = search_space.sample(None) + elif isinstance(search_space, (list, tuple)): + config[attr] = random.choice(search_space) + elif isinstance(search_space, dict): + config[attr] = {} + for k, v in search_space.items(): + _fill_config(config[attr], k, v) + + +def _filter_mutated_params_from_config( + config: Dict, hyperparam_mutations: Dict +) -> Dict: + """Filter out hyperparameters from a config so that only parameters specified + within hyperparam_mutations remain. This recursively filters nested configs. + + Example: + >>> config = { + ... "a": {"b": 2, "c": 0, "d": {"e": 0.1}}, + ... "f": {"g": 0.5}, + ... } + >>> hyperparam_mutations = { + ... "a": {"b": [1, 2], "c": [-1, 0]}, + ... } + >>> _filter_mutated_params_from_config(config, hyperparam_mutations) == { + ... "a": {"b": 2, "c": 0} + ... } + True + + Args: + config: The config dict that we want to filter. + hyperparam_mutations: A dict containing a subset of hyperparameters from + config, used to filter the config. + + Returns: + mutated_params: A copy of config containing only params specified in + hyperparam_mutations + """ + mutated_params = {} + for param_name in config: + if param_name not in hyperparam_mutations: + continue + + if isinstance(config[param_name], dict): + nested_params = _filter_mutated_params_from_config( + config[param_name], hyperparam_mutations[param_name] + ) + mutated_params[param_name] = nested_params + else: + mutated_params[param_name] = config[param_name] + return mutated_params + + +@PublicAPI +class PopulationBasedTraining(FIFOScheduler): + """Implements the Population Based Training (PBT) algorithm. + + https://www.deepmind.com/blog/population-based-training-of-neural-networks + + PBT trains a group of models (or agents) in parallel. Periodically, poorly + performing models clone the state of the top performers, and a random + mutation is applied to their hyperparameters in the hopes of + outperforming the current top models. + + Unlike other hyperparameter search algorithms, PBT mutates hyperparameters + during training time. This enables very fast hyperparameter discovery and + also automatically discovers good annealing schedules. + + This Tune PBT implementation considers all trials added as part of the + PBT population. If the number of trials exceeds the cluster capacity, + they will be time-multiplexed as to balance training progress across the + population. To run multiple trials, use `tune.TuneConfig(num_samples=)`. + + In {LOG_DIR}/{MY_EXPERIMENT_NAME}/, all mutations are logged in + `pbt_global.txt` and individual policy perturbations are recorded + in pbt_policy_{i}.txt. Tune logs: [target trial tag, clone trial tag, + target trial iteration, clone trial iteration, old config, new config] + on each perturbation step. + + Args: + time_attr: The training result attr to use for comparing time. + Note that you can pass in something non-temporal such as + `training_iteration` as a measure of progress, the only requirement + is that the attribute should increase monotonically. + metric: The training result objective value attribute. Stopping + procedures will use this attribute. If None but a mode was passed, + the `ray.tune.result.DEFAULT_METRIC` will be used per default. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. + perturbation_interval: Models will be considered for + perturbation at this interval of `time_attr`. Note that + perturbation incurs checkpoint overhead, so you shouldn't set this + to be too frequent. + burn_in_period: Models will not be considered for + perturbation before this interval of `time_attr` has passed. This + guarantees that models are trained for at least a certain amount + of time or timesteps before being perturbed. + hyperparam_mutations: Hyperparams to mutate. The format is + as follows: for each key, either a list, function, + or a tune search space object (tune.loguniform, tune.uniform, + etc.) can be provided. A list specifies an allowed set of + categorical values. A function or tune search space object + specifies the distribution of a continuous parameter. You must + use tune.choice, tune.uniform, tune.loguniform, etc.. Arbitrary + tune.sample_from objects are not supported. + A key can also hold a dict for nested hyperparameters. + You must specify at least one of `hyperparam_mutations` or + `custom_explore_fn`. + Tune will sample the search space provided by + `hyperparam_mutations` for the initial hyperparameter values if the + corresponding hyperparameters are not present in a trial's initial `config`. + quantile_fraction: Parameters are transferred from the top + `quantile_fraction` fraction of trials to the bottom + `quantile_fraction` fraction. Needs to be between 0 and 0.5. + Setting it to 0 essentially implies doing no exploitation at all. + resample_probability: The probability of resampling from the + original distribution when applying `hyperparam_mutations`. If not + resampled, the value will be perturbed by a factor chosen from + `perturbation_factors` if continuous, or changed to an adjacent value + if discrete. + perturbation_factors: Scaling factors to choose between when mutating + a continuous hyperparameter. + custom_explore_fn: You can also specify a custom exploration + function. This function is invoked as `f(config)` after built-in + perturbations from `hyperparam_mutations` are applied, and should + return `config` updated as needed. You must specify at least one of + `hyperparam_mutations` or `custom_explore_fn`. + log_config: Whether to log the ray config of each model to + local_dir at each exploit. Allows config schedule to be + reconstructed. + require_attrs: Whether to require time_attr and metric to appear + in result for every iteration. If True, error will be raised + if these values are not present in trial result. + synch: If False, will use asynchronous implementation of + PBT. Trial perturbations occur every perturbation_interval for each + trial independently. If True, will use synchronous implementation + of PBT. Perturbations will occur only after all trials are + synced at the same time_attr every perturbation_interval. + Defaults to False. See Appendix A.1 here + https://arxiv.org/pdf/1711.09846.pdf. + + .. code-block:: python + + import random + from ray import tune + from ray.tune.schedulers import PopulationBasedTraining + + pbt = PopulationBasedTraining( + time_attr="training_iteration", + metric="episode_reward_mean", + mode="max", + perturbation_interval=10, # every 10 `time_attr` units + # (training_iterations in this case) + hyperparam_mutations={ + # Perturb factor1 by scaling it by 0.8 or 1.2. Resampling + # resets it to a value sampled from the lambda function. + "factor_1": lambda: random.uniform(0.0, 20.0), + # Alternatively, use tune search space primitives. + # The search space for factor_1 is equivalent to factor_2. + "factor_2": tune.uniform(0.0, 20.0), + # Perturb factor3 by changing it to an adjacent value, e.g. + # 10 -> 1 or 10 -> 100. Resampling will choose at random. + "factor_3": [1, 10, 100, 1000, 10000], + # Using tune.choice is NOT equivalent to the above. + # factor_4 is treated as a continuous hyperparameter. + "factor_4": tune.choice([1, 10, 100, 1000, 10000]), + }) + tuner = tune.Tuner( + trainable, + tune_config=tune.TuneConfig( + scheduler=pbt, + num_samples=8, + ), + ) + tuner.fit() + + """ + + def __init__( + self, + time_attr: str = "time_total_s", + metric: Optional[str] = None, + mode: Optional[str] = None, + perturbation_interval: float = 60.0, + burn_in_period: float = 0.0, + hyperparam_mutations: Dict[ + str, Union[dict, list, tuple, Callable, Domain] + ] = None, + quantile_fraction: float = 0.25, + resample_probability: float = 0.25, + perturbation_factors: Tuple[float, float] = (1.2, 0.8), + custom_explore_fn: Optional[Callable] = None, + log_config: bool = True, + require_attrs: bool = True, + synch: bool = False, + ): + hyperparam_mutations = hyperparam_mutations or {} + for value in hyperparam_mutations.values(): + if not isinstance(value, (dict, list, tuple, Domain, Callable)): + raise TypeError( + "`hyperparam_mutation` values must be either " + "a List, Tuple, Dict, a tune search space object, or " + "a callable." + ) + if isinstance(value, Function): + raise ValueError( + "arbitrary tune.sample_from objects are not " + "supported for `hyperparam_mutation` values." + "You must use other built in primitives like" + "tune.uniform, tune.loguniform, etc." + ) + + if not hyperparam_mutations and not custom_explore_fn: + raise TuneError( + "You must specify at least one of `hyperparam_mutations` " + "or `custom_explore_fn` to use PBT." + ) + + if quantile_fraction > 0.5 or quantile_fraction < 0: + raise ValueError( + "You must set `quantile_fraction` to a value between 0 and" + "0.5. Current value: '{}'".format(quantile_fraction) + ) + + if perturbation_interval <= 0: + raise ValueError( + "perturbation_interval must be a positive number greater " + "than 0. Current value: '{}'".format(perturbation_interval) + ) + + if mode: + assert mode in ["min", "max"], "`mode` must be 'min' or 'max'." + + super().__init__() + self._metric = metric + self._mode = mode + self._metric_op = None + if self._mode == "max": + self._metric_op = 1.0 + elif self._mode == "min": + self._metric_op = -1.0 + self._time_attr = time_attr + self._perturbation_interval = perturbation_interval + self._burn_in_period = burn_in_period + self._hyperparam_mutations = hyperparam_mutations + self._quantile_fraction = quantile_fraction + self._resample_probability = resample_probability + self._perturbation_factors = perturbation_factors + self._trial_state = {} + self._custom_explore_fn = custom_explore_fn + self._log_config = log_config + self._require_attrs = require_attrs + self._synch = synch + self._next_perturbation_sync = max( + self._perturbation_interval, + self._burn_in_period, + ) + + # Metrics + self._num_checkpoints = 0 + self._num_perturbations = 0 + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], **spec + ) -> bool: + if self._metric and metric: + return False + if self._mode and mode: + return False + + if metric: + self._metric = metric + if mode: + self._mode = mode + + if self._mode == "max": + self._metric_op = 1.0 + elif self._mode == "min": + self._metric_op = -1.0 + + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + return True + + def on_trial_add(self, tune_controller: "TuneController", trial: Trial): + if tune_controller.search_alg is not None and isinstance( + tune_controller.search_alg, SearchGenerator + ): + raise ValueError( + "Search algorithms cannot be used with {} " + "schedulers. Please remove {}.".format( + self.__class__.__name__, tune_controller.search_alg + ) + ) + + if not self._metric or not self._metric_op: + raise ValueError( + "{} has been instantiated without a valid `metric` ({}) or " + "`mode` ({}) parameter. Either pass these parameters when " + "instantiating the scheduler, or pass them as parameters " + "to `tune.TuneConfig()`".format( + self.__class__.__name__, self._metric, self._mode + ) + ) + + checkpoint_config = trial.run_metadata.checkpoint_manager.checkpoint_config + if ( + checkpoint_config.num_to_keep + and checkpoint_config.num_to_keep <= 2 + and log_once("pbt_num_to_keep") + ): + warnings.warn( + "Using `CheckpointConfig.num_to_keep <= 2` with PBT can lead to " + "restoration problems when checkpoint are deleted too early for " + "other trials to exploit them. If this happens, increase the value " + "of `num_to_keep`." + ) + + self._trial_state[trial] = _PBTTrialState(trial) + + for attr in self._hyperparam_mutations.keys(): + if attr not in trial.config: + if log_once(attr + "-missing"): + logger.debug( + "Cannot find {} in config. Using search " + "space provided by hyperparam_mutations." + ) + # Add attr to trial's config by sampling search space from + # hyperparam_mutations. + _fill_config(trial.config, attr, self._hyperparam_mutations[attr]) + # Make sure this attribute is added to CLI output. + trial.evaluated_params[attr] = trial.config[attr] + + def on_trial_result( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ) -> str: + if self._time_attr not in result: + time_missing_msg = ( + "Cannot find time_attr {} " + "in trial result {}. Make sure that this " + "attribute is returned in the " + "results of your Trainable.".format(self._time_attr, result) + ) + if self._require_attrs: + raise RuntimeError( + time_missing_msg + + "If this error is expected, you can change this to " + "a warning message by " + "setting PBT(require_attrs=False)" + ) + else: + if log_once("pbt-time_attr-error"): + logger.warning(time_missing_msg) + if self._metric not in result: + metric_missing_msg = ( + "Cannot find metric {} in trial result {}. " + "Make sure that this attribute is returned " + "in the " + "results of your Trainable.".format(self._metric, result) + ) + if self._require_attrs: + raise RuntimeError( + metric_missing_msg + "If this error is expected, " + "you can change this to a warning message by " + "setting PBT(require_attrs=False)" + ) + else: + if log_once("pbt-metric-error"): + logger.warning(metric_missing_msg) + + if self._metric not in result or self._time_attr not in result: + return TrialScheduler.CONTINUE + + time = result[self._time_attr] + state = self._trial_state[trial] + + # Continue training if burn-in period has not been reached, yet. + if time < self._burn_in_period: + logger.debug(f"Still in burn-in period: {time} < {self._burn_in_period}") + return TrialScheduler.CONTINUE + + # Continue training if perturbation interval has not been reached, yet. + time_since_perturb = time - state.last_perturbation_time + if time_since_perturb < self._perturbation_interval: + logger.debug( + f"Perturbation interval not reached: " + f"{time_since_perturb} < {self._perturbation_interval}" + ) + return TrialScheduler.CONTINUE # avoid checkpoint overhead + + logger.debug(f"Updating trial state for trial {trial} at time {time}") + self._save_trial_state(state, time, result, trial) + + if not self._synch: + state.last_perturbation_time = time + lower_quantile, upper_quantile = self._quantiles() + decision = TrialScheduler.CONTINUE + for other_trial in tune_controller.get_trials(): + if other_trial.status in [Trial.PENDING, Trial.PAUSED]: + decision = TrialScheduler.PAUSE + break + self._checkpoint_or_exploit( + trial, tune_controller, upper_quantile, lower_quantile + ) + return TrialScheduler.NOOP if trial.status == Trial.PAUSED else decision + else: + # Synchronous mode. + if any( + self._trial_state[t].last_train_time < self._next_perturbation_sync + and t != trial + for t in tune_controller.get_live_trials() + ): + logger.debug( + f"Sync: Other trials are not at perturb time, yet. " + f"Pausing trial {trial} to wait." + ) + else: + # All trials are synced at the same timestep. + logger.debug("Sync: All trials are at perturb time.") + lower_quantile, upper_quantile = self._quantiles() + all_trials = tune_controller.get_trials() + not_in_quantile = [] + for t in all_trials: + if t not in lower_quantile and t not in upper_quantile: + not_in_quantile.append(t) + + logger.debug( + "Trial statistics\n" + f"Upper quantile: {upper_quantile}\n" + f"Lower quantile: {lower_quantile}\n" + f"Not in quantile: {not_in_quantile}" + ) + + # Move upper quantile trials to beginning and lower quantile + # to end. This ensures that checkpointing of strong trials + # occurs before exploiting of weaker ones. + all_trials = upper_quantile + not_in_quantile + lower_quantile + for t in all_trials: + logger.debug(f"Perturbing trial {t}") + self._trial_state[t].last_perturbation_time = time + self._checkpoint_or_exploit( + t, tune_controller, upper_quantile, lower_quantile + ) + + all_train_times = [ + self._trial_state[t].last_train_time + for t in tune_controller.get_trials() + ] + max_last_train_time = max(all_train_times) + self._next_perturbation_sync = max( + self._next_perturbation_sync + self._perturbation_interval, + max_last_train_time, + ) + logger.debug(f"Next perturb at time {self._next_perturbation_sync}") + # In sync mode we should pause all trials once result comes in. + # Once a perturbation step happens for all trials, they should + # still all be paused. + # choose_trial_to_run will then pick the next trial to run out of + # the paused trials. + return ( + TrialScheduler.NOOP + if trial.status == Trial.PAUSED + else TrialScheduler.PAUSE + ) + + def _save_trial_state( + self, state: _PBTTrialState, time: int, result: Dict, trial: Trial + ): + """Saves necessary trial information when result is received. + Args: + state: The state object for the trial. + time: The current timestep of the trial. + result: The trial's result dictionary. + trial: The trial object. + """ + + # This trial has reached its perturbation interval. + # Record new state in the state object. + score = self._metric_op * result[self._metric] + state.last_score = score + state.last_train_time = time + state.last_result = result + + return score + + def _checkpoint_or_exploit( + self, + trial: Trial, + tune_controller: "TuneController", + upper_quantile: List[Trial], + lower_quantile: List[Trial], + ): + """Checkpoint if in upper quantile, exploits if in lower.""" + state = self._trial_state[trial] + if trial in upper_quantile: + # The trial last result is only updated after the scheduler + # callback. So, we override with the current result. + logger.debug(f"Trial {trial} is in upper quantile. Saving checkpoint.") + if trial.status == Trial.PAUSED: + if trial.temporary_state.saving_to and isinstance( + trial.temporary_state.saving_to, _FutureTrainingResult + ): + logger.debug(f"Trial {trial} is still saving.") + state.last_checkpoint = trial.temporary_state.saving_to + else: + # Paused trial will always have an in-memory checkpoint. + logger.debug( + f"Trial {trial} is paused. Use last available " + f"checkpoint {trial.checkpoint}." + ) + state.last_checkpoint = trial.checkpoint + else: + logger.debug(f"Instructing {trial} to save.") + state.last_checkpoint = tune_controller._schedule_trial_save( + trial, result=state.last_result + ) + self._num_checkpoints += 1 + else: + state.last_checkpoint = None # not a top trial + + if trial in lower_quantile: + trial_to_clone = random.choice(upper_quantile) + assert trial is not trial_to_clone + clone_state = self._trial_state[trial_to_clone] + last_checkpoint = clone_state.last_checkpoint + + logger.debug( + f"Trial {trial} is in lower quantile. " + f"Exploiting trial {trial_to_clone}." + ) + + if isinstance(last_checkpoint, _FutureTrainingResult): + training_result = last_checkpoint.resolve() + + if training_result: + clone_state.last_result = training_result.metrics + clone_state.last_checkpoint = training_result.checkpoint + last_checkpoint = clone_state.last_checkpoint + else: + logger.debug( + "PBT-scheduled checkpoint save resolved to None. Trial " + f"{trial_to_clone} didn't save any checkpoint before " + f"and can't be exploited." + ) + last_checkpoint = None + + if not last_checkpoint: + logger.info( + f"[pbt]: no checkpoint for trial {trial_to_clone}." + f" Skip exploit for Trial {trial}" + ) + return + self._exploit(tune_controller, trial, trial_to_clone) + + def _log_config_on_step( + self, + trial_state: _PBTTrialState, + new_state: _PBTTrialState, + trial: Trial, + trial_to_clone: Trial, + new_config: Dict, + ): + """Logs transition during exploit/exploit step. + + For each step, logs: [target trial tag, clone trial tag, target trial + iteration, clone trial iteration, old config, new config]. + """ + trial_name, trial_to_clone_name = (trial_state.orig_tag, new_state.orig_tag) + trial_id = trial.trial_id + trial_to_clone_id = trial_to_clone.trial_id + trial_path = os.path.join( + trial.local_experiment_path, "pbt_policy_" + trial_id + ".txt" + ) + trial_to_clone_path = os.path.join( + trial_to_clone.local_dir, "pbt_policy_" + trial_to_clone_id + ".txt" + ) + policy = [ + trial_name, + trial_to_clone_name, + trial.last_result.get(TRAINING_ITERATION, 0), + trial_to_clone.last_result.get(TRAINING_ITERATION, 0), + trial_to_clone.config, + new_config, + ] + # Log to global file. + with open( + os.path.join(trial.local_experiment_path, "pbt_global.txt"), "a+" + ) as f: + print(json.dumps(policy, cls=SafeFallbackEncoder), file=f) + # Overwrite state in target trial from trial_to_clone. + if os.path.exists(trial_to_clone_path): + shutil.copyfile(trial_to_clone_path, trial_path) + # Log new exploit in target trial log. + with open(trial_path, "a+") as f: + f.write(json.dumps(policy, cls=SafeFallbackEncoder) + "\n") + + def _get_new_config(self, trial: Trial, trial_to_clone: Trial) -> Tuple[Dict, Dict]: + """Gets new config for trial by exploring trial_to_clone's config. + + Args: + trial: The current trial that decided to exploit trial_to_clone. + trial_to_clone: The top-performing trial with a hyperparameter config + that the current trial will explore by perturbing. + + Returns: + new_config: New hyperparameter configuration (after random mutations). + operations: Map of hyperparams -> strings describing mutation operations + performed + """ + return _explore( + trial_to_clone.config, + self._hyperparam_mutations, + self._resample_probability, + self._perturbation_factors, + self._custom_explore_fn, + ) + + def _summarize_hyperparam_changes( + self, + old_params: Dict, + new_params: Dict, + operations: Optional[Dict] = None, + prefix: str = "", + ) -> str: + """Generates a summary of hyperparameter changes from a PBT "explore" step. + + Example: + Given the following hyperparam_mutations: + + hyperparam_mutations = { + "a": tune.uniform(0, 1), + "b": list(range(5)), + "c": { + "d": tune.uniform(2, 3), + "e": {"f": [-1, 0, 1]}, + }, + } + + This is an example summary output of the operations performed on old_params + to get new_params: + + a : 0.5 --- (* 0.8) --> 0.4 + b : 2 --- (resample) --> 4 + c : + d : 2.5 --- (* 1.2) --> 3.0 + e : + f : 0 --- (shift right) --> 1 + + The summary shows the old and new hyperparameter values, with the operation + used to perturb labeled in between. + If the operation for a certain hyperparameter is not provided, then the summary + will just contain arrows without a label. (ex: a : 0.5 -----> 0.4) + + Args: + old_params: Old values of hyperparameters that are perturbed to generate + the new config + new_params: The newly generated hyperparameter config from PBT exploration + operations: Map of hyperparams -> string descriptors the operations + performed to generate the values in `new_params` + prefix: Helper argument to format nested dict hyperparam configs + + Returns: + summary_str: The hyperparameter change summary to print/log. + """ + summary_str = "" + if not old_params: + return summary_str + for param_name in old_params: + old_val = old_params[param_name] + assert param_name in new_params, ( + "`old_params` and `new_params` " + f"must both contain the key: '{param_name}'\n" + f"old_params.keys() = {old_params.keys()}\n" + f"new_params.keys() = {new_params.keys()}" + ) + new_val = new_params[param_name] + summary_str += f"{prefix}{param_name} : " + if isinstance(old_val, Dict): + # Handle nested hyperparameters by recursively summarizing + summary_str += "\n" + nested_operations = operations.get(param_name, {}) + summary_str += self._summarize_hyperparam_changes( + old_val, + new_val, + operations=nested_operations, + prefix=prefix + " " * 4, + ) + else: + op = operations.get(param_name, None) + if not op: + arrow = "----->" + else: + arrow = f"--- ({op}) -->" + summary_str += f"{old_val} {arrow} {new_val}\n" + return summary_str + + def _exploit( + self, + tune_controller: "TuneController", + trial: Trial, + trial_to_clone: Trial, + ): + """Transfers perturbed state from trial_to_clone -> trial. + + If specified, also logs the updated hyperparam state. + """ + trial_state = self._trial_state[trial] + new_state = self._trial_state[trial_to_clone] + class_name = self.__class__.__name__ + logger.info( + f"\n\n[{class_name}] [Exploit] Cloning trial " + "{} (score = {:4f}) into trial {} (score = {:4f})\n".format( + trial_to_clone.trial_id, + new_state.last_score, + trial.trial_id, + trial_state.last_score, + ) + ) + + new_config, operations = self._get_new_config(trial, trial_to_clone) + + # Only log mutated hyperparameters and not entire config. + old_params = _filter_mutated_params_from_config( + trial_to_clone.config, self._hyperparam_mutations + ) + new_params = _filter_mutated_params_from_config( + new_config, self._hyperparam_mutations + ) + explore_info_str = ( + f"\n\n[{class_name}] [Explore] Perturbed the hyperparameter config of trial" + f"{trial.trial_id}:\n" + ) + explore_info_str += ( + self._summarize_hyperparam_changes(old_params, new_params, operations) + or "No hyperparameters mutated." + ) + logger.info(explore_info_str) + + if self._log_config: + self._log_config_on_step( + trial_state, new_state, trial, trial_to_clone, new_config + ) + + new_tag = _make_experiment_tag( + trial_state.orig_tag, new_config, self._hyperparam_mutations + ) + if trial.status == Trial.PAUSED: + # If trial is paused we update it with a new checkpoint. + # When the trial is started again, the new checkpoint is used. + if not self._synch: + raise TuneError( + "Trials should be paused here only if in " + "synchronous mode. If you encounter this error" + " please raise an issue on Ray Github." + ) + else: + tune_controller.pause_trial(trial, should_checkpoint=False) + trial.set_experiment_tag(new_tag) + # Clone hyperparameters from the `trial_to_clone` + trial.set_config(new_config) + + # Resume training from a shallow copy of `trial_to_clone`'s latest + # checkpoint + checkpoint_to_exploit: Checkpoint = copy.copy(new_state.last_checkpoint) + + trial.run_metadata.checkpoint_manager._latest_checkpoint_result = ( + _TrainingResult( + checkpoint=checkpoint_to_exploit, metrics=new_state.last_result + ) + ) + + self._num_perturbations += 1 + # Transfer over the last perturbation time as well + trial_state.last_perturbation_time = new_state.last_perturbation_time + trial_state.last_train_time = new_state.last_train_time + + def _quantiles(self) -> Tuple[List[Trial], List[Trial]]: + """Returns trials in the lower and upper `quantile` of the population. + + If there is not enough data to compute this, returns empty lists. + """ + trials = [] + for trial, state in self._trial_state.items(): + logger.debug("Trial {}, state {}".format(trial, state)) + if trial.is_finished(): + logger.debug("Trial {} is finished".format(trial)) + if state.last_score is not None and not trial.is_finished(): + trials.append(trial) + trials.sort(key=lambda t: self._trial_state[t].last_score) + + if len(trials) <= 1: + return [], [] + else: + num_trials_in_quantile = int( + math.ceil(len(trials) * self._quantile_fraction) + ) + if num_trials_in_quantile > len(trials) / 2: + num_trials_in_quantile = int(math.floor(len(trials) / 2)) + return (trials[:num_trials_in_quantile], trials[-num_trials_in_quantile:]) + + def choose_trial_to_run(self, tune_controller: "TuneController") -> Optional[Trial]: + """Ensures all trials get fair share of time (as defined by time_attr). + + This enables the PBT scheduler to support a greater number of + concurrent trials than can fit in the cluster at any given time. + """ + candidates = [] + for trial in tune_controller.get_trials(): + if trial.status in [ + Trial.PENDING, + Trial.PAUSED, + ]: + if not self._synch: + candidates.append(trial) + elif ( + self._trial_state[trial].last_train_time + < self._next_perturbation_sync + ): + candidates.append(trial) + candidates.sort(key=lambda trial: self._trial_state[trial].last_train_time) + return candidates[0] if candidates else None + + # Unit test only. TODO(xwjiang): Remove test-specific APIs. + def reset_stats(self): + self._num_perturbations = 0 + self._num_checkpoints = 0 + + # Unit test only. TODO(xwjiang): Remove test-specific APIs. + def last_scores(self, trials: List[Trial]) -> List[float]: + scores = [] + for trial in trials: + state = self._trial_state[trial] + if state.last_score is not None and not trial.is_finished(): + scores.append(state.last_score) + return scores + + def debug_string(self) -> str: + return "PopulationBasedTraining: {} checkpoints, {} perturbs".format( + self._num_checkpoints, self._num_perturbations + ) + + +@PublicAPI +class PopulationBasedTrainingReplay(FIFOScheduler): + """Replays a Population Based Training run. + + Population Based Training does not return a single hyperparameter + configuration, but rather a schedule of configurations. For instance, + PBT might discover that a larger learning rate leads to good results + in the first training iterations, but that a smaller learning rate + is preferable later. + + This scheduler enables replaying these parameter schedules from + a finished PBT run. This requires that population based training has + been run with ``log_config=True``, which is the default setting. + + The scheduler will only accept and train a single trial. It will + start with the initial config of the existing trial and update the + config according to the schedule. + + Args: + policy_file: The PBT policy file. Usually this is + stored in ``~/ray_results/experiment_name/pbt_policy_xxx.txt`` + where ``xxx`` is the trial ID. + + Example: + + .. code-block:: python + + # Replaying a result from ray.tune.examples.pbt_convnet_example + from ray import tune + + from ray.tune.examples.pbt_convnet_example import PytorchTrainable + from ray.tune.schedulers import PopulationBasedTrainingReplay + + replay = PopulationBasedTrainingReplay( + "~/ray_results/pbt_test/pbt_policy_XXXXX_00001.txt") + + tuner = tune.Tuner( + PytorchTrainable, + run_config=tune.RunConfig( + stop={"training_iteration": 100} + ), + tune_config=tune.TuneConfig( + scheduler=replay, + ), + ) + tuner.fit() + + + """ + + def __init__(self, policy_file: str): + policy_file = Path(policy_file).expanduser() + if not policy_file.exists(): + raise ValueError("Policy file not found: {}".format(policy_file.as_posix())) + + self.policy_file = policy_file.as_posix() + + # Find and read pbt policy file, potentially raise error + initial_config, self._policy = self._load_policy(self.policy_file) + + self.experiment_tag = "replay_{}".format(os.path.basename(self.policy_file)) + self.config = initial_config + self.current_config = self.config + + self._trial = None + self._current_step = 0 + self._num_perturbations = 0 + + self._policy_iter = iter(self._policy) + self._next_policy = next(self._policy_iter, None) + + def _load_policy(self, policy_file: str) -> Tuple[Dict, List[Tuple[int, Dict]]]: + raw_policy = [] + with open(policy_file, "rt") as fp: + for row in fp.readlines(): + try: + parsed_row = json.loads(row) + except json.JSONDecodeError: + raise ValueError( + "Could not read PBT policy file: {}.".format(policy_file) + ) from None + raw_policy.append(tuple(parsed_row)) + + # Loop through policy from end to start to obtain changepoints + policy = [] + last_new_tag = None + last_old_conf = None + for old_tag, new_tag, old_step, new_step, old_conf, new_conf in reversed( + raw_policy + ): + if last_new_tag and old_tag != last_new_tag: + # Tag chain ended. This means that previous changes were + # overwritten by the last change and should be ignored. + break + last_new_tag = new_tag + last_old_conf = old_conf + + policy.append((new_step, new_conf)) + + return last_old_conf, list(reversed(policy)) + + def on_trial_add(self, tune_controller: "TuneController", trial: Trial): + if self._trial: + raise ValueError( + "More than one trial added to PBT replay run. This " + "means the same schedule will be trained multiple " + "times. Do you want to set `n_samples=1`?" + ) + self._trial = trial + if self._trial.config and self._policy: + logger.warning( + "Trial was initialized with a config, which was overwritten. " + "Did you start the PBT replay with a `config` parameter?" + ) + elif self._trial.config and not self._policy: + # Only train with initial policy + self.config = self._trial.config + elif not self._trial.config and not self._policy: + raise ValueError( + "No replay policy found and trial initialized without a " + "valid config. Either pass a `config` argument to `tune.Tuner()`" + "or consider not using PBT replay for this run." + ) + self._trial.set_config(self.config) + + def on_trial_result( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ) -> str: + if TRAINING_ITERATION not in result: + # No time reported + return TrialScheduler.CONTINUE + + if not self._next_policy: + # No more changes in the config + return TrialScheduler.CONTINUE + + step = result[TRAINING_ITERATION] + self._current_step = step + + change_at, new_config = self._next_policy + + if step < change_at: + # Don't change the policy just yet + return TrialScheduler.CONTINUE + + logger.info( + "Population Based Training replay is now at step {}. " + "Configuration will be changed to {}.".format(step, new_config) + ) + + result = tune_controller._schedule_trial_save(trial, result=result) + training_result = result.resolve() + trial.run_metadata.checkpoint_manager._latest_checkpoint_result = ( + training_result + ) + + new_tag = _make_experiment_tag(self.experiment_tag, new_config, new_config) + + tune_controller.pause_trial(trial, should_checkpoint=False) + trial.set_experiment_tag(new_tag) + trial.set_config(new_config) + + self.current_config = new_config + self._num_perturbations += 1 + self._next_policy = next(self._policy_iter, None) + + return TrialScheduler.NOOP + + def debug_string(self) -> str: + return "PopulationBasedTraining replay: Step {}, perturb {}".format( + self._current_step, self._num_perturbations + ) diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/resource_changing_scheduler.py b/venv/lib/python3.10/site-packages/ray/tune/schedulers/resource_changing_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..24d437cf892f9eded05ac2b6ec511900e4e3b911 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/schedulers/resource_changing_scheduler.py @@ -0,0 +1,871 @@ +import logging +import pickle +import warnings +from copy import deepcopy +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Set, Tuple, Union + +import numpy as np + +from ray.air.execution.resources.request import _sum_bundles +from ray.tune.execution.placement_groups import PlacementGroupFactory +from ray.tune.experiment import Trial +from ray.tune.schedulers.trial_scheduler import FIFOScheduler, TrialScheduler +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.tune.execution.tune_controller import TuneController + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="beta") +class DistributeResources: + """This class creates a basic uniform resource allocation function. + + The function naively balances free resources (CPUs and GPUs) between + trials, giving them all equal priority, ensuring that all resources + are always being used. The free resources will be placed in new bundles. + The function assumes that all bundles are equal (there is no "head" + bundle). + + If for some reason a trial ends up with + more resources than there are free ones, it will adjust downwards. + It will also ensure that trial as at least as many resources as + it started with (``base_trial_resource``). + + The function returns a new ``PlacementGroupFactory`` with updated + resource requirements, or None. If the returned + ``PlacementGroupFactory`` is equal by value to the one the + trial has currently, the scheduler will skip the update process + internally (same with None). + + If you wish to implement your own resource distribution logic, + you can do so by extending this class, as it provides several + generic methods. You can also implement a function instead. + + Args: + add_bundles: If True, create new bundles from free resources. + Otherwise, spread them among base_trial_resource bundles. + increase_by: A dict with key-value + pairs representing an atomic unit of resources (name-amount) + the trial will be increased by. If not set, the trial will + increase by 1 CPU/GPU. + increase_by_times: If set to >=1 and ``increase_by`` is set, + the trial will increase by maximum of + ``increase_by_times * increase_by`` resources. If set to <1, + no upper limit is set. Ignored if ``increase_by`` is not set. + reserve_resources: A dict of + resource_name-amount pairs representing the resources + that will not be allocated to resized trials. + """ + + def __init__( + self, + add_bundles: bool = False, + increase_by: Optional[Dict[str, float]] = None, + increase_by_times: int = -1, + reserve_resources: Optional[Dict[str, float]] = None, + ): + self.add_bundles = add_bundles + self.increase_by = increase_by or {} + self.increase_by_times = increase_by_times + self.reserve_resources = reserve_resources or {} + + def _validate( + self, base_trial_resource: PlacementGroupFactory, result: Dict[str, Any] + ) -> bool: + """Return False if we should keep the current resources outright.""" + if not isinstance(base_trial_resource, PlacementGroupFactory): + raise ValueError( + f"{self.__class__.__name__} only supports PlacementGroupFactories." + ) + + if not self.add_bundles and len(base_trial_resource.bundles) > 1: + raise ValueError( + "If `add_bundles` is False, the number of bundles in " + "`resources_per_trial` must be 1 " + f"(got {len(base_trial_resource.bundles)})." + ) + + # Don't bother if this is just the first iteration + if result["training_iteration"] < 1: + return False + return True + + def _get_total_available_resources( + self, tune_controller: "TuneController" + ) -> Tuple[float, float]: + """Get the number of CPUs and GPUs avaialble in total (not just free)""" + total_available_cpus = ( + tune_controller._resource_updater.get_num_cpus() + - self.reserve_resources.get("CPU", 0) + ) + total_available_gpus = ( + tune_controller._resource_updater.get_num_gpus() + - self.reserve_resources.get("GPU", 0) + ) + return total_available_cpus, total_available_gpus + + def _get_used_cpus_and_gpus(self, t: Trial) -> Tuple[float, float]: + """Check how many CPUs and GPUs a trial is using currently""" + return ( + t.placement_group_factory.required_resources.get("CPU", 0), + t.placement_group_factory.required_resources.get("GPU", 0), + ) + + def _get_resources_from_bundles( + self, bundles: List[Dict[str, float]] + ) -> Dict[str, float]: + """Get total sums of resources in bundles""" + if not bundles: + return {"CPU": 0, "GPU": 0} + return _sum_bundles(bundles) + + def _is_bundle_empty(self, bundle: Dict[str, float]) -> bool: + return not (bundle.get("CPU", 0) or bundle.get("GPU", 0)) + + def _add_two_bundles( + self, + bundles_a: List[Dict[str, float]], + bundles_b: List[Dict[str, float]], + increase_by: Dict[str, float], + limit_to_increase_by_times: bool, + max_increase_by_times: int = -1, + ): + """Add two bundles together. + + If ``limit_to_increase_by_times`` is True, ``self.increase_by_times`` > 0 + and ``max_increase_by_times`` > 0, ensure that the resulting number of + bundles is not above ``min(max_increase_by_times, self.increase_by_times)``. + + If ``limit_to_increase_by_times`` is True and ``self.increase_by_times`` > 0, + ensure that the resulting number of bundles is not above + `self.increase_by_times``. + """ + if limit_to_increase_by_times: + if max_increase_by_times > 0 and self.increase_by_times > 0: + max_increase_by_times = min( + max_increase_by_times, self.increase_by_times + ) + elif self.increase_by_times > 0: + max_increase_by_times = self.increase_by_times + + if self.add_bundles: + bundles = [b for b in bundles_a if not self._is_bundle_empty(b)] + [ + b for b in bundles_b if not self._is_bundle_empty(b) + ] + if max_increase_by_times > 0: + bundles = bundles[:max_increase_by_times] + else: + bundles_a = bundles_a or [{}] + bundles_b = bundles_b or [{}] + bundles = [ + { + "CPU": bundles_a[0].get("CPU", 0) + bundles_b[0].get("CPU", 0), + "GPU": bundles_a[0].get("GPU", 0) + bundles_b[0].get("GPU", 0), + } + ] + if max_increase_by_times > 0: + bundles[0]["CPU"] = min( + bundles[0]["CPU"], + increase_by.get("CPU", 0) * max_increase_by_times, + ) + bundles[0]["GPU"] = min( + bundles[0]["GPU"], + increase_by.get("GPU", 0) * max_increase_by_times, + ) + + return bundles + + def _get_multiplier( + self, + increase_by: Dict[str, float], + cpus: float = 0, + gpus: float = 0, + max_multiplier: int = -1, + ) -> int: + """Get how many times ``increase_by`` bundles + occur in ``cpus`` and ``gpus``.""" + if increase_by.get("CPU", 0) and increase_by.get("GPU", 0): + multiplier = min( + cpus // increase_by.get("CPU", 0), + gpus // increase_by.get("GPU", 0), + ) + elif increase_by.get("GPU", 0): + multiplier = gpus // increase_by.get("GPU", 0) + else: + multiplier = cpus // increase_by.get("CPU", 0) + + if max_multiplier > 0 and multiplier > 0: + multiplier = min(max_multiplier, multiplier) + return int(multiplier) + + def _remove_bundles( + self, + bundles: List[Dict[str, float]], + increase_by: Dict[str, float], + multiplier: int, + ) -> List[Dict[str, float]]: + """Remove ``multiplier`` ``increase_by`` bundles from ``bundles``.""" + multiplier = -abs(multiplier) + if self.add_bundles: + bundles = bundles[:multiplier] + else: + bundles = deepcopy(bundles) + bundles[0]["CPU"] += increase_by.get("CPU", 0) * multiplier + bundles[0]["GPU"] += increase_by.get("GPU", 0) * multiplier + bundles[0]["CPU"] = max(bundles[0]["CPU"], 0) + bundles[0]["GPU"] = max(bundles[0]["GPU"], 0) + return bundles + + def _create_new_bundles( + self, + increase_by: Dict[str, float], + multiplier: int, + ) -> List[Dict[str, float]]: + """Create a list of new bundles containing ``increase_by`` * ``multiplier``.""" + multiplier = abs(multiplier) + + if self.add_bundles: + bundles = [increase_by] * int(multiplier) + else: + bundles = [{}] + bundles[0]["CPU"] = increase_by.get("CPU", 0) * multiplier + bundles[0]["GPU"] = increase_by.get("GPU", 0) * multiplier + + return bundles + + def _modify_bundles_with_free_resources( + self, + bundles: List[Dict[str, float]], + increase_by: Dict[str, float], + free_cpus: float, + free_gpus: float, + *, + max_multiplier: int = -1, + max_increase_by_times: int = -1, + ): + """Given free resources, increase/decrease the number of bundles in + ``bundles``.""" + multiplier = self._get_multiplier( + increase_by, free_cpus, free_gpus, max_multiplier + ) + if multiplier < 0: + bundles = self._remove_bundles(bundles, increase_by, multiplier) + elif multiplier > 0: + bundles_to_add = self._create_new_bundles(increase_by, multiplier) + bundles = self._add_two_bundles( + bundles, bundles_to_add, increase_by, True, max_increase_by_times + ) + return bundles + + def _get_added_bundles( + self, bundles: List[Dict[str, float]], base_bundles: List[Dict[str, float]] + ) -> List[Dict[str, float]]: + """Return the difference between bundles and base_bundles""" + if self.add_bundles: + added_bundles = bundles[len(base_bundles) :] + else: + if not bundles: + bundles = [{"CPU": 0, "GPU": 0}] + if not base_bundles: + base_bundles = [{"CPU": 0, "GPU": 0}] + added_bundles = [ + { + "CPU": bundles[0].get("CPU", 0) - base_bundles[0].get("CPU", 0), + "GPU": bundles[0].get("GPU", 0) - base_bundles[0].get("GPU", 0), + } + ] + return added_bundles + + def _are_bundles_below_limit( + self, + bundles: List[Dict[str, float]], + base_bundles: Optional[List[Dict[str, float]]] = None, + max_added_cpus: Optional[float] = None, + max_added_gpus: Optional[float] = None, + ): + if not max_added_cpus: + if self.increase_by_times > 0: + max_added_cpus = self.increase_by.get("CPU", 0) * self.increase_by_times + else: + max_added_cpus = np.inf + if not max_added_gpus: + if self.increase_by_times > 0: + max_added_gpus = self.increase_by.get("GPU", 0) * self.increase_by_times + else: + max_added_gpus = np.inf + added_resources = self._get_resources_from_bundles( + self._get_added_bundles(bundles, base_bundles) if base_bundles else bundles + ) + ret = ( + added_resources.get("CPU", -np.inf) < max_added_cpus + or added_resources.get("GPU", -np.inf) < max_added_gpus + ) + return ret + + def _get_new_added_bundles( + self, + trial: Trial, + all_trials: List[Trial], + base_bundles: List[Dict[str, float]], + increase_by: Dict[str, float], + total_available_cpus: float, + total_available_gpus: float, + used_cpus: float, + used_gpus: float, + ) -> List[Dict[str, float]]: + """Returns updated added bundles.""" + upper_limit_all_trials_bundles = [list() for _ in range(len(all_trials))] + + free_cpus = total_available_cpus - used_cpus + free_gpus = total_available_gpus - used_gpus + + base_resources = self._get_resources_from_bundles(base_bundles) + upper_limit_cpus_to_distribute = total_available_cpus - ( + base_resources.get("CPU", 0) * len(all_trials) + ) + upper_limit_gpus_to_distribute = total_available_gpus - ( + base_resources.get("GPU", 0) * len(all_trials) + ) + max_increase_by_times = 0 + + # First, calculate upper limits for uniform allocation + # This is done by simulating a clean slate scenario + # The loop runs until all resources are allocated or + # all trials are at their resource limits + i = 0 + trials_at_limit = set() + while ( + len(trials_at_limit) < len(all_trials) + # we have previously asserted that at least one resource has to be + # bigger than 0 + and upper_limit_cpus_to_distribute >= increase_by.get("CPU", 0) + and upper_limit_gpus_to_distribute >= increase_by.get("GPU", 0) + ): + idx = i % len(upper_limit_all_trials_bundles) + old_bundles = deepcopy(upper_limit_all_trials_bundles[idx]) + upper_limit_all_trials_bundles[ + idx + ] = self._modify_bundles_with_free_resources( + upper_limit_all_trials_bundles[idx], + increase_by, + upper_limit_cpus_to_distribute, + upper_limit_gpus_to_distribute, + max_multiplier=1, + ) + added_resources = self._get_resources_from_bundles( + self._get_added_bundles( + upper_limit_all_trials_bundles[idx], old_bundles + ) + ) + if not added_resources.get("CPU", 0) and not added_resources.get("GPU", 0): + trials_at_limit.add(idx) + elif idx == 0: + max_increase_by_times += 1 + upper_limit_cpus_to_distribute -= added_resources.get("CPU", 0) + upper_limit_gpus_to_distribute -= added_resources.get("GPU", 0) + i += 1 + + # Add new resourcs, but only up to calculated upper limits + # (max_increase_by_times) + return self._modify_bundles_with_free_resources( + self._get_added_bundles( + trial.placement_group_factory.bundles, base_bundles + ), + increase_by, + free_cpus, + free_gpus, + max_increase_by_times=max_increase_by_times, + ) + + def __call__( + self, + tune_controller: "TuneController", + trial: Trial, + result: Dict[str, Any], + scheduler: "ResourceChangingScheduler", + ) -> Optional[PlacementGroupFactory]: + """Run resource allocation logic. + + Returns a new ``PlacementGroupFactory`` with updated + resource requirements, or None. If the returned + ``PlacementGroupFactory`` is equal by value to the one the + trial has currently, the scheduler will skip the update process + internally (same with None). + + Args: + tune_controller: Trial runner for this Tune run. + Can be used to obtain information about other trials. + trial: The trial to allocate new resources to. + result: The latest results of trial. + scheduler: The scheduler calling + the function. + """ + # Get base trial resources as defined in + # ``tune.run(resources_per_trial)`` + base_trial_resource = scheduler.base_trial_resources + + if not self._validate(base_trial_resource=base_trial_resource, result=result): + return None + + # default values if resources_per_trial is unspecified + if base_trial_resource is None: + base_trial_resource = PlacementGroupFactory([{"CPU": 1, "GPU": 0}]) + + if self.increase_by: + increase_by = self.increase_by + assert not self._is_bundle_empty(increase_by) + assert increase_by.get("CPU", 0) >= 0 and increase_by.get("GPU", 0) >= 0 + elif self.add_bundles: + increase_by = base_trial_resource.bundles[-1] + elif base_trial_resource.bundles[0].get("GPU", 0): + increase_by = {"GPU": 1} + else: + increase_by = {"CPU": 1} + + base_bundles = deepcopy(base_trial_resource.bundles) + + ( + total_available_cpus, + total_available_gpus, + ) = self._get_total_available_resources(tune_controller=tune_controller) + + all_trials = tune_controller.get_live_trials() + + used_cpus_and_gpus = [self._get_used_cpus_and_gpus(t) for t in all_trials] + used_cpus, used_gpus = zip(*used_cpus_and_gpus) + used_cpus = sum(used_cpus) + used_gpus = sum(used_gpus) + + added_bundles = self._get_new_added_bundles( + trial, + all_trials, + base_bundles, + increase_by, + total_available_cpus, + total_available_gpus, + used_cpus, + used_gpus, + ) + + new_bundles = self._add_two_bundles( + base_bundles, added_bundles, increase_by, False + ) + + pgf = PlacementGroupFactory( + new_bundles, + strategy=base_trial_resource.strategy, + *base_trial_resource._args, + **base_trial_resource._kwargs, + ) + pgf._head_bundle_is_empty = base_trial_resource._head_bundle_is_empty + return pgf + + +@PublicAPI(stability="beta") +class DistributeResourcesToTopJob(DistributeResources): + """This class creates a "TopJob" resource allocation function. + + The function will assign all of the free resources to the best + performing trial (as defined by ``metric`` and ``mode``). The + previous best trials will not have their resources deallocated, + unless in the case outlined below. + + If for some reason a trial ends up with + more resources than there are free ones, it will adjust downwards. + It will also ensure that trial as at least as many resources as + it started with (``base_trial_resource``). + + The function returns a new ``PlacementGroupFactory`` with updated + resource requirements, or None. If the returned + ``PlacementGroupFactory`` is equal by value to the one the + trial has currently, the scheduler will skip the update process + internally (same with None). + + Args: + add_bundles: If True, create new bundles from free resources. + Otherwise, spread them among base_trial_resource bundles. + increase_by: A dict with key-value + pairs representing an atomic unit of resources (name-amount) + the trial will be increased by. If not set, the trial will + increase by 1 CPU/GPU. + increase_by_times: If set to >=1 and ``increase_by`` is set, + the trial will increase by maximum of + ``increase_by_times * increase_by`` resources. If set to <1, + no upper limit is set. Ignored if ``increase_by`` is not set. + reserve_resources: A dict of + resource_name-amount pairs representing the resources + that will not be allocated to resized trials. + is that the attribute should increase monotonically. + metric: The training result objective value attribute. Stopping + procedures will use this attribute. If None, will use the metric + of the scheduler. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. If None, will use the metric + of the scheduler. + + """ + + def __init__( + self, + add_bundles: bool = False, + increase_by: Optional[Dict[str, float]] = None, + increase_by_times: int = -1, + reserve_resources: Optional[Dict[str, float]] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + ): + super().__init__(add_bundles, increase_by, increase_by_times, reserve_resources) + self.metric = metric + self.mode = mode + + @property + def _metric_op(self) -> float: + if self.mode not in ("min", "max"): + raise ValueError("The mode parameter can only be either min or max.") + if self.mode == "max": + return 1.0 + return -1.0 + + def _get_new_added_bundles( + self, + trial: Trial, + all_trials: List[Trial], + base_bundles: List[Dict[str, float]], + increase_by: Dict[str, float], + total_available_cpus: float, + total_available_gpus: float, + used_cpus: float, + used_gpus: float, + ) -> List[Dict[str, float]]: + if self.metric is None: + raise ValueError( + "The metric parameter cannot be None. The parameter can be set in " + "either `DistributeResourcesToTopJob`, the base scheduler or in " + "`tune.TuneConfig()` (highest to lowest priority)." + ) + + free_cpus = total_available_cpus - used_cpus + free_gpus = total_available_gpus - used_gpus + + sorted_trials = sorted( + all_trials, + key=lambda t: -self._metric_op * t.last_result.get(self.metric, np.inf), + ) + + added_bundles = self._get_added_bundles( + trial.placement_group_factory.bundles, base_bundles + ) + + best_trial = next( + ( + t + for t in sorted_trials + if self._are_bundles_below_limit( + t.placement_group_factory.bundles, base_bundles + ) + ), + sorted_trials[0], + ) + + if ( + trial.trial_id != best_trial.trial_id + # Only reduce resources here + and self._get_multiplier(increase_by, free_cpus, free_gpus) >= 0 + ): + return added_bundles + + return self._modify_bundles_with_free_resources( + added_bundles, + increase_by, + free_cpus, + free_gpus, + ) + + +_DistributeResourcesDefault = DistributeResources(add_bundles=False) +_DistributeResourcesDistributedDefault = DistributeResources(add_bundles=True) + + +@PublicAPI(stability="beta") +class ResourceChangingScheduler(TrialScheduler): + """A utility scheduler to dynamically change resources of live trials. + + .. versionadded:: 1.5.0 + + .. note:: + Experimental. API may change in future releases. + + The ResourceChangingScheduler works by wrapping around any other + scheduler and adjusting the resource requirements of live trials + in response to the decisions of the wrapped scheduler + through a user-specified ``resources_allocation_function``. + + An example of such a function can be found in + :doc:`/tune/examples/includes/xgboost_dynamic_resources_example`. + + If the functional API is used, the current trial resources can be obtained + by calling `tune.get_trial_resources()` inside the training function. + The function should be able to + :ref:`load and save checkpoints ` + (the latter preferably every iteration). + + If the Trainable (class) API is used, you can obtain the current trial + resources through the ``Trainable.trial_resources`` property. + + Cannot be used if ``reuse_actors`` is True in ``tune.TuneConfig()``. A ValueError + will be raised in that case. + + Args: + base_scheduler: The scheduler to provide decisions + about trials. If None, a default FIFOScheduler will be used. + resources_allocation_function: The callable used to change + live trial resource requiements during tuning. This callable + will be called on each trial as it finishes one step of training. + The callable must take four arguments: ``TrialRunner``, current + ``Trial``, current result :class:`dict` and the + ``ResourceChangingScheduler`` calling it. The callable must + return a ``PlacementGroupFactory`` + or None (signifying no need for an update). If + ``resources_allocation_function`` is None, no resource + requirements will be changed at any time. + By default, :class:`DistributeResources` will be used, + distributing available CPUs and GPUs over all running trials + in a robust way, without any prioritization. + + Warning: + If the ``resources_allocation_function`` sets trial resource + requirements to values bigger than possible, the trial will + not run. Ensure that your callable accounts for that possibility + by setting upper limits. Consult :class:`DistributeResources` + to see how that may be done. + + Example: + .. code-block:: python + + base_scheduler = ASHAScheduler(max_t=16) + def my_resources_allocation_function( + tune_controller: "TuneController", + trial: Trial, + result: Dict[str, Any], + scheduler: "ResourceChangingScheduler" + ) -> Optional[Union[PlacementGroupFactory, Resource]]: + # logic here + # usage of PlacementGroupFactory is strongly preferred + return PlacementGroupFactory(...) + scheduler = ResourceChangingScheduler( + base_scheduler, + my_resources_allocation_function + ) + + See :doc:`/tune/examples/includes/xgboost_dynamic_resources_example` for a + more detailed example. + """ + + def __init__( + self, + base_scheduler: Optional[TrialScheduler] = None, + resources_allocation_function: Optional[ + Callable[ + [ + "TuneController", + Trial, + Dict[str, Any], + "ResourceChangingScheduler", + ], + Optional[PlacementGroupFactory], + ] + ] = _DistributeResourcesDefault, + ) -> None: + super().__init__() + if resources_allocation_function is None: + warnings.warn( + "`resources_allocation_function` is None. No resource " + "requirements will be changed at any time. Pass a " + "correctly defined function to enable functionality." + ) + self._resources_allocation_function = resources_allocation_function + self._base_scheduler = base_scheduler or FIFOScheduler() + self._base_trial_resources: Optional[PlacementGroupFactory] = None + self._trials_to_reallocate: Dict[ + Trial, Optional[Union[dict, PlacementGroupFactory]] + ] = {} + self._reallocated_trial_ids: Set[str] = set() + self._metric = None + self._mode = None + + @property + def metric(self): + return self._base_scheduler._metric + + @property + def base_trial_resources(self) -> Optional[PlacementGroupFactory]: + return self._base_trial_resources + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], **spec + ) -> bool: + self._metric = metric + self._mode = mode + return self._base_scheduler.set_search_properties(metric, mode, **spec) + + def on_trial_add(self, tune_controller: "TuneController", trial: Trial, **kwargs): + # use the first trial resources as the base + if self._base_trial_resources is None: + self._base_trial_resources = trial.placement_group_factory + # Raise error if the resources of a newly added trial don't match + # base resources, but allow trials that have already had their + # resources changed by ResourceChangingScheduler + # (those can be added again during loading from a checkpoint) + elif trial.trial_id not in self._reallocated_trial_ids: + trial_resources = trial.placement_group_factory + if trial_resources != self._base_trial_resources: + raise RuntimeError( + "ResourceChangingScheduler doesn't support trials with " + "varying base resources. First trial had " + f"{self._base_trial_resources}, trial {trial} has " + f"{trial_resources}." + ) + + return self._base_scheduler.on_trial_add(tune_controller, trial, **kwargs) + + def on_trial_error(self, tune_controller: "TuneController", trial: Trial, **kwargs): + return self._base_scheduler.on_trial_error(tune_controller, trial, **kwargs) + + def on_trial_result( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ) -> str: + base_scheduler_decision = self._base_scheduler.on_trial_result( + tune_controller, trial, result + ) + if base_scheduler_decision == TrialScheduler.CONTINUE: + new_resources = self.reallocate_trial_resources_if_needed( + tune_controller, trial, result + ) + if new_resources: + self._trials_to_reallocate[trial] = new_resources + return TrialScheduler.PAUSE + return base_scheduler_decision + + def on_trial_complete( + self, + tune_controller: "TuneController", + trial: Trial, + result: Dict, + **kwargs, + ): + return self._base_scheduler.on_trial_complete( + tune_controller, trial, result, **kwargs + ) + + def on_trial_remove( + self, tune_controller: "TuneController", trial: Trial, **kwargs + ): + return self._base_scheduler.on_trial_remove(tune_controller, trial, **kwargs) + + def choose_trial_to_run( + self, tune_controller: "TuneController", **kwargs + ) -> Optional[Trial]: + if getattr(tune_controller, "_reuse_actors", False): + raise ValueError( + "ResourceChangingScheduler cannot be used with " + "`reuse_actors=True`. FIX THIS by setting " + "`reuse_actors=False` in `tune.TuneConfig()`." + ) + + any_resources_changed = False + + new_trials_to_reallocate = {} + for trial, new_resources in self._trials_to_reallocate.items(): + if trial.status == Trial.RUNNING: + new_trials_to_reallocate[trial] = new_resources + logger.debug(f"{trial} is still running, skipping for now") + continue + any_resources_changed = any_resources_changed or self.set_trial_resources( + trial, new_resources + ) + self._trials_to_reallocate = new_trials_to_reallocate + + trial = self._base_scheduler.choose_trial_to_run(tune_controller, **kwargs) + return trial + + def debug_string(self) -> str: + return "(ResourceChangingScheduler) " f"{self._base_scheduler.debug_string()}" + + def save(self, checkpoint_path: str): + save_object = self.__dict__ + with open(checkpoint_path, "wb") as outputFile: + pickle.dump(save_object, outputFile) + + def restore(self, checkpoint_path: str): + with open(checkpoint_path, "rb") as inputFile: + save_object = pickle.load(inputFile) + self.__dict__.update(save_object) + + def set_trial_resources( + self, trial: Trial, new_resources: Union[Dict, PlacementGroupFactory] + ) -> bool: + """Returns True if new_resources were set.""" + if new_resources: + logger.info( + f"Setting trial {trial} resource to {new_resources} " + f"with {new_resources._bundles}" + ) + trial.placement_group_factory = None + trial.update_resources(new_resources) + # keep track of all trials which had their resources changed + self._reallocated_trial_ids.add(trial.trial_id) + return True + return False + + def _are_resources_the_same( + self, + trial: Trial, + new_resources, + ) -> bool: + """Returns True if trial's resources are value equal to new_resources. + + Only checks for PlacementGroupFactories at this moment. + """ + if ( + isinstance(new_resources, PlacementGroupFactory) + and trial.placement_group_factory == new_resources + ): + logger.debug( + f"{trial} PGF " + f"{trial.placement_group_factory.required_resources}" + f" and {new_resources.required_resources}" + f" are the same, skipping" + ) + return True + else: + return False + + def reallocate_trial_resources_if_needed( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ) -> Optional[Union[dict, PlacementGroupFactory]]: + """Calls user defined resources_allocation_function. If the returned + resources are not none and not the same as currently present, returns + them. Otherwise, returns None.""" + if self._resources_allocation_function is None: + return None + + if not getattr(self._resources_allocation_function, "metric", None): + self._resources_allocation_function.metric = getattr( + self._base_scheduler, "_metric", self._metric + ) + if not getattr(self._resources_allocation_function, "mode", None): + self._resources_allocation_function.mode = getattr( + self._base_scheduler, "_mode", self._mode + ) + + new_resources = self._resources_allocation_function( + tune_controller, trial, result, self + ) + + # if we can check if the new resources are the same, + # we do that here and skip resource allocation + if new_resources and not self._are_resources_the_same(trial, new_resources): + return new_resources + return None diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/trial_scheduler.py b/venv/lib/python3.10/site-packages/ray/tune/schedulers/trial_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..d99db5d24704c5cc891b0813837d39c32a2321ec --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/schedulers/trial_scheduler.py @@ -0,0 +1,170 @@ +from typing import TYPE_CHECKING, Dict, Optional + +from ray.air._internal.usage import tag_scheduler +from ray.tune.experiment import Trial +from ray.tune.result import DEFAULT_METRIC +from ray.util.annotations import DeveloperAPI, PublicAPI + +if TYPE_CHECKING: + from ray.tune.execution.tune_controller import TuneController + + +@DeveloperAPI +class TrialScheduler: + """Interface for implementing a Trial Scheduler class. + + Note to Tune developers: If a new scheduler is added, please update + `air/_internal/usage.py`. + """ + + CONTINUE = "CONTINUE" #: Status for continuing trial execution + PAUSE = "PAUSE" #: Status for pausing trial execution + STOP = "STOP" #: Status for stopping trial execution + # Caution: Temporary and anti-pattern! This means Scheduler calls + # into Executor directly without going through TrialRunner. + # TODO(xwjiang): Deprecate this after we control the interaction + # between schedulers and executor. + NOOP = "NOOP" + + _metric = None + + _supports_buffered_results = True + + def __init__(self): + tag_scheduler(self) + + @property + def metric(self): + return self._metric + + @property + def supports_buffered_results(self): + return self._supports_buffered_results + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], **spec + ) -> bool: + """Pass search properties to scheduler. + + This method acts as an alternative to instantiating schedulers + that react to metrics with their own `metric` and `mode` parameters. + + Args: + metric: Metric to optimize + mode: One of ["min", "max"]. Direction to optimize. + **spec: Any kwargs for forward compatiblity. + Info like Experiment.PUBLIC_KEYS is provided through here. + """ + if self._metric and metric: + return False + if metric: + self._metric = metric + + if self._metric is None: + # Per default, use anonymous metric + self._metric = DEFAULT_METRIC + + return True + + def on_trial_add(self, tune_controller: "TuneController", trial: Trial): + """Called when a new trial is added to the trial runner.""" + + raise NotImplementedError + + def on_trial_error(self, tune_controller: "TuneController", trial: Trial): + """Notification for the error of trial. + + This will only be called when the trial is in the RUNNING state.""" + + raise NotImplementedError + + def on_trial_result( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ) -> str: + """Called on each intermediate result returned by a trial. + + At this point, the trial scheduler can make a decision by returning + one of CONTINUE, PAUSE, and STOP. This will only be called when the + trial is in the RUNNING state.""" + + raise NotImplementedError + + def on_trial_complete( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ): + """Notification for the completion of trial. + + This will only be called when the trial is in the RUNNING state and + either completes naturally or by manual termination.""" + + raise NotImplementedError + + def on_trial_remove(self, tune_controller: "TuneController", trial: Trial): + """Called to remove trial. + + This is called when the trial is in PAUSED or PENDING state. Otherwise, + call `on_trial_complete`.""" + + raise NotImplementedError + + def choose_trial_to_run(self, tune_controller: "TuneController") -> Optional[Trial]: + """Called to choose a new trial to run. + + This should return one of the trials in tune_controller that is in + the PENDING or PAUSED state. This function must be idempotent. + + If no trial is ready, return None.""" + + raise NotImplementedError + + def debug_string(self) -> str: + """Returns a human readable message for printing to the console.""" + + raise NotImplementedError + + def save(self, checkpoint_path: str): + """Save trial scheduler to a checkpoint""" + raise NotImplementedError + + def restore(self, checkpoint_path: str): + """Restore trial scheduler from checkpoint.""" + raise NotImplementedError + + +@PublicAPI +class FIFOScheduler(TrialScheduler): + """Simple scheduler that just runs trials in submission order.""" + + def __init__(self): + super().__init__() + + def on_trial_add(self, tune_controller: "TuneController", trial: Trial): + pass + + def on_trial_error(self, tune_controller: "TuneController", trial: Trial): + pass + + def on_trial_result( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ) -> str: + return TrialScheduler.CONTINUE + + def on_trial_complete( + self, tune_controller: "TuneController", trial: Trial, result: Dict + ): + pass + + def on_trial_remove(self, tune_controller: "TuneController", trial: Trial): + pass + + def choose_trial_to_run(self, tune_controller: "TuneController") -> Optional[Trial]: + for trial in tune_controller.get_trials(): + if trial.status == Trial.PENDING: + return trial + for trial in tune_controller.get_trials(): + if trial.status == Trial.PAUSED: + return trial + return None + + def debug_string(self) -> str: + return "Using FIFO scheduling algorithm." diff --git a/venv/lib/python3.10/site-packages/ray/tune/schedulers/util.py b/venv/lib/python3.10/site-packages/ray/tune/schedulers/util.py new file mode 100644 index 0000000000000000000000000000000000000000..0d0e012a8367e89397a6258632e5f92e6d41d23d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/schedulers/util.py @@ -0,0 +1,27 @@ +import logging +from typing import Optional + +logger = logging.getLogger(__name__) + + +def _set_search_properties_backwards_compatible( + set_search_properties_func, metric: Optional[str], mode: Optional[str], **spec +) -> bool: + """Wraps around set_search_properties() so that it is backward compatible. + + Also outputs a warning to encourage custom schedulers to be updated. + """ + try: + return set_search_properties_func(metric, mode, **spec) + except TypeError as e: + if str(e).startswith( + "set_search_properties() got an unexpected keyword argument" + ): + logger.warning( + "Please update custom Scheduler to take in function signature " + "as ``def set_search_properties(metric, mode, " + "**spec) -> bool``." + ) + return set_search_properties_func(metric, mode) + else: + raise e diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..39afca111dceaf388d3bffba2a501c5498d598e4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/__init__.py @@ -0,0 +1,153 @@ +from ray._common.utils import get_function_args +from ray.tune.search.basic_variant import BasicVariantGenerator +from ray.tune.search.concurrency_limiter import ConcurrencyLimiter +from ray.tune.search.repeater import Repeater +from ray.tune.search.search_algorithm import SearchAlgorithm +from ray.tune.search.search_generator import SearchGenerator +from ray.tune.search.searcher import Searcher +from ray.tune.search.variant_generator import grid_search +from ray.util import PublicAPI + + +def _import_variant_generator(): + return BasicVariantGenerator + + +def _import_ax_search(): + from ray.tune.search.ax.ax_search import AxSearch + + return AxSearch + + +def _import_hyperopt_search(): + from ray.tune.search.hyperopt.hyperopt_search import HyperOptSearch + + return HyperOptSearch + + +def _import_bayesopt_search(): + from ray.tune.search.bayesopt.bayesopt_search import BayesOptSearch + + return BayesOptSearch + + +def _import_bohb_search(): + from ray.tune.search.bohb.bohb_search import TuneBOHB + + return TuneBOHB + + +def _import_nevergrad_search(): + from ray.tune.search.nevergrad.nevergrad_search import NevergradSearch + + return NevergradSearch + + +def _import_optuna_search(): + from ray.tune.search.optuna.optuna_search import OptunaSearch + + return OptunaSearch + + +def _import_zoopt_search(): + from ray.tune.search.zoopt.zoopt_search import ZOOptSearch + + return ZOOptSearch + + +def _import_hebo_search(): + from ray.tune.search.hebo.hebo_search import HEBOSearch + + return HEBOSearch + + +SEARCH_ALG_IMPORT = { + "variant_generator": _import_variant_generator, + "random": _import_variant_generator, + "ax": _import_ax_search, + "hyperopt": _import_hyperopt_search, + "bayesopt": _import_bayesopt_search, + "bohb": _import_bohb_search, + "nevergrad": _import_nevergrad_search, + "optuna": _import_optuna_search, + "zoopt": _import_zoopt_search, + "hebo": _import_hebo_search, +} + + +@PublicAPI(stability="beta") +def create_searcher( + search_alg, + **kwargs, +): + """Instantiate a search algorithm based on the given string. + + This is useful for swapping between different search algorithms. + + Args: + search_alg: The search algorithm to use. + metric: The training result objective value attribute. Stopping + procedures will use this attribute. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. + **kwargs: Additional parameters. + These keyword arguments will be passed to the initialization + function of the chosen class. + Returns: + ray.tune.search.Searcher: The search algorithm. + Example: + >>> from ray import tune # doctest: +SKIP + >>> search_alg = tune.create_searcher('ax') # doctest: +SKIP + """ + + search_alg = search_alg.lower() + if search_alg not in SEARCH_ALG_IMPORT: + raise ValueError( + f"The `search_alg` argument must be one of " + f"{list(SEARCH_ALG_IMPORT)}. " + f"Got: {search_alg}" + ) + + SearcherClass = SEARCH_ALG_IMPORT[search_alg]() + + search_alg_args = get_function_args(SearcherClass) + trimmed_kwargs = {k: v for k, v in kwargs.items() if k in search_alg_args} + + return SearcherClass(**trimmed_kwargs) + + +UNRESOLVED_SEARCH_SPACE = str( + "You passed a `{par}` parameter to {cls} that contained unresolved search " + "space definitions. {cls} should however be instantiated with fully " + "configured search spaces only. To use Ray Tune's automatic search space " + "conversion, pass the space definition as part of the `param_space` argument " + "to `tune.Tuner()` instead." +) + +UNDEFINED_SEARCH_SPACE = str( + "Trying to sample a configuration from {cls}, but no search " + "space has been defined. Either pass the `{space}` argument when " + "instantiating the search algorithm, or pass a `param_space` to " + "`tune.Tuner()`." +) + +UNDEFINED_METRIC_MODE = str( + "Trying to sample a configuration from {cls}, but the `metric` " + "({metric}) or `mode` ({mode}) parameters have not been set. " + "Either pass these arguments when instantiating the search algorithm, " + "or pass them to `tune.TuneConfig()`." +) + + +__all__ = [ + "SearchAlgorithm", + "Searcher", + "ConcurrencyLimiter", + "Repeater", + "BasicVariantGenerator", + "grid_search", + "SearchGenerator", + "UNRESOLVED_SEARCH_SPACE", + "UNDEFINED_SEARCH_SPACE", + "UNDEFINED_METRIC_MODE", +] diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/__pycache__/basic_variant.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/__pycache__/basic_variant.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..145d1751e098d1e64f4297e9276cd5f39e121d69 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/__pycache__/basic_variant.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/_mock.py b/venv/lib/python3.10/site-packages/ray/tune/search/_mock.py new file mode 100644 index 0000000000000000000000000000000000000000..f1e8eb0b2140ebcebf4f6528642ed9ce7a1afd18 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/_mock.py @@ -0,0 +1,55 @@ +from typing import Dict, List, Optional + +from ray.tune.experiment import Trial +from ray.tune.search import ConcurrencyLimiter, Searcher +from ray.tune.search.search_generator import SearchGenerator + + +class _MockSearcher(Searcher): + def __init__(self, **kwargs): + self.live_trials = {} + self.counter = {"result": 0, "complete": 0} + self.final_results = [] + self.stall = False + self.results = [] + super(_MockSearcher, self).__init__(**kwargs) + + def suggest(self, trial_id: str): + if not self.stall: + self.live_trials[trial_id] = 1 + return {"test_variable": 2} + return None + + def on_trial_result(self, trial_id: str, result: Dict): + self.counter["result"] += 1 + self.results += [result] + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ): + self.counter["complete"] += 1 + if result: + self._process_result(result) + if trial_id in self.live_trials: + del self.live_trials[trial_id] + + def _process_result(self, result: Dict): + self.final_results += [result] + + +class _MockSuggestionAlgorithm(SearchGenerator): + def __init__(self, max_concurrent: Optional[int] = None, **kwargs): + self.searcher = _MockSearcher(**kwargs) + if max_concurrent: + self.searcher = ConcurrencyLimiter( + self.searcher, max_concurrent=max_concurrent + ) + super(_MockSuggestionAlgorithm, self).__init__(self.searcher) + + @property + def live_trials(self) -> List[Trial]: + return self.searcher.live_trials + + @property + def results(self) -> List[Dict]: + return self.searcher.results diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/ax/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/search/ax/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2cc1df85b97152386a332358657e13e2dd06ede --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/ax/__init__.py @@ -0,0 +1,3 @@ +from ray.tune.search.ax.ax_search import AxSearch + +__all__ = ["AxSearch"] diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/ax/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/ax/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6b433b08a16ca49ddcce4fec7bff56205985598 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/ax/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/ax/__pycache__/ax_search.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/ax/__pycache__/ax_search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba2b252fc564384cf7b2c9f21e0c343856770fe0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/ax/__pycache__/ax_search.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/ax/ax_search.py b/venv/lib/python3.10/site-packages/ray/tune/search/ax/ax_search.py new file mode 100644 index 0000000000000000000000000000000000000000..5cc408a89c73104f62f3fdb531c2c01be406686f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/ax/ax_search.py @@ -0,0 +1,432 @@ +import copy +import logging +from typing import Dict, List, Optional, Union + +import numpy as np + +from ray import cloudpickle +from ray.tune.result import DEFAULT_METRIC +from ray.tune.search import ( + UNDEFINED_METRIC_MODE, + UNDEFINED_SEARCH_SPACE, + UNRESOLVED_SEARCH_SPACE, + Searcher, +) +from ray.tune.search.sample import ( + Categorical, + Float, + Integer, + LogUniform, + Quantized, + Uniform, +) +from ray.tune.search.variant_generator import parse_spec_vars +from ray.tune.utils.util import flatten_dict, unflatten_list_dict + +try: + import ax + from ax.service.ax_client import AxClient +except ImportError: + ax = AxClient = None + +# This exception only exists in newer Ax releases for python 3.7 +try: + from ax.exceptions.core import DataRequiredError + from ax.exceptions.generation_strategy import MaxParallelismReachedException +except ImportError: + MaxParallelismReachedException = DataRequiredError = Exception + + +logger = logging.getLogger(__name__) + + +class AxSearch(Searcher): + """Uses `Ax `_ to optimize hyperparameters. + + Ax is a platform for understanding, managing, deploying, and + automating adaptive experiments. Ax provides an easy to use + interface with BoTorch, a flexible, modern library for Bayesian + optimization in PyTorch. More information can be found in https://ax.dev/. + + To use this search algorithm, you must install Ax: + + .. code-block:: bash + + $ pip install ax-platform + + Parameters: + space: Parameters in the experiment search space. + Required elements in the dictionaries are: "name" (name of + this parameter, string), "type" (type of the parameter: "range", + "fixed", or "choice", string), "bounds" for range parameters + (list of two values, lower bound first), "values" for choice + parameters (list of values), and "value" for fixed parameters + (single value). + metric: Name of the metric used as objective in this + experiment. This metric must be present in `raw_data` argument + to `log_data`. This metric must also be present in the dict + reported/returned by the Trainable. If None but a mode was passed, + the `ray.tune.result.DEFAULT_METRIC` will be used per default. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. Defaults to "max". + points_to_evaluate: Initial parameter suggestions to be run + first. This is for when you already have some good parameters + you want to run first to help the algorithm make better suggestions + for future parameters. Needs to be a list of dicts containing the + configurations. + parameter_constraints: Parameter constraints, such as + "x3 >= x4" or "x3 + x4 >= 2". + outcome_constraints: Outcome constraints of form + "metric_name >= bound", like "m1 <= 3." + ax_client: Optional AxClient instance. If this is set, do + not pass any values to these parameters: `space`, `metric`, + `parameter_constraints`, `outcome_constraints`. + **ax_kwargs: Passed to AxClient instance. Ignored if `AxClient` is not + None. + + Tune automatically converts search spaces to Ax's format: + + .. code-block:: python + + from ray import tune + from ray.tune.search.ax import AxSearch + + config = { + "x1": tune.uniform(0.0, 1.0), + "x2": tune.uniform(0.0, 1.0) + } + + def easy_objective(config): + for i in range(100): + intermediate_result = config["x1"] + config["x2"] * i + tune.report({"score": intermediate_result}) + + ax_search = AxSearch() + tuner = tune.Tuner( + easy_objective, + tune_config=tune.TuneConfig( + search_alg=ax_search, + metric="score", + mode="max", + ), + param_space=config, + ) + tuner.fit() + + If you would like to pass the search space manually, the code would + look like this: + + .. code-block:: python + + from ray import tune + from ray.tune.search.ax import AxSearch + + parameters = [ + {"name": "x1", "type": "range", "bounds": [0.0, 1.0]}, + {"name": "x2", "type": "range", "bounds": [0.0, 1.0]}, + ] + + def easy_objective(config): + for i in range(100): + intermediate_result = config["x1"] + config["x2"] * i + tune.report({"score": intermediate_result}) + + ax_search = AxSearch(space=parameters, metric="score", mode="max") + tuner = tune.Tuner( + easy_objective, + tune_config=tune.TuneConfig( + search_alg=ax_search, + ), + ) + tuner.fit() + + """ + + def __init__( + self, + space: Optional[Union[Dict, List[Dict]]] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + points_to_evaluate: Optional[List[Dict]] = None, + parameter_constraints: Optional[List] = None, + outcome_constraints: Optional[List] = None, + ax_client: Optional[AxClient] = None, + **ax_kwargs, + ): + assert ( + ax is not None + ), """Ax must be installed! + You can install AxSearch with the command: + `pip install ax-platform`.""" + + if mode: + assert mode in ["min", "max"], "`mode` must be 'min' or 'max'." + + super(AxSearch, self).__init__( + metric=metric, + mode=mode, + ) + + self._ax = ax_client + self._ax_kwargs = ax_kwargs or {} + + if isinstance(space, dict) and space: + resolved_vars, domain_vars, grid_vars = parse_spec_vars(space) + if domain_vars or grid_vars: + logger.warning( + UNRESOLVED_SEARCH_SPACE.format(par="space", cls=type(self)) + ) + space = self.convert_search_space(space) + + self._space = space + self._parameter_constraints = parameter_constraints + self._outcome_constraints = outcome_constraints + + self._points_to_evaluate = copy.deepcopy(points_to_evaluate) + + self._parameters = [] + self._live_trial_mapping = {} + + if self._ax or self._space: + self._setup_experiment() + + def _setup_experiment(self): + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + if not self._ax: + self._ax = AxClient(**self._ax_kwargs) + + try: + exp = self._ax.experiment + has_experiment = True + except ValueError: + has_experiment = False + + if not has_experiment: + if not self._space: + raise ValueError( + "You have to create an Ax experiment by calling " + "`AxClient.create_experiment()`, or you should pass an " + "Ax search space as the `space` parameter to `AxSearch`, " + "or pass a `param_space` dict to `tune.Tuner()`." + ) + if self._mode not in ["min", "max"]: + raise ValueError( + "Please specify the `mode` argument when initializing " + "the `AxSearch` object or pass it to `tune.TuneConfig()`." + ) + self._ax.create_experiment( + parameters=self._space, + objective_name=self._metric, + parameter_constraints=self._parameter_constraints, + outcome_constraints=self._outcome_constraints, + minimize=self._mode != "max", + ) + else: + if any( + [ + self._space, + self._parameter_constraints, + self._outcome_constraints, + self._mode, + self._metric, + ] + ): + raise ValueError( + "If you create the Ax experiment yourself, do not pass " + "values for these parameters to `AxSearch`: {}.".format( + [ + "space", + "parameter_constraints", + "outcome_constraints", + "mode", + "metric", + ] + ) + ) + + exp = self._ax.experiment + + # Update mode and metric from experiment if it has been passed + self._mode = "min" if exp.optimization_config.objective.minimize else "max" + self._metric = exp.optimization_config.objective.metric.name + + self._parameters = list(exp.parameters) + + if self._ax._enforce_sequential_optimization: + logger.warning( + "Detected sequential enforcement. Be sure to use " + "a ConcurrencyLimiter." + ) + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ): + if self._ax: + return False + space = self.convert_search_space(config) + self._space = space + if metric: + self._metric = metric + if mode: + self._mode = mode + + self._setup_experiment() + return True + + def suggest(self, trial_id: str) -> Optional[Dict]: + if not self._ax: + raise RuntimeError( + UNDEFINED_SEARCH_SPACE.format( + cls=self.__class__.__name__, space="space" + ) + ) + + if not self._metric or not self._mode: + raise RuntimeError( + UNDEFINED_METRIC_MODE.format( + cls=self.__class__.__name__, metric=self._metric, mode=self._mode + ) + ) + + if self._points_to_evaluate: + config = self._points_to_evaluate.pop(0) + parameters, trial_index = self._ax.attach_trial(config) + else: + try: + parameters, trial_index = self._ax.get_next_trial() + except (MaxParallelismReachedException, DataRequiredError): + return None + + self._live_trial_mapping[trial_id] = trial_index + try: + suggested_config = unflatten_list_dict(parameters) + except AssertionError: + # Fails to unflatten if keys are out of order, which only happens + # if search space includes a list with both constants and + # tunable hyperparameters: + # Ex: "a": [1, tune.uniform(2, 3), 4] + suggested_config = unflatten_list_dict( + {k: parameters[k] for k in sorted(parameters.keys())} + ) + return suggested_config + + def on_trial_complete(self, trial_id, result=None, error=False): + """Notification for the completion of trial. + + Data of form key value dictionary of metric names and values. + """ + if result: + self._process_result(trial_id, result) + self._live_trial_mapping.pop(trial_id) + + def _process_result(self, trial_id, result): + ax_trial_index = self._live_trial_mapping[trial_id] + metrics_to_include = [self._metric] + [ + oc.metric.name + for oc in self._ax.experiment.optimization_config.outcome_constraints + ] + metric_dict = {} + for key in metrics_to_include: + val = result[key] + if np.isnan(val) or np.isinf(val): + # Don't report trials with NaN metrics to Ax + self._ax.abandon_trial( + trial_index=ax_trial_index, + reason=f"nan/inf metrics reported by {trial_id}", + ) + return + metric_dict[key] = (val, None) + self._ax.complete_trial(trial_index=ax_trial_index, raw_data=metric_dict) + + @staticmethod + def convert_search_space(spec: Dict): + resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec) + + if grid_vars: + raise ValueError( + "Grid search parameters cannot be automatically converted " + "to an Ax search space." + ) + + # Flatten and resolve again after checking for grid search. + spec = flatten_dict(spec, prevent_delimiter=True) + resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec) + + def resolve_value(par, domain): + sampler = domain.get_sampler() + if isinstance(sampler, Quantized): + logger.warning( + "AxSearch does not support quantization. Dropped quantization." + ) + sampler = sampler.sampler + + if isinstance(domain, Float): + if isinstance(sampler, LogUniform): + return { + "name": par, + "type": "range", + "bounds": [domain.lower, domain.upper], + "value_type": "float", + "log_scale": True, + } + elif isinstance(sampler, Uniform): + return { + "name": par, + "type": "range", + "bounds": [domain.lower, domain.upper], + "value_type": "float", + "log_scale": False, + } + elif isinstance(domain, Integer): + if isinstance(sampler, LogUniform): + return { + "name": par, + "type": "range", + "bounds": [domain.lower, domain.upper - 1], + "value_type": "int", + "log_scale": True, + } + elif isinstance(sampler, Uniform): + return { + "name": par, + "type": "range", + "bounds": [domain.lower, domain.upper - 1], + "value_type": "int", + "log_scale": False, + } + elif isinstance(domain, Categorical): + if isinstance(sampler, Uniform): + return {"name": par, "type": "choice", "values": domain.categories} + + raise ValueError( + "AxSearch does not support parameters of type " + "`{}` with samplers of type `{}`".format( + type(domain).__name__, type(domain.sampler).__name__ + ) + ) + + # Parameter name is e.g. "a/b/c" for nested dicts, + # "a/d/0", "a/d/1" for nested lists (using the index in the list) + fixed_values = [ + {"name": "/".join(str(p) for p in path), "type": "fixed", "value": val} + for path, val in resolved_vars + ] + resolved_values = [ + resolve_value("/".join(str(p) for p in path), domain) + for path, domain in domain_vars + ] + + return fixed_values + resolved_values + + def save(self, checkpoint_path: str): + save_object = self.__dict__ + with open(checkpoint_path, "wb") as outputFile: + cloudpickle.dump(save_object, outputFile) + + def restore(self, checkpoint_path: str): + with open(checkpoint_path, "rb") as inputFile: + save_object = cloudpickle.load(inputFile) + self.__dict__.update(save_object) diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/basic_variant.py b/venv/lib/python3.10/site-packages/ray/tune/search/basic_variant.py new file mode 100644 index 0000000000000000000000000000000000000000..73bdaa31c5e8cba26c322d1d60b09bcbb4af9f53 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/basic_variant.py @@ -0,0 +1,421 @@ +import copy +import itertools +import os +import uuid +import warnings +from pathlib import Path +from typing import TYPE_CHECKING, Dict, List, Optional, Union + +import numpy as np + +from ray.air._internal.usage import tag_searcher +from ray.tune.error import TuneError +from ray.tune.experiment.config_parser import _create_trial_from_spec, _make_parser +from ray.tune.search.sample import _BackwardsCompatibleNumpyRng, np_random_generator +from ray.tune.search.search_algorithm import SearchAlgorithm +from ray.tune.search.variant_generator import ( + _count_spec_samples, + _count_variants, + _flatten_resolved_vars, + _get_preset_variants, + format_vars, + generate_variants, +) +from ray.tune.utils.util import _atomic_save, _load_newest_checkpoint +from ray.util import PublicAPI + +if TYPE_CHECKING: + from ray.tune.experiment import Experiment + +SERIALIZATION_THRESHOLD = 1e6 + + +class _VariantIterator: + """Iterates over generated variants from the search space. + + This object also toggles between lazy evaluation and + eager evaluation of samples. If lazy evaluation is enabled, + this object cannot be serialized. + """ + + def __init__(self, iterable, lazy_eval=False): + self.lazy_eval = lazy_eval + self.iterable = iterable + self._has_next = True + if lazy_eval: + self._load_value() + else: + self.iterable = list(iterable) + self._has_next = bool(self.iterable) + + def _load_value(self): + try: + self.next_value = next(self.iterable) + except StopIteration: + self._has_next = False + + def has_next(self): + return self._has_next + + def __next__(self): + if self.lazy_eval: + current_value = self.next_value + self._load_value() + return current_value + current_value = self.iterable.pop(0) + self._has_next = bool(self.iterable) + return current_value + + +class _TrialIterator: + """Generates trials from the spec. + + Args: + uuid_prefix: Used in creating the trial name. + num_samples: Number of samples from distribution + (same as tune.TuneConfig). + unresolved_spec: Experiment specification + that might have unresolved distributions. + constant_grid_search: Should random variables be sampled + first before iterating over grid variants (True) or not (False). + points_to_evaluate: Configurations that will be tried out without sampling. + lazy_eval: Whether variants should be generated + lazily or eagerly. This is toggled depending + on the size of the grid search. + start: index at which to start counting trials. + random_state (int | np.random.Generator | np.random.RandomState): + Seed or numpy random generator to use for reproducible results. + If None (default), will use the global numpy random generator + (``np.random``). Please note that full reproducibility cannot + be guaranteed in a distributed environment. + """ + + def __init__( + self, + uuid_prefix: str, + num_samples: int, + unresolved_spec: dict, + constant_grid_search: bool = False, + points_to_evaluate: Optional[List] = None, + lazy_eval: bool = False, + start: int = 0, + random_state: Optional[ + Union[int, "np_random_generator", np.random.RandomState] + ] = None, + ): + self.parser = _make_parser() + self.num_samples = num_samples + self.uuid_prefix = uuid_prefix + self.num_samples_left = num_samples + self.unresolved_spec = unresolved_spec + self.constant_grid_search = constant_grid_search + self.points_to_evaluate = points_to_evaluate or [] + self.num_points_to_evaluate = len(self.points_to_evaluate) + self.counter = start + self.lazy_eval = lazy_eval + self.variants = None + self.random_state = random_state + + def create_trial(self, resolved_vars, spec): + trial_id = self.uuid_prefix + ("%05d" % self.counter) + experiment_tag = str(self.counter) + # Always append resolved vars to experiment tag? + if resolved_vars: + experiment_tag += "_{}".format(format_vars(resolved_vars)) + self.counter += 1 + return _create_trial_from_spec( + spec, + self.parser, + evaluated_params=_flatten_resolved_vars(resolved_vars), + trial_id=trial_id, + experiment_tag=experiment_tag, + ) + + def __next__(self): + """Generates Trial objects with the variant generation process. + + Uses a fixed point iteration to resolve variants. All trials + should be able to be generated at once. + + See also: `ray.tune.search.variant_generator`. + + Returns: + Trial object + """ + + if "run" not in self.unresolved_spec: + raise TuneError("Must specify `run` in {}".format(self.unresolved_spec)) + + if self.variants and self.variants.has_next(): + # This block will be skipped upon instantiation. + # `variants` will be set later after the first loop. + resolved_vars, spec = next(self.variants) + return self.create_trial(resolved_vars, spec) + + if self.points_to_evaluate: + config = self.points_to_evaluate.pop(0) + self.num_samples_left -= 1 + self.variants = _VariantIterator( + _get_preset_variants( + self.unresolved_spec, + config, + constant_grid_search=self.constant_grid_search, + random_state=self.random_state, + ), + lazy_eval=self.lazy_eval, + ) + resolved_vars, spec = next(self.variants) + return self.create_trial(resolved_vars, spec) + elif self.num_samples_left > 0: + self.variants = _VariantIterator( + generate_variants( + self.unresolved_spec, + constant_grid_search=self.constant_grid_search, + random_state=self.random_state, + ), + lazy_eval=self.lazy_eval, + ) + self.num_samples_left -= 1 + resolved_vars, spec = next(self.variants) + return self.create_trial(resolved_vars, spec) + else: + raise StopIteration + + def __iter__(self): + return self + + +@PublicAPI +class BasicVariantGenerator(SearchAlgorithm): + """Uses Tune's variant generation for resolving variables. + + This is the default search algorithm used if no other search algorithm + is specified. + + + Args: + points_to_evaluate: Initial parameter suggestions to be run + first. This is for when you already have some good parameters + you want to run first to help the algorithm make better suggestions + for future parameters. Needs to be a list of dicts containing the + configurations. + max_concurrent: Maximum number of concurrently running trials. + If 0 (default), no maximum is enforced. + constant_grid_search: If this is set to ``True``, Ray Tune will + *first* try to sample random values and keep them constant over + grid search parameters. If this is set to ``False`` (default), + Ray Tune will sample new random parameters in each grid search + condition. + random_state: + Seed or numpy random generator to use for reproducible results. + If None (default), will use the global numpy random generator + (``np.random``). Please note that full reproducibility cannot + be guaranteed in a distributed environment. + + + Example: + + .. code-block:: python + + from ray import tune + + # This will automatically use the `BasicVariantGenerator` + tuner = tune.Tuner( + lambda config: config["a"] + config["b"], + tune_config=tune.TuneConfig( + num_samples=4 + ), + param_space={ + "a": tune.grid_search([1, 2]), + "b": tune.randint(0, 3) + }, + ) + tuner.fit() + + In the example above, 8 trials will be generated: For each sample + (``4``), each of the grid search variants for ``a`` will be sampled + once. The ``b`` parameter will be sampled randomly. + + The generator accepts a pre-set list of points that should be evaluated. + The points will replace the first samples of each experiment passed to + the ``BasicVariantGenerator``. + + Each point will replace one sample of the specified ``num_samples``. If + grid search variables are overwritten with the values specified in the + presets, the number of samples will thus be reduced. + + Example: + + .. code-block:: python + + from ray import tune + from ray.tune.search.basic_variant import BasicVariantGenerator + + tuner = tune.Tuner( + lambda config: config["a"] + config["b"], + tune_config=tune.TuneConfig( + search_alg=BasicVariantGenerator(points_to_evaluate=[ + {"a": 2, "b": 2}, + {"a": 1}, + {"b": 2} + ]), + num_samples=4 + ), + param_space={ + "a": tune.grid_search([1, 2]), + "b": tune.randint(0, 3) + }, + ) + tuner.fit() + + The example above will produce six trials via four samples: + + - The first sample will produce one trial with ``a=2`` and ``b=2``. + - The second sample will produce one trial with ``a=1`` and ``b`` sampled + randomly + - The third sample will produce two trials, one for each grid search + value of ``a``. It will be ``b=2`` for both of these trials. + - The fourth sample will produce two trials, one for each grid search + value of ``a``. ``b`` will be sampled randomly and independently for + both of these trials. + + """ + + CKPT_FILE_TMPL = "basic-variant-state-{}.json" + + def __init__( + self, + points_to_evaluate: Optional[List[Dict]] = None, + max_concurrent: int = 0, + constant_grid_search: bool = False, + random_state: Optional[ + Union[int, "np_random_generator", np.random.RandomState] + ] = None, + ): + tag_searcher(self) + self._trial_generator = [] + self._iterators = [] + self._trial_iter = None + self._finished = False + self._random_state = _BackwardsCompatibleNumpyRng(random_state) + + self._points_to_evaluate = points_to_evaluate or [] + + # Unique prefix for all trials generated, e.g., trial ids start as + # 2f1e_00001, 2f1ef_00002, 2f1ef_0003, etc. Overridable for testing. + force_test_uuid = os.environ.get("_TEST_TUNE_TRIAL_UUID") + if force_test_uuid: + self._uuid_prefix = force_test_uuid + "_" + else: + self._uuid_prefix = str(uuid.uuid1().hex)[:5] + "_" + + self._total_samples = 0 + self.max_concurrent = max_concurrent + self._constant_grid_search = constant_grid_search + self._live_trials = set() + + @property + def total_samples(self): + return self._total_samples + + def add_configurations( + self, experiments: Union["Experiment", List["Experiment"], Dict[str, Dict]] + ): + """Chains generator given experiment specifications. + + Arguments: + experiments: Experiments to run. + """ + from ray.tune.experiment import _convert_to_experiment_list + + experiment_list = _convert_to_experiment_list(experiments) + + for experiment in experiment_list: + grid_vals = _count_spec_samples(experiment.spec, num_samples=1) + lazy_eval = grid_vals > SERIALIZATION_THRESHOLD + if lazy_eval: + warnings.warn( + f"The number of pre-generated samples ({grid_vals}) " + "exceeds the serialization threshold " + f"({int(SERIALIZATION_THRESHOLD)}). Resume ability is " + "disabled. To fix this, reduce the number of " + "dimensions/size of the provided grid search." + ) + + previous_samples = self._total_samples + points_to_evaluate = copy.deepcopy(self._points_to_evaluate) + self._total_samples += _count_variants(experiment.spec, points_to_evaluate) + iterator = _TrialIterator( + uuid_prefix=self._uuid_prefix, + num_samples=experiment.spec.get("num_samples", 1), + unresolved_spec=experiment.spec, + constant_grid_search=self._constant_grid_search, + points_to_evaluate=points_to_evaluate, + lazy_eval=lazy_eval, + start=previous_samples, + random_state=self._random_state, + ) + self._iterators.append(iterator) + self._trial_generator = itertools.chain(self._trial_generator, iterator) + + def next_trial(self): + """Provides one Trial object to be queued into the TrialRunner. + + Returns: + Trial: Returns a single trial. + """ + if self.is_finished(): + return None + if self.max_concurrent > 0 and len(self._live_trials) >= self.max_concurrent: + return None + if not self._trial_iter: + self._trial_iter = iter(self._trial_generator) + try: + trial = next(self._trial_iter) + self._live_trials.add(trial.trial_id) + return trial + except StopIteration: + self._trial_generator = [] + self._trial_iter = None + self.set_finished() + return None + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ): + if trial_id in self._live_trials: + self._live_trials.remove(trial_id) + + def get_state(self): + if any(iterator.lazy_eval for iterator in self._iterators): + return False + state = self.__dict__.copy() + del state["_trial_generator"] + return state + + def set_state(self, state): + self.__dict__.update(state) + for iterator in self._iterators: + self._trial_generator = itertools.chain(self._trial_generator, iterator) + + def save_to_dir(self, dirpath, session_str): + if any(iterator.lazy_eval for iterator in self._iterators): + return False + state_dict = self.get_state() + _atomic_save( + state=state_dict, + checkpoint_dir=dirpath, + file_name=self.CKPT_FILE_TMPL.format(session_str), + tmp_file_name=".tmp_generator", + ) + + def has_checkpoint(self, dirpath: str): + """Whether a checkpoint file exists within dirpath.""" + return any(Path(dirpath).glob(self.CKPT_FILE_TMPL.format("*"))) + + def restore_from_dir(self, dirpath: str): + """Restores self + searcher + search wrappers from dirpath.""" + state_dict = _load_newest_checkpoint(dirpath, self.CKPT_FILE_TMPL.format("*")) + if not state_dict: + raise RuntimeError("Unable to find checkpoint in {}.".format(dirpath)) + self.set_state(state_dict) diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2569dcd5849a69f9818e90ac6db9cc4891c2da9c --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/__init__.py @@ -0,0 +1,3 @@ +from ray.tune.search.bayesopt.bayesopt_search import BayesOptSearch + +__all__ = ["BayesOptSearch"] diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7114f6b0b091209f1a37905c9fdfac8ee12ece70 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/__pycache__/bayesopt_search.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/__pycache__/bayesopt_search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf67964796db2f7419f9c670cc30692ed5b8ef06 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/__pycache__/bayesopt_search.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/bayesopt_search.py b/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/bayesopt_search.py new file mode 100644 index 0000000000000000000000000000000000000000..97b67192bcc88aafe81a9dd5d361b03884d84688 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/bayesopt/bayesopt_search.py @@ -0,0 +1,449 @@ +import json +import logging +import pickle +from collections import defaultdict +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple + +from ray.tune.result import DEFAULT_METRIC +from ray.tune.search import ( + UNDEFINED_METRIC_MODE, + UNDEFINED_SEARCH_SPACE, + UNRESOLVED_SEARCH_SPACE, + Searcher, +) +from ray.tune.search.sample import Domain, Float, Quantized, Uniform +from ray.tune.search.variant_generator import parse_spec_vars +from ray.tune.utils import flatten_dict +from ray.tune.utils.util import is_nan_or_inf, unflatten_dict + +try: # Python 3 only -- needed for lint test. + import bayes_opt as byo +except ImportError: + byo = None + + +if TYPE_CHECKING: + from ray.tune import ExperimentAnalysis + +logger = logging.getLogger(__name__) + + +def _dict_hash(config, precision): + flatconfig = flatten_dict(config) + for param, value in flatconfig.items(): + if isinstance(value, float): + flatconfig[param] = "{:.{digits}f}".format(value, digits=precision) + + hashed = json.dumps(flatconfig, sort_keys=True, default=str) + return hashed + + +class BayesOptSearch(Searcher): + """Uses bayesian-optimization/BayesianOptimization to optimize hyperparameters. + + bayesian-optimization/BayesianOptimization is a library for Bayesian Optimization. More + info can be found here: https://github.com/bayesian-optimization/BayesianOptimization. + + This searcher will automatically filter out any NaN, inf or -inf + results. + + You will need to install bayesian-optimization/BayesianOptimization via the following: + + .. code-block:: bash + + pip install bayesian-optimization==1.4.3 + + Initializing this search algorithm with a ``space`` requires that it's + in the ``BayesianOptimization`` search space format. Otherwise, you + should instead pass in a Tune search space into ``Tuner(param_space=...)``, + and the search space will be automatically converted for you. + + See this ``BayesianOptimization`` example notebook + `_ + for an example. + + Args: + space: Continuous search space. Parameters will be sampled from + this space which will be used to run trials. + metric: The training result objective value attribute. If None + but a mode was passed, the anonymous metric `_metric` will be used + per default. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. + points_to_evaluate: Initial parameter suggestions to be run + first. This is for when you already have some good parameters + you want to run first to help the algorithm make better suggestions + for future parameters. Needs to be a list of dicts containing the + configurations. + utility_kwargs: Parameters to define the utility function. + The default value is a dictionary with three keys: + - kind: ucb (Upper Confidence Bound) + - kappa: 2.576 + - xi: 0.0 + random_state: Used to initialize BayesOpt. + random_search_steps: Number of initial random searches. + This is necessary to avoid initial local overfitting + of the Bayesian process. + verbose: Sets verbosity level for BayesOpt packages. + patience: If patience is set and we've repeated a trial numerous times, + we terminate the experiment. + skip_duplicate: skip duplicate config + analysis: Optionally, the previous analysis to integrate. + + Tune automatically converts search spaces to BayesOptSearch's format: + + .. code-block:: python + + from ray import tune + from ray.tune.search.bayesopt import BayesOptSearch + + config = { + "width": tune.uniform(0, 20), + "height": tune.uniform(-100, 100) + } + + bayesopt = BayesOptSearch(metric="mean_loss", mode="min") + tuner = tune.Tuner( + my_func, + tune_config=tune.TuneConfig( + search_alg=baysopt, + ), + param_space=config, + ) + tuner.fit() + + If you would like to pass the search space manually, the code would + look like this: + + .. code-block:: python + + from ray import tune + from ray.tune.search.bayesopt import BayesOptSearch + + space = { + 'width': (0, 20), + 'height': (-100, 100), + } + bayesopt = BayesOptSearch(space, metric="mean_loss", mode="min") + tuner = tune.Tuner( + my_func, + tune_config=tune.TuneConfig( + search_alg=bayesopt, + ), + ) + tuner.fit() + + """ + + # bayes_opt.BayesianOptimization: Optimization object + optimizer = None + + def __init__( + self, + space: Optional[Dict] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + points_to_evaluate: Optional[List[Dict]] = None, + utility_kwargs: Optional[Dict] = None, + random_state: int = 42, + random_search_steps: int = 10, + verbose: int = 0, + patience: int = 5, + skip_duplicate: bool = True, + analysis: Optional["ExperimentAnalysis"] = None, + ): + assert byo is not None, ( + "BayesOpt must be installed!. You can install BayesOpt with" + " the command: `pip install bayesian-optimization==1.4.3`." + ) + if mode: + assert mode in ["min", "max"], "`mode` must be 'min' or 'max'." + self._config_counter = defaultdict(int) + self._patience = patience + # int: Precision at which to hash values. + self.repeat_float_precision = 5 + if self._patience <= 0: + raise ValueError("patience must be set to a value greater than 0!") + self._skip_duplicate = skip_duplicate + super(BayesOptSearch, self).__init__( + metric=metric, + mode=mode, + ) + + if utility_kwargs is None: + # The defaults arguments are the same + # as in the package BayesianOptimization + utility_kwargs = dict( + kind="ucb", + kappa=2.576, + xi=0.0, + ) + + if mode == "max": + self._metric_op = 1.0 + elif mode == "min": + self._metric_op = -1.0 + + self._points_to_evaluate = points_to_evaluate + + self._live_trial_mapping = {} + self._buffered_trial_results = [] + self.random_search_trials = random_search_steps + self._total_random_search_trials = 0 + + self.utility = byo.UtilityFunction(**utility_kwargs) + + self._analysis = analysis + + if isinstance(space, dict) and space: + resolved_vars, domain_vars, grid_vars = parse_spec_vars(space) + if domain_vars or grid_vars: + logger.warning( + UNRESOLVED_SEARCH_SPACE.format(par="space", cls=type(self)) + ) + space = self.convert_search_space(space, join=True) + + self._space = space + self._verbose = verbose + self._random_state = random_state + + self.optimizer = None + if space: + self._setup_optimizer() + + def _setup_optimizer(self): + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + self.optimizer = byo.BayesianOptimization( + f=None, + pbounds=self._space, + verbose=self._verbose, + random_state=self._random_state, + ) + + # Registering the provided analysis, if given + if self._analysis is not None: + self.register_analysis(self._analysis) + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ) -> bool: + if self.optimizer: + return False + space = self.convert_search_space(config) + self._space = space + if metric: + self._metric = metric + if mode: + self._mode = mode + + if self._mode == "max": + self._metric_op = 1.0 + elif self._mode == "min": + self._metric_op = -1.0 + + self._setup_optimizer() + return True + + def suggest(self, trial_id: str) -> Optional[Dict]: + """Return new point to be explored by black box function. + + Args: + trial_id: Id of the trial. + This is a short alphanumerical string. + + Returns: + Either a dictionary describing the new point to explore or + None, when no new point is to be explored for the time being. + """ + if not self.optimizer: + raise RuntimeError( + UNDEFINED_SEARCH_SPACE.format( + cls=self.__class__.__name__, space="space" + ) + ) + + if not self._metric or not self._mode: + raise RuntimeError( + UNDEFINED_METRIC_MODE.format( + cls=self.__class__.__name__, metric=self._metric, mode=self._mode + ) + ) + + if self._points_to_evaluate: + config = self._points_to_evaluate.pop(0) + else: + # We compute the new point to explore + config = self.optimizer.suggest(self.utility) + + config_hash = _dict_hash(config, self.repeat_float_precision) + # Check if already computed + already_seen = config_hash in self._config_counter + self._config_counter[config_hash] += 1 + top_repeats = max(self._config_counter.values()) + + # If patience is set and we've repeated a trial numerous times, + # we terminate the experiment. + if self._patience is not None and top_repeats > self._patience: + return Searcher.FINISHED + # If we have seen a value before, we'll skip it. + if already_seen and self._skip_duplicate: + logger.info("Skipping duplicated config: {}.".format(config)) + return None + + # If we are still in the random search part and we are waiting for + # trials to complete + if len(self._buffered_trial_results) < self.random_search_trials: + # We check if we have already maxed out the number of requested + # random search trials + if self._total_random_search_trials == self.random_search_trials: + # If so we stop the suggestion and return None + return None + # Otherwise we increase the total number of rndom search trials + if config: + self._total_random_search_trials += 1 + + # Save the new trial to the trial mapping + self._live_trial_mapping[trial_id] = config + + # Return a deep copy of the mapping + return unflatten_dict(config) + + def register_analysis(self, analysis: "ExperimentAnalysis"): + """Integrate the given analysis into the gaussian process. + + Args: + analysis: Optionally, the previous analysis + to integrate. + """ + for (_, report), params in zip( + analysis.dataframe(metric=self._metric, mode=self._mode).iterrows(), + analysis.get_all_configs().values(), + ): + # We add the obtained results to the + # gaussian process optimizer + self._register_result(params, report) + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ): + """Notification for the completion of trial. + + Args: + trial_id: Id of the trial. + This is a short alphanumerical string. + result: Dictionary of result. + May be none when some error occurs. + error: Boolean representing a previous error state. + The result should be None when error is True. + """ + # We try to get the parameters used for this trial + params = self._live_trial_mapping.pop(trial_id, None) + + # The results may be None if some exception is raised during the trial. + # Also, if the parameters are None (were already processed) + # we interrupt the following procedure. + # Additionally, if somehow the error is True but + # the remaining values are not we also block the method + if result is None or params is None or error: + return + + # If we don't have to execute some random search steps + if len(self._buffered_trial_results) >= self.random_search_trials: + # we simply register the obtained result + self._register_result(params, result) + return + + # We store the results into a temporary cache + self._buffered_trial_results.append((params, result)) + + # If the random search finished, + # we update the BO with all the computer points. + if len(self._buffered_trial_results) == self.random_search_trials: + for params, result in self._buffered_trial_results: + self._register_result(params, result) + + def _register_result(self, params: Tuple[str], result: Dict): + """Register given tuple of params and results.""" + if is_nan_or_inf(result[self.metric]): + return + self.optimizer.register(params, self._metric_op * result[self.metric]) + + def get_state(self) -> Dict[str, Any]: + state = self.__dict__.copy() + return state + + def set_state(self, state: Dict[str, Any]): + self.__dict__.update(state) + + def save(self, checkpoint_path: str): + """Storing current optimizer state.""" + save_object = self.get_state() + with open(checkpoint_path, "wb") as f: + pickle.dump(save_object, f) + + def restore(self, checkpoint_path: str): + """Restoring current optimizer state.""" + with open(checkpoint_path, "rb") as f: + save_object = pickle.load(f) + + if isinstance(save_object, dict): + self.set_state(save_object) + else: + # Backwards compatibility + ( + self.optimizer, + self._buffered_trial_results, + self._total_random_search_trials, + self._config_counter, + self._points_to_evaluate, + ) = save_object + + @staticmethod + def convert_search_space(spec: Dict, join: bool = False) -> Dict: + resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec) + + if grid_vars: + raise ValueError( + "Grid search parameters cannot be automatically converted " + "to a BayesOpt search space." + ) + + # Flatten and resolve again after checking for grid search. + spec = flatten_dict(spec, prevent_delimiter=True) + resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec) + + def resolve_value(domain: Domain) -> Tuple[float, float]: + sampler = domain.get_sampler() + if isinstance(sampler, Quantized): + logger.warning( + "BayesOpt search does not support quantization. " + "Dropped quantization." + ) + sampler = sampler.get_sampler() + + if isinstance(domain, Float): + if domain.sampler is not None and not isinstance( + domain.sampler, Uniform + ): + logger.warning( + "BayesOpt does not support specific sampling methods. " + "The {} sampler will be dropped.".format(sampler) + ) + return (domain.lower, domain.upper) + + raise ValueError( + "BayesOpt does not support parameters of type " + "`{}`".format(type(domain).__name__) + ) + + # Parameter name is e.g. "a/b/c" for nested dicts + bounds = {"/".join(path): resolve_value(domain) for path, domain in domain_vars} + + if join: + spec.update(bounds) + bounds = spec + + return bounds diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/bohb/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/search/bohb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..40068b1562adcd327627c8b8f641079c95364ccc --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/bohb/__init__.py @@ -0,0 +1,3 @@ +from ray.tune.search.bohb.bohb_search import BOHB, TuneBOHB + +__all__ = ["BOHB", "TuneBOHB"] diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/bohb/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/bohb/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de74d20abf9244404483b69ad23cfedb83caed1d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/bohb/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/bohb/__pycache__/bohb_search.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/bohb/__pycache__/bohb_search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b81b8b8339ecfeb4e2318b9a3dc4afcccf9b8c9d Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/bohb/__pycache__/bohb_search.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/bohb/bohb_search.py b/venv/lib/python3.10/site-packages/ray/tune/search/bohb/bohb_search.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa701b700f7f5adf1eed308364725c779c5466d --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/bohb/bohb_search.py @@ -0,0 +1,383 @@ +"""BOHB (Bayesian Optimization with HyperBand)""" + +import copy +import logging +import math +from typing import Dict, List, Optional, Union + +# use cloudpickle instead of pickle to make BOHB obj +# pickleable +from ray import cloudpickle +from ray.tune.result import DEFAULT_METRIC +from ray.tune.search import ( + UNDEFINED_METRIC_MODE, + UNDEFINED_SEARCH_SPACE, + UNRESOLVED_SEARCH_SPACE, + Searcher, +) +from ray.tune.search.sample import ( + Categorical, + Domain, + Float, + Integer, + LogUniform, + Normal, + Quantized, + Uniform, +) +from ray.tune.search.variant_generator import parse_spec_vars +from ray.tune.utils.util import flatten_dict, unflatten_list_dict + +try: + import ConfigSpace + from hpbandster.optimizers.config_generators.bohb import BOHB +except ImportError: + BOHB = ConfigSpace = None + +logger = logging.getLogger(__name__) + + +class _BOHBJobWrapper: + """Mock object for HpBandSter to process.""" + + def __init__(self, loss: float, budget: float, config: Dict): + self.result = {"loss": loss} + self.kwargs = {"budget": budget, "config": config.copy()} + self.exception = None + + +class TuneBOHB(Searcher): + """BOHB suggestion component. + + + Requires HpBandSter and ConfigSpace to be installed. You can install + HpBandSter and ConfigSpace with: ``pip install hpbandster ConfigSpace``. + + This should be used in conjunction with HyperBandForBOHB. + + Args: + space: Continuous ConfigSpace search space. + Parameters will be sampled from this space which will be used + to run trials. + bohb_config: configuration for HpBandSter BOHB algorithm + metric: The training result objective value attribute. If None + but a mode was passed, the anonymous metric `_metric` will be used + per default. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. + points_to_evaluate: Initial parameter suggestions to be run + first. This is for when you already have some good parameters + you want to run first to help the algorithm make better suggestions + for future parameters. Needs to be a list of dicts containing the + configurations. + seed: Optional random seed to initialize the random number + generator. Setting this should lead to identical initial + configurations at each run. + max_concurrent: Number of maximum concurrent trials. + If this Searcher is used in a ``ConcurrencyLimiter``, the + ``max_concurrent`` value passed to it will override the + value passed here. Set to <= 0 for no limit on concurrency. + + Tune automatically converts search spaces to TuneBOHB's format: + + .. code-block:: python + + config = { + "width": tune.uniform(0, 20), + "height": tune.uniform(-100, 100), + "activation": tune.choice(["relu", "tanh"]) + } + + algo = TuneBOHB(metric="mean_loss", mode="min") + bohb = HyperBandForBOHB( + time_attr="training_iteration", + metric="mean_loss", + mode="min", + max_t=100) + run(my_trainable, config=config, scheduler=bohb, search_alg=algo) + + If you would like to pass the search space manually, the code would + look like this: + + .. code-block:: python + + import ConfigSpace as CS + + config_space = CS.ConfigurationSpace() + config_space.add_hyperparameter( + CS.UniformFloatHyperparameter("width", lower=0, upper=20)) + config_space.add_hyperparameter( + CS.UniformFloatHyperparameter("height", lower=-100, upper=100)) + config_space.add_hyperparameter( + CS.CategoricalHyperparameter( + name="activation", choices=["relu", "tanh"])) + + algo = TuneBOHB( + config_space, metric="mean_loss", mode="min") + bohb = HyperBandForBOHB( + time_attr="training_iteration", + metric="mean_loss", + mode="min", + max_t=100) + run(my_trainable, scheduler=bohb, search_alg=algo) + + """ + + def __init__( + self, + space: Optional[Union[Dict, "ConfigSpace.ConfigurationSpace"]] = None, + bohb_config: Optional[Dict] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + points_to_evaluate: Optional[List[Dict]] = None, + seed: Optional[int] = None, + max_concurrent: int = 0, + ): + assert ( + BOHB is not None + ), """HpBandSter must be installed! + You can install HpBandSter with the command: + `pip install hpbandster ConfigSpace`.""" + if mode: + assert mode in ["min", "max"], "`mode` must be 'min' or 'max'." + self.trial_to_params = {} + self._metric = metric + + self._bohb_config = bohb_config + + if isinstance(space, dict) and space: + resolved_vars, domain_vars, grid_vars = parse_spec_vars(space) + if domain_vars or grid_vars: + logger.warning( + UNRESOLVED_SEARCH_SPACE.format(par="space", cls=type(self)) + ) + space = self.convert_search_space(space) + + self._space = space + self._seed = seed + + self.running = set() + self.paused = set() + + self._max_concurrent = max_concurrent + self._points_to_evaluate = points_to_evaluate + + super(TuneBOHB, self).__init__( + metric=self._metric, + mode=mode, + ) + + if self._space: + self._setup_bohb() + + def set_max_concurrency(self, max_concurrent: int) -> bool: + self._max_concurrent = max_concurrent + return True + + def _setup_bohb(self): + from hpbandster.optimizers.config_generators.bohb import BOHB + + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + if self._mode == "max": + self._metric_op = -1.0 + elif self._mode == "min": + self._metric_op = 1.0 + + if self._seed is not None: + self._space.seed(self._seed) + + self.running = set() + self.paused = set() + + bohb_config = self._bohb_config or {} + self.bohber = BOHB(self._space, **bohb_config) + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ) -> bool: + if self._space: + return False + space = self.convert_search_space(config) + self._space = space + + if metric: + self._metric = metric + if mode: + self._mode = mode + + self._setup_bohb() + return True + + def suggest(self, trial_id: str) -> Optional[Dict]: + if not self._space: + raise RuntimeError( + UNDEFINED_SEARCH_SPACE.format( + cls=self.__class__.__name__, space="space" + ) + ) + + if not self._metric or not self._mode: + raise RuntimeError( + UNDEFINED_METRIC_MODE.format( + cls=self.__class__.__name__, metric=self._metric, mode=self._mode + ) + ) + + max_concurrent = ( + self._max_concurrent if self._max_concurrent > 0 else float("inf") + ) + if len(self.running) >= max_concurrent: + return None + + if self._points_to_evaluate: + config = self._points_to_evaluate.pop(0) + else: + # This parameter is not used in hpbandster implementation. + config, _ = self.bohber.get_config(None) + self.trial_to_params[trial_id] = copy.deepcopy(config) + self.running.add(trial_id) + return unflatten_list_dict(config) + + def on_trial_result(self, trial_id: str, result: Dict): + if trial_id not in self.paused: + self.running.add(trial_id) + if "hyperband_info" not in result: + logger.warning( + "BOHB Info not detected in result. Are you using " + "HyperBandForBOHB as a scheduler?" + ) + elif "budget" in result.get("hyperband_info", {}): + hbs_wrapper = self.to_wrapper(trial_id, result) + self.bohber.new_result(hbs_wrapper) + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ): + del self.trial_to_params[trial_id] + self.paused.discard(trial_id) + self.running.discard(trial_id) + + def to_wrapper(self, trial_id: str, result: Dict) -> _BOHBJobWrapper: + return _BOHBJobWrapper( + self._metric_op * result[self.metric], + result["hyperband_info"]["budget"], + self.trial_to_params[trial_id], + ) + + # BOHB Specific. + # TODO(team-ml): Refactor alongside HyperBandForBOHB + def on_pause(self, trial_id: str): + self.paused.add(trial_id) + self.running.discard(trial_id) + + def on_unpause(self, trial_id: str): + self.paused.discard(trial_id) + self.running.add(trial_id) + + @staticmethod + def convert_search_space(spec: Dict) -> "ConfigSpace.ConfigurationSpace": + resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec) + + if grid_vars: + raise ValueError( + "Grid search parameters cannot be automatically converted " + "to a TuneBOHB search space." + ) + + # Flatten and resolve again after checking for grid search. + spec = flatten_dict(spec, prevent_delimiter=True) + resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec) + + def resolve_value( + par: str, domain: Domain + ) -> ConfigSpace.hyperparameters.Hyperparameter: + quantize = None + + sampler = domain.get_sampler() + if isinstance(sampler, Quantized): + quantize = sampler.q + sampler = sampler.sampler + + if isinstance(domain, Float): + if isinstance(sampler, LogUniform): + lower = domain.lower + upper = domain.upper + if quantize: + lower = math.ceil(domain.lower / quantize) * quantize + upper = math.floor(domain.upper / quantize) * quantize + return ConfigSpace.UniformFloatHyperparameter( + par, lower=lower, upper=upper, q=quantize, log=True + ) + elif isinstance(sampler, Uniform): + lower = domain.lower + upper = domain.upper + if quantize: + lower = math.ceil(domain.lower / quantize) * quantize + upper = math.floor(domain.upper / quantize) * quantize + return ConfigSpace.UniformFloatHyperparameter( + par, lower=lower, upper=upper, q=quantize, log=False + ) + elif isinstance(sampler, Normal): + return ConfigSpace.hyperparameters.NormalFloatHyperparameter( + par, mu=sampler.mean, sigma=sampler.sd, q=quantize, log=False + ) + + elif isinstance(domain, Integer): + if isinstance(sampler, LogUniform): + lower = domain.lower + upper = domain.upper + if quantize: + lower = math.ceil(domain.lower / quantize) * quantize + upper = math.floor(domain.upper / quantize) * quantize + else: + # Tune search space integers are exclusive + upper -= 1 + return ConfigSpace.UniformIntegerHyperparameter( + par, lower=lower, upper=upper, q=quantize, log=True + ) + elif isinstance(sampler, Uniform): + lower = domain.lower + upper = domain.upper + if quantize: + lower = math.ceil(domain.lower / quantize) * quantize + upper = math.floor(domain.upper / quantize) * quantize + else: + # Tune search space integers are exclusive + upper -= 1 + return ConfigSpace.UniformIntegerHyperparameter( + par, lower=lower, upper=upper, q=quantize, log=False + ) + + elif isinstance(domain, Categorical): + if isinstance(sampler, Uniform): + return ConfigSpace.CategoricalHyperparameter( + par, choices=domain.categories + ) + + raise ValueError( + "TuneBOHB does not support parameters of type " + "`{}` with samplers of type `{}`".format( + type(domain).__name__, type(domain.sampler).__name__ + ) + ) + + cs = ConfigSpace.ConfigurationSpace() + for path, domain in domain_vars: + par = "/".join(str(p) for p in path) + value = resolve_value(par, domain) + cs.add_hyperparameter(value) + + return cs + + def save(self, checkpoint_path: str): + save_object = self.__dict__ + with open(checkpoint_path, "wb") as outputFile: + cloudpickle.dump(save_object, outputFile) + + def restore(self, checkpoint_path: str): + with open(checkpoint_path, "rb") as inputFile: + save_object = cloudpickle.load(inputFile) + self.__dict__.update(save_object) diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/concurrency_limiter.py b/venv/lib/python3.10/site-packages/ray/tune/search/concurrency_limiter.py new file mode 100644 index 0000000000000000000000000000000000000000..847db982ea881a0079dd78cdf8b4689ac1c02401 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/concurrency_limiter.py @@ -0,0 +1,176 @@ +import copy +import logging +from typing import Dict, List, Optional + +from ray.tune.search.searcher import Searcher +from ray.tune.search.util import _set_search_properties_backwards_compatible +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + + +@PublicAPI +class ConcurrencyLimiter(Searcher): + """A wrapper algorithm for limiting the number of concurrent trials. + + Certain Searchers have their own internal logic for limiting + the number of concurrent trials. If such a Searcher is passed to a + ``ConcurrencyLimiter``, the ``max_concurrent`` of the + ``ConcurrencyLimiter`` will override the ``max_concurrent`` value + of the Searcher. The ``ConcurrencyLimiter`` will then let the + Searcher's internal logic take over. + + Args: + searcher: Searcher object that the + ConcurrencyLimiter will manage. + max_concurrent: Maximum concurrent samples from the underlying + searcher. + batch: Whether to wait for all concurrent samples + to finish before updating the underlying searcher. + + Example: + + .. code-block:: python + + from ray.tune.search import ConcurrencyLimiter + search_alg = HyperOptSearch(metric="accuracy") + search_alg = ConcurrencyLimiter(search_alg, max_concurrent=2) + tuner = tune.Tuner( + trainable, + tune_config=tune.TuneConfig( + search_alg=search_alg + ), + ) + tuner.fit() + """ + + def __init__(self, searcher: Searcher, max_concurrent: int, batch: bool = False): + assert type(max_concurrent) is int and max_concurrent > 0 + self.searcher = searcher + self.max_concurrent = max_concurrent + self.batch = batch + self.live_trials = set() + self.num_unfinished_live_trials = 0 + self.cached_results = {} + self._limit_concurrency = True + + if not isinstance(searcher, Searcher): + raise RuntimeError( + f"The `ConcurrencyLimiter` only works with `Searcher` " + f"objects (got {type(searcher)}). Please try to pass " + f"`max_concurrent` to the search generator directly." + ) + + self._set_searcher_max_concurrency() + + super(ConcurrencyLimiter, self).__init__( + metric=self.searcher.metric, mode=self.searcher.mode + ) + + def _set_searcher_max_concurrency(self): + # If the searcher has special logic for handling max concurrency, + # we do not do anything inside the ConcurrencyLimiter + self._limit_concurrency = not self.searcher.set_max_concurrency( + self.max_concurrent + ) + + def set_max_concurrency(self, max_concurrent: int) -> bool: + # Determine if this behavior is acceptable, or if it should + # raise an exception. + self.max_concurrent = max_concurrent + return True + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ) -> bool: + self._set_searcher_max_concurrency() + return _set_search_properties_backwards_compatible( + self.searcher.set_search_properties, metric, mode, config, **spec + ) + + def suggest(self, trial_id: str) -> Optional[Dict]: + if not self._limit_concurrency: + return self.searcher.suggest(trial_id) + + assert ( + trial_id not in self.live_trials + ), f"Trial ID {trial_id} must be unique: already found in set." + if len(self.live_trials) >= self.max_concurrent: + logger.debug( + f"Not providing a suggestion for {trial_id} due to " + "concurrency limit: %s/%s.", + len(self.live_trials), + self.max_concurrent, + ) + return + + suggestion = self.searcher.suggest(trial_id) + if suggestion not in (None, Searcher.FINISHED): + self.live_trials.add(trial_id) + self.num_unfinished_live_trials += 1 + return suggestion + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ): + if not self._limit_concurrency: + return self.searcher.on_trial_complete(trial_id, result=result, error=error) + + if trial_id not in self.live_trials: + return + elif self.batch: + self.cached_results[trial_id] = (result, error) + self.num_unfinished_live_trials -= 1 + if self.num_unfinished_live_trials <= 0: + # Update the underlying searcher once the + # full batch is completed. + for trial_id, (result, error) in self.cached_results.items(): + self.searcher.on_trial_complete( + trial_id, result=result, error=error + ) + self.live_trials.remove(trial_id) + self.cached_results = {} + self.num_unfinished_live_trials = 0 + else: + return + else: + self.searcher.on_trial_complete(trial_id, result=result, error=error) + self.live_trials.remove(trial_id) + self.num_unfinished_live_trials -= 1 + + def on_trial_result(self, trial_id: str, result: Dict) -> None: + self.searcher.on_trial_result(trial_id, result) + + def add_evaluated_point( + self, + parameters: Dict, + value: float, + error: bool = False, + pruned: bool = False, + intermediate_values: Optional[List[float]] = None, + ): + return self.searcher.add_evaluated_point( + parameters, value, error, pruned, intermediate_values + ) + + def get_state(self) -> Dict: + state = self.__dict__.copy() + del state["searcher"] + return copy.deepcopy(state) + + def set_state(self, state: Dict): + self.__dict__.update(state) + + def save(self, checkpoint_path: str): + self.searcher.save(checkpoint_path) + + def restore(self, checkpoint_path: str): + self.searcher.restore(checkpoint_path) + + # BOHB Specific. + # TODO(team-ml): Refactor alongside HyperBandForBOHB + def on_pause(self, trial_id: str): + self.searcher.on_pause(trial_id) + + def on_unpause(self, trial_id: str): + self.searcher.on_unpause(trial_id) diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/hebo/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/search/hebo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..66e5c5675bb22e2d013a89b994146192763ed1b3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/hebo/__init__.py @@ -0,0 +1,3 @@ +from ray.tune.search.hebo.hebo_search import HEBOSearch + +__all__ = ["HEBOSearch"] diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/hebo/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/hebo/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a039128bdd96ecfdd26de34c3e29e9aeccd86cae Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/hebo/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/hebo/__pycache__/hebo_search.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/hebo/__pycache__/hebo_search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b158e949ea8b6b9e286367b9e2874d54cff47ac6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/hebo/__pycache__/hebo_search.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/hebo/hebo_search.py b/venv/lib/python3.10/site-packages/ray/tune/search/hebo/hebo_search.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f130c5d514461364ed566ec5ed2004abb01975 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/hebo/hebo_search.py @@ -0,0 +1,466 @@ +import logging +import pickle +from typing import Dict, List, Optional, Union + +import numpy as np +import pandas as pd + +from ray.tune.result import DEFAULT_METRIC +from ray.tune.search import ( + UNDEFINED_METRIC_MODE, + UNDEFINED_SEARCH_SPACE, + UNRESOLVED_SEARCH_SPACE, + Searcher, +) +from ray.tune.search.sample import ( + Categorical, + Domain, + Float, + Integer, + LogUniform, + Quantized, + Uniform, +) +from ray.tune.search.variant_generator import parse_spec_vars +from ray.tune.utils.util import is_nan_or_inf, unflatten_dict, validate_warmstart + +try: # Python 3 only -- needed for lint test. + import hebo + import torch # hebo has torch as a dependency +except ImportError: + hebo = None + +logger = logging.getLogger(__name__) + +SPACE_ERROR_MESSAGE = ( + "Space must be either a HEBO DesignSpace object" + "or a dictionary with ONLY tune search spaces." +) + + +class HEBOSearch(Searcher): + """Uses HEBO (Heteroscedastic Evolutionary Bayesian Optimization) + to optimize hyperparameters. + + HEBO is a cutting edge black-box optimization framework created + by Huawei's Noah Ark. More info can be found here: + https://github.com/huawei-noah/HEBO/tree/master/HEBO. + + `space` can either be a HEBO's `DesignSpace` object or a dict of Tune + search spaces. + + Please note that the first few trials will be random and used + to kickstart the search process. In order to achieve good results, + we recommend setting the number of trials to at least 16. + + Maximum number of concurrent trials is determined by ``max_concurrent`` + argument. Trials will be done in batches of ``max_concurrent`` trials. + If this Searcher is used in a ``ConcurrencyLimiter``, the + ``max_concurrent`` value passed to it will override the value passed + here. + + Args: + space: A dict mapping parameter names to Tune search spaces or a + HEBO DesignSpace object. + metric: The training result objective value attribute. If None + but a mode was passed, the anonymous metric `_metric` will be used + per default. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. + points_to_evaluate: Initial parameter suggestions to be run + first. This is for when you already have some good parameters + you want to run first to help the algorithm make better suggestions + for future parameters. Needs to be a list of dicts containing the + configurations. + evaluated_rewards: If you have previously evaluated the + parameters passed in as points_to_evaluate you can avoid + re-running those trials by passing in the reward attributes + as a list so the optimiser can be told the results without + needing to re-compute the trial. Must be the same length as + points_to_evaluate. + random_state_seed: Seed for reproducible + results. Defaults to None. Please note that setting this to a value + will change global random states for `numpy` and `torch` + on initalization and loading from checkpoint. + max_concurrent: Number of maximum concurrent trials. + If this Searcher is used in a ``ConcurrencyLimiter``, the + ``max_concurrent`` value passed to it will override the + value passed here. + **kwargs: The keyword arguments will be passed to `HEBO()``. + + Tune automatically converts search spaces to HEBO's format: + + .. code-block:: python + + from ray import tune + from ray.tune.search.hebo import HEBOSearch + + config = { + "width": tune.uniform(0, 20), + "height": tune.uniform(-100, 100) + } + + hebo = HEBOSearch(metric="mean_loss", mode="min") + tuner = tune.Tuner( + trainable_function, + tune_config=tune.TuneConfig( + search_alg=hebo + ), + param_space=config + ) + tuner.fit() + + Alternatively, you can pass a HEBO `DesignSpace` object manually to the + Searcher: + + .. code-block:: python + + from ray import tune + from ray.tune.search.hebo import HEBOSearch + from hebo.design_space.design_space import DesignSpace + + space_config = [ + {'name' : 'width', 'type' : 'num', 'lb' : 0, 'ub' : 20}, + {'name' : 'height', 'type' : 'num', 'lb' : -100, 'ub' : 100}, + ] + space = DesignSpace().parse(space_config) + + hebo = HEBOSearch(space, metric="mean_loss", mode="min") + tuner = tune.Tuner( + trainable_function, + tune_config=tune.TuneConfig( + search_alg=hebo + ) + ) + tuner.fit() + + """ + + def __init__( + self, + space: Optional[ + Union[Dict, "hebo.design_space.design_space.DesignSpace"] + ] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + points_to_evaluate: Optional[List[Dict]] = None, + evaluated_rewards: Optional[List] = None, + random_state_seed: Optional[int] = None, + max_concurrent: int = 8, + **kwargs, + ): + assert hebo is not None, ( + "HEBO must be installed! You can install HEBO with" + " the command: `pip install 'HEBO>=0.2.0'`." + "This error may also be caused if HEBO" + " dependencies have bad versions. Try updating HEBO" + " first." + ) + if mode: + assert mode in ["min", "max"], "`mode` must be 'min' or 'max'." + assert ( + isinstance(max_concurrent, int) and max_concurrent >= 1 + ), "`max_concurrent` must be an integer and at least 1." + if random_state_seed is not None: + assert isinstance( + random_state_seed, int + ), "random_state_seed must be None or int, got '{}'.".format( + type(random_state_seed) + ) + super(HEBOSearch, self).__init__(metric=metric, mode=mode) + + if isinstance(space, dict) and space: + resolved_vars, domain_vars, grid_vars = parse_spec_vars(space) + if resolved_vars: + raise TypeError(SPACE_ERROR_MESSAGE) + if domain_vars or grid_vars: + logger.warning( + UNRESOLVED_SEARCH_SPACE.format(par="space", cls=type(self)) + ) + space = self.convert_search_space(space) + elif space is not None and not isinstance( + space, hebo.design_space.design_space.DesignSpace + ): + raise TypeError(SPACE_ERROR_MESSAGE + " Got {}.".format(type(space))) + + self._hebo_config = kwargs + self._random_state_seed = random_state_seed + self._space = space + self._points_to_evaluate = points_to_evaluate + self._evaluated_rewards = evaluated_rewards + self._initial_points = [] + self._live_trial_mapping = {} + + self._max_concurrent = max_concurrent + self._suggestions_cache = [] + self._batch_filled = False + + self._opt = None + if space: + self._setup_optimizer() + + def set_max_concurrency(self, max_concurrent: int) -> bool: + self._max_concurrent = max_concurrent + return True + + def _setup_optimizer(self): + # HEBO internally minimizes, so "max" => -1 + if self._mode == "max": + self._metric_op = -1.0 + elif self._mode == "min": + self._metric_op = 1.0 + + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + if not isinstance(self._space, hebo.design_space.design_space.DesignSpace): + raise ValueError( + f"Invalid search space: {type(self._space)}. Either pass a " + f"valid search space to the `HEBOSearch` class or pass " + f"a `param_space` parameter to `tune.Tuner()`" + ) + + if self._space.num_paras <= 0: + raise ValueError( + "Got empty search space. Please make sure to pass " + "a valid search space with at least one parameter to " + "`HEBOSearch`" + ) + + if self._random_state_seed is not None: + np.random.seed(self._random_state_seed) + torch.random.manual_seed(self._random_state_seed) + + self._opt = hebo.optimizers.hebo.HEBO(space=self._space, **self._hebo_config) + + if self._points_to_evaluate: + validate_warmstart( + self._space.para_names, + self._points_to_evaluate, + self._evaluated_rewards, + ) + if self._evaluated_rewards: + self._opt.observe( + pd.DataFrame(self._points_to_evaluate), + np.array(self._evaluated_rewards) * self._metric_op, + ) + else: + self._initial_points = self._points_to_evaluate + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ) -> bool: + if self._opt: + return False + space = self.convert_search_space(config) + self._space = space + + if metric: + self._metric = metric + if mode: + self._mode = mode + + self._setup_optimizer() + return True + + def suggest(self, trial_id: str) -> Optional[Dict]: + if not self._opt: + raise RuntimeError( + UNDEFINED_SEARCH_SPACE.format( + cls=self.__class__.__name__, space="space" + ) + ) + + if not self._metric or not self._mode: + raise RuntimeError( + UNDEFINED_METRIC_MODE.format( + cls=self.__class__.__name__, metric=self._metric, mode=self._mode + ) + ) + + if not self._live_trial_mapping: + self._batch_filled = False + + if self._initial_points: + params = self._initial_points.pop(0) + suggestion = pd.DataFrame([params], index=[0]) + else: + if ( + self._batch_filled + or len(self._live_trial_mapping) >= self._max_concurrent + ): + return None + if not self._suggestions_cache: + suggestion = self._opt.suggest(n_suggestions=self._max_concurrent) + self._suggestions_cache = suggestion.to_dict("records") + params = self._suggestions_cache.pop(0) + suggestion = pd.DataFrame([params], index=[0]) + self._live_trial_mapping[trial_id] = suggestion + if len(self._live_trial_mapping) >= self._max_concurrent: + self._batch_filled = True + return unflatten_dict(params) + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ): + """Notification for the completion of trial. + + HEBO always minimizes.""" + + if result: + self._process_result(trial_id, result) + self._live_trial_mapping.pop(trial_id) + + def _process_result(self, trial_id: str, result: Dict): + trial_info = self._live_trial_mapping[trial_id] + if result and not is_nan_or_inf(result[self._metric]): + self._opt.observe( + trial_info, np.array([self._metric_op * result[self._metric]]) + ) + + def add_evaluated_point( + self, + parameters: Dict, + value: float, + error: bool = False, + pruned: bool = False, + intermediate_values: Optional[List[float]] = None, + ): + if intermediate_values: + logger.warning("HEBO doesn't use intermediate_values. Ignoring.") + if not error and not pruned: + self._opt.observe( + pd.DataFrame( + [ + { + k: v + for k, v in parameters.items() + if k in self._opt.space.para_names + } + ] + ), + np.array([value]) * self._metric_op, + ) + else: + logger.warning( + "Only non errored and non pruned points can be added to HEBO." + ) + + def save(self, checkpoint_path: str): + """Storing current optimizer state.""" + if self._random_state_seed is not None: + numpy_random_state = np.random.get_state() + torch_random_state = torch.get_rng_state() + else: + numpy_random_state = None + torch_random_state = None + save_object = self.__dict__.copy() + save_object["__numpy_random_state"] = numpy_random_state + save_object["__torch_random_state"] = torch_random_state + with open(checkpoint_path, "wb") as f: + pickle.dump(save_object, f) + + def restore(self, checkpoint_path: str): + """Restoring current optimizer state.""" + with open(checkpoint_path, "rb") as f: + save_object = pickle.load(f) + + if isinstance(save_object, dict): + numpy_random_state = save_object.pop("__numpy_random_state", None) + torch_random_state = save_object.pop("__torch_random_state", None) + self.__dict__.update(save_object) + else: + # Backwards compatibility + ( + self._opt, + self._initial_points, + numpy_random_state, + torch_random_state, + self._live_trial_mapping, + self._max_concurrent, + self._suggestions_cache, + self._space, + self._hebo_config, + self._batch_filled, + ) = save_object + if numpy_random_state is not None: + np.random.set_state(numpy_random_state) + if torch_random_state is not None: + torch.random.set_rng_state(torch_random_state) + + @staticmethod + def convert_search_space(spec: Dict, prefix: str = "") -> Dict: + resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec) + + params = [] + + if not domain_vars and not grid_vars: + return {} + + if grid_vars: + raise ValueError( + "Grid search parameters cannot be automatically converted " + "to a HEBO search space." + ) + + def resolve_value(par: str, domain: Domain): + sampler = domain.get_sampler() + if isinstance(sampler, Quantized): + logger.warning( + "HEBO search does not support quantization. " + "Dropped quantization." + ) + sampler = sampler.get_sampler() + + if isinstance(domain, Float): + if isinstance(sampler, LogUniform): + return { + "name": par, + "type": "pow", + "lb": domain.lower, + "ub": domain.upper, + } + elif isinstance(sampler, Uniform): + return { + "name": par, + "type": "num", + "lb": domain.lower, + "ub": domain.upper, + } + + elif isinstance(domain, Integer): + if isinstance(sampler, LogUniform): + return { + "name": par, + "type": "pow_int", + "lb": domain.lower, + "ub": domain.upper - 1, # Upper bound exclusive + } + elif isinstance(sampler, Uniform): + return { + "name": par, + "type": "int", + "lb": domain.lower, + "ub": domain.upper - 1, # Upper bound exclusive + } + elif isinstance(domain, Categorical): + return { + "name": par, + "type": "cat", + "categories": list(domain.categories), + } + + raise ValueError( + "HEBO does not support parameters of type " + "`{}` with samplers of type `{}`".format( + type(domain).__name__, type(domain.sampler).__name__ + ) + ) + + for path, domain in domain_vars: + par = "/".join([str(p) for p in ((prefix,) + path if prefix else path)]) + value = resolve_value(par, domain) + params.append(value) + + return hebo.design_space.design_space.DesignSpace().parse(params) diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3b142015f04bf2eec6b1be7e54d545621dfe2953 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/__init__.py @@ -0,0 +1,3 @@ +from ray.tune.search.hyperopt.hyperopt_search import HyperOptSearch + +__all__ = ["HyperOptSearch"] diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9d552572feb20162b2d4df7cc578a935579fb70 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/__pycache__/hyperopt_search.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/__pycache__/hyperopt_search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb681cc9860636e8e2d2718d7695e70fe6b3b30b Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/__pycache__/hyperopt_search.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/hyperopt_search.py b/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/hyperopt_search.py new file mode 100644 index 0000000000000000000000000000000000000000..d1d3f964acb7117fde438195ea5ba092ad1f4802 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/hyperopt/hyperopt_search.py @@ -0,0 +1,559 @@ +import copy +import logging +from functools import partial +from typing import Any, Dict, List, Optional + +import numpy as np + +# Use cloudpickle instead of pickle to make lambda funcs in HyperOpt pickleable +from ray import cloudpickle +from ray.tune.error import TuneError +from ray.tune.result import DEFAULT_METRIC +from ray.tune.search import ( + UNDEFINED_METRIC_MODE, + UNDEFINED_SEARCH_SPACE, + UNRESOLVED_SEARCH_SPACE, + Searcher, +) +from ray.tune.search.sample import ( + Categorical, + Domain, + Float, + Integer, + LogUniform, + Normal, + Quantized, + Uniform, +) +from ray.tune.search.variant_generator import assign_value, parse_spec_vars +from ray.tune.utils import flatten_dict + +try: + hyperopt_logger = logging.getLogger("hyperopt") + hyperopt_logger.setLevel(logging.WARNING) + import hyperopt as hpo + from hyperopt.pyll import Apply +except ImportError: + hpo = None + Apply = None + + +logger = logging.getLogger(__name__) + + +HYPEROPT_UNDEFINED_DETAILS = ( + " This issue can also come up with HyperOpt if your search space only " + "contains constant variables, which is not supported by HyperOpt. In that case, " + "don't pass any searcher or add sample variables to the search space." +) + + +class HyperOptSearch(Searcher): + """A wrapper around HyperOpt to provide trial suggestions. + + HyperOpt a Python library for serial and parallel optimization + over awkward search spaces, which may include real-valued, discrete, + and conditional dimensions. More info can be found at + http://hyperopt.github.io/hyperopt. + + HyperOptSearch uses the Tree-structured Parzen Estimators algorithm, + though it can be trivially extended to support any algorithm HyperOpt + supports. + + To use this search algorithm, you will need to install HyperOpt: + + .. code-block:: bash + + pip install -U hyperopt + + + Parameters: + space: HyperOpt configuration. Parameters will be sampled + from this configuration and will be used to override + parameters generated in the variant generation process. + metric: The training result objective value attribute. If None + but a mode was passed, the anonymous metric `_metric` will be used + per default. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. + points_to_evaluate: Initial parameter suggestions to be run + first. This is for when you already have some good parameters + you want to run first to help the algorithm make better suggestions + for future parameters. Needs to be a list of dicts containing the + configurations. + n_initial_points: number of random evaluations of the + objective function before starting to approximate it with + tree parzen estimators. Defaults to 20. + random_state_seed: seed for reproducible + results. Defaults to None. + gamma: parameter governing the tree parzen + estimators suggestion algorithm. Defaults to 0.25. + + Tune automatically converts search spaces to HyperOpt's format: + + .. code-block:: python + + config = { + 'width': tune.uniform(0, 20), + 'height': tune.uniform(-100, 100), + 'activation': tune.choice(["relu", "tanh"]) + } + + current_best_params = [{ + 'width': 10, + 'height': 0, + 'activation': "relu", + }] + + hyperopt_search = HyperOptSearch( + metric="mean_loss", mode="min", + points_to_evaluate=current_best_params) + + tuner = tune.Tuner( + trainable, + tune_config=tune.TuneConfig( + search_alg=hyperopt_search + ), + param_space=config + ) + tuner.fit() + + If you would like to pass the search space manually, the code would + look like this: + + .. code-block:: python + + space = { + 'width': hp.uniform('width', 0, 20), + 'height': hp.uniform('height', -100, 100), + 'activation': hp.choice("activation", ["relu", "tanh"]) + } + + current_best_params = [{ + 'width': 10, + 'height': 0, + 'activation': "relu", + }] + + hyperopt_search = HyperOptSearch( + space, metric="mean_loss", mode="min", + points_to_evaluate=current_best_params) + + tuner = tune.Tuner( + trainable, + tune_config=tune.TuneConfig( + search_alg=hyperopt_search + ), + ) + tuner.fit() + + """ + + def __init__( + self, + space: Optional[Dict] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + points_to_evaluate: Optional[List[Dict]] = None, + n_initial_points: int = 20, + random_state_seed: Optional[int] = None, + gamma: float = 0.25, + ): + assert ( + hpo is not None + ), "HyperOpt must be installed! Run `pip install hyperopt`." + if mode: + assert mode in ["min", "max"], "`mode` must be 'min' or 'max'." + super(HyperOptSearch, self).__init__( + metric=metric, + mode=mode, + ) + # hyperopt internally minimizes, so "max" => -1 + if mode == "max": + self.metric_op = -1.0 + elif mode == "min": + self.metric_op = 1.0 + + if n_initial_points is None: + self.algo = hpo.tpe.suggest + else: + self.algo = partial(hpo.tpe.suggest, n_startup_jobs=n_initial_points) + if gamma is not None: + self.algo = partial(self.algo, gamma=gamma) + + self._points_to_evaluate = copy.deepcopy(points_to_evaluate) + + self._live_trial_mapping = {} + self.rstate = np.random.RandomState(random_state_seed) + + self.domain = None + if isinstance(space, dict) and space: + resolved_vars, domain_vars, grid_vars = parse_spec_vars(space) + if domain_vars or grid_vars: + logger.warning( + UNRESOLVED_SEARCH_SPACE.format(par="space", cls=type(self)) + ) + space = self.convert_search_space(space) + self._space = space + self._setup_hyperopt() + + def _setup_hyperopt(self) -> None: + from hyperopt.fmin import generate_trials_to_calculate + + if not self._space: + raise RuntimeError( + UNDEFINED_SEARCH_SPACE.format( + cls=self.__class__.__name__, space="space" + ) + + HYPEROPT_UNDEFINED_DETAILS + ) + + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + if self._points_to_evaluate is None: + self._hpopt_trials = hpo.Trials() + self._points_to_evaluate = 0 + else: + assert isinstance(self._points_to_evaluate, (list, tuple)) + + for i in range(len(self._points_to_evaluate)): + config = self._points_to_evaluate[i] + self._convert_categories_to_indices(config) + # HyperOpt treats initial points as LIFO, reverse to get FIFO + self._points_to_evaluate = list(reversed(self._points_to_evaluate)) + self._hpopt_trials = generate_trials_to_calculate(self._points_to_evaluate) + self._hpopt_trials.refresh() + self._points_to_evaluate = len(self._points_to_evaluate) + + self.domain = hpo.Domain(lambda spc: spc, self._space) + + def _convert_categories_to_indices(self, config) -> None: + """Convert config parameters for categories into hyperopt-compatible + representations where instead the index of the category is expected.""" + + def _lookup(config_dict, space_dict, key): + if isinstance(config_dict[key], dict): + for k in config_dict[key]: + _lookup(config_dict[key], space_dict[key], k) + else: + if ( + key in space_dict + and isinstance(space_dict[key], hpo.base.pyll.Apply) + and space_dict[key].name == "switch" + ): + if len(space_dict[key].pos_args) > 0: + categories = [ + a.obj + for a in space_dict[key].pos_args[1:] + if a.name == "literal" + ] + try: + idx = categories.index(config_dict[key]) + except ValueError as exc: + msg = ( + f"Did not find category with value " + f"`{config_dict[key]}` in " + f"hyperopt parameter `{key}`. " + ) + + if isinstance(config_dict[key], int): + msg += ( + "In previous versions, a numerical " + "index was expected for categorical " + "values of `points_to_evaluate`, " + "but in ray>=1.2.0, the categorical " + "value is expected to be directly " + "provided. " + ) + + msg += "Please make sure the specified category is valid." + raise ValueError(msg) from exc + config_dict[key] = idx + + for k in config: + _lookup(config, self._space, k) + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ) -> bool: + if self.domain: + return False + space = self.convert_search_space(config) + self._space = space + + if metric: + self._metric = metric + if mode: + self._mode = mode + + self.metric_op = -1.0 if self._mode == "max" else 1.0 + + self._setup_hyperopt() + return True + + def suggest(self, trial_id: str) -> Optional[Dict]: + if not self.domain: + raise RuntimeError( + UNDEFINED_SEARCH_SPACE.format( + cls=self.__class__.__name__, space="space" + ) + + HYPEROPT_UNDEFINED_DETAILS + ) + if not self._metric or not self._mode: + raise RuntimeError( + UNDEFINED_METRIC_MODE.format( + cls=self.__class__.__name__, metric=self._metric, mode=self._mode + ) + ) + + if self._points_to_evaluate > 0: + using_point_to_evaluate = True + new_trial = self._hpopt_trials.trials[self._points_to_evaluate - 1] + self._points_to_evaluate -= 1 + else: + using_point_to_evaluate = False + new_ids = self._hpopt_trials.new_trial_ids(1) + self._hpopt_trials.refresh() + + # Get new suggestion from Hyperopt + new_trials = self.algo( + new_ids, + self.domain, + self._hpopt_trials, + self.rstate.randint(2**31 - 1), + ) + self._hpopt_trials.insert_trial_docs(new_trials) + self._hpopt_trials.refresh() + new_trial = new_trials[0] + self._live_trial_mapping[trial_id] = (new_trial["tid"], new_trial) + + # Taken from HyperOpt.base.evaluate + config = hpo.base.spec_from_misc(new_trial["misc"]) + + # We have to flatten nested spaces here so parameter names match + config = flatten_dict(config, flatten_list=True) + + ctrl = hpo.base.Ctrl(self._hpopt_trials, current_trial=new_trial) + memo = self.domain.memo_from_config(config) + hpo.utils.use_obj_for_literal_in_memo( + self.domain.expr, ctrl, hpo.base.Ctrl, memo + ) + + try: + suggested_config = hpo.pyll.rec_eval( + self.domain.expr, + memo=memo, + print_node_on_error=self.domain.rec_eval_print_node_on_error, + ) + except (AssertionError, TypeError) as e: + if using_point_to_evaluate and ( + isinstance(e, AssertionError) or "GarbageCollected" in str(e) + ): + raise ValueError( + "HyperOpt encountered a GarbageCollected switch argument. " + "Usually this is caused by a config in " + "`points_to_evaluate` " + "missing a key present in `space`. Ensure that " + "`points_to_evaluate` contains " + "all non-constant keys from `space`.\n" + "Config from `points_to_evaluate`: " + f"{config}\n" + "HyperOpt search space: " + f"{self._space}" + ) from e + raise e + return copy.deepcopy(suggested_config) + + def on_trial_result(self, trial_id: str, result: Dict) -> None: + ho_trial = self._get_hyperopt_trial(trial_id) + if ho_trial is None: + return + now = hpo.utils.coarse_utcnow() + ho_trial["book_time"] = now + ho_trial["refresh_time"] = now + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ) -> None: + """Notification for the completion of trial. + + The result is internally negated when interacting with HyperOpt + so that HyperOpt can "maximize" this value, as it minimizes on default. + """ + ho_trial = self._get_hyperopt_trial(trial_id) + if ho_trial is None: + return + ho_trial["refresh_time"] = hpo.utils.coarse_utcnow() + if error: + ho_trial["state"] = hpo.base.JOB_STATE_ERROR + ho_trial["misc"]["error"] = (str(TuneError), "Tune Error") + self._hpopt_trials.refresh() + elif result: + self._process_result(trial_id, result) + del self._live_trial_mapping[trial_id] + + def _process_result(self, trial_id: str, result: Dict) -> None: + ho_trial = self._get_hyperopt_trial(trial_id) + if not ho_trial: + return + ho_trial["refresh_time"] = hpo.utils.coarse_utcnow() + + ho_trial["state"] = hpo.base.JOB_STATE_DONE + hp_result = self._to_hyperopt_result(result) + ho_trial["result"] = hp_result + self._hpopt_trials.refresh() + + def _to_hyperopt_result(self, result: Dict) -> Dict: + try: + return {"loss": self.metric_op * result[self.metric], "status": "ok"} + except KeyError as e: + raise RuntimeError( + f"Hyperopt expected to see the metric `{self.metric}` in the " + f"last result, but it was not found. To fix this, make " + f"sure your call to `tune.report` or your return value of " + f"your trainable class `step()` contains the above metric " + f"as a key." + ) from e + + def _get_hyperopt_trial(self, trial_id: str) -> Optional[Dict]: + if trial_id not in self._live_trial_mapping: + return + hyperopt_tid = self._live_trial_mapping[trial_id][0] + return [t for t in self._hpopt_trials.trials if t["tid"] == hyperopt_tid][0] + + def get_state(self) -> Dict: + return { + "hyperopt_trials": self._hpopt_trials, + "rstate": self.rstate.get_state(), + } + + def set_state(self, state: Dict) -> None: + self._hpopt_trials = state["hyperopt_trials"] + self.rstate.set_state(state["rstate"]) + + def save(self, checkpoint_path: str) -> None: + save_object = self.__dict__.copy() + save_object["__rstate"] = self.rstate.get_state() + with open(checkpoint_path, "wb") as f: + cloudpickle.dump(save_object, f) + + def restore(self, checkpoint_path: str) -> None: + with open(checkpoint_path, "rb") as f: + save_object = cloudpickle.load(f) + + if "__rstate" not in save_object: + # Backwards compatibility + self.set_state(save_object) + else: + self.rstate.set_state(save_object.pop("__rstate")) + self.__dict__.update(save_object) + + @staticmethod + def convert_search_space(spec: Dict, prefix: str = "") -> Dict: + spec = copy.deepcopy(spec) + resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec) + + if not domain_vars and not grid_vars: + return {} + + if grid_vars: + raise ValueError( + "Grid search parameters cannot be automatically converted " + "to a HyperOpt search space." + ) + + def resolve_value(par: str, domain: Domain) -> Any: + quantize = None + + sampler = domain.get_sampler() + if isinstance(sampler, Quantized): + quantize = sampler.q + sampler = sampler.sampler + + if isinstance(domain, Float): + if isinstance(sampler, LogUniform): + if quantize: + return hpo.hp.qloguniform( + par, np.log(domain.lower), np.log(domain.upper), quantize + ) + return hpo.hp.loguniform( + par, np.log(domain.lower), np.log(domain.upper) + ) + elif isinstance(sampler, Uniform): + if quantize: + return hpo.hp.quniform( + par, domain.lower, domain.upper, quantize + ) + return hpo.hp.uniform(par, domain.lower, domain.upper) + elif isinstance(sampler, Normal): + if quantize: + return hpo.hp.qnormal(par, sampler.mean, sampler.sd, quantize) + return hpo.hp.normal(par, sampler.mean, sampler.sd) + + elif isinstance(domain, Integer): + if isinstance(sampler, LogUniform): + if quantize: + return hpo.base.pyll.scope.int( + hpo.hp.qloguniform( + par, + np.log(domain.lower), + np.log(domain.upper), + quantize, + ) + ) + return hpo.base.pyll.scope.int( + hpo.hp.qloguniform( + par, np.log(domain.lower), np.log(domain.upper - 1), 1.0 + ) + ) + elif isinstance(sampler, Uniform): + if quantize: + return hpo.base.pyll.scope.int( + hpo.hp.quniform( + par, domain.lower, domain.upper - 1, quantize + ) + ) + return hpo.hp.uniformint(par, domain.lower, high=domain.upper - 1) + elif isinstance(domain, Categorical): + if isinstance(sampler, Uniform): + return hpo.hp.choice( + par, + [ + ( + HyperOptSearch.convert_search_space( + category, prefix=par + ) + if isinstance(category, dict) + else ( + HyperOptSearch.convert_search_space( + dict(enumerate(category)), prefix=f"{par}/{i}" + ) + if isinstance(category, list) + and len(category) > 0 + and isinstance(category[0], Domain) + else ( + resolve_value(f"{par}/{i}", category) + if isinstance(category, Domain) + else category + ) + ) + ) + for i, category in enumerate(domain.categories) + ], + ) + + raise ValueError( + "HyperOpt does not support parameters of type " + "`{}` with samplers of type `{}`".format( + type(domain).__name__, type(domain.sampler).__name__ + ) + ) + + for path, domain in domain_vars: + par = "/".join([str(p) for p in ((prefix,) + path if prefix else path)]) + value = resolve_value(par, domain) + assign_value(spec, path, value) + + return spec diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..da69e05d07ddabd6dba42739a3173edb1befa752 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/__init__.py @@ -0,0 +1,3 @@ +from ray.tune.search.nevergrad.nevergrad_search import NevergradSearch + +__all__ = ["NevergradSearch"] diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e53d6f117877bde944a2d760c447d3c7e31589a7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/__pycache__/nevergrad_search.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/__pycache__/nevergrad_search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70e1d35223d8c33fbfc8ec886832925819506012 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/__pycache__/nevergrad_search.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/nevergrad_search.py b/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/nevergrad_search.py new file mode 100644 index 0000000000000000000000000000000000000000..e26c9de2fe25cf2b0c6f0c60ef0641aed04adc39 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/nevergrad/nevergrad_search.py @@ -0,0 +1,374 @@ +import inspect +import logging +import math +import pickle +from typing import Dict, List, Optional, Sequence, Type, Union + +from ray.tune.result import DEFAULT_METRIC +from ray.tune.search import ( + UNDEFINED_METRIC_MODE, + UNDEFINED_SEARCH_SPACE, + UNRESOLVED_SEARCH_SPACE, + Searcher, +) +from ray.tune.search.sample import ( + Categorical, + Domain, + Float, + Integer, + LogUniform, + Quantized, +) +from ray.tune.search.variant_generator import parse_spec_vars +from ray.tune.utils.util import flatten_dict, unflatten_dict + +try: + import nevergrad as ng + from nevergrad.optimization import Optimizer + from nevergrad.optimization.base import ConfiguredOptimizer + + Parameter = ng.p.Parameter +except ImportError: + ng = None + Optimizer = None + ConfiguredOptimizer = None + Parameter = None + +logger = logging.getLogger(__name__) + + +class NevergradSearch(Searcher): + """Uses Nevergrad to optimize hyperparameters. + + Nevergrad is an open source tool from Facebook for derivative free + optimization. More info can be found at: + https://github.com/facebookresearch/nevergrad. + + You will need to install Nevergrad via the following command: + + .. code-block:: bash + + $ pip install nevergrad + + Parameters: + optimizer: Optimizer class provided from Nevergrad. + See here for available optimizers: + https://facebookresearch.github.io/nevergrad/optimizers_ref.html#optimizers + This can also be an instance of a `ConfiguredOptimizer`. See the + section on configured optimizers in the above link. + optimizer_kwargs: Kwargs passed in when instantiating the `optimizer` + space: Nevergrad parametrization + to be passed to optimizer on instantiation, or list of parameter + names if you passed an optimizer object. + metric: The training result objective value attribute. If None + but a mode was passed, the anonymous metric `_metric` will be used + per default. + mode: One of {min, max}. Determines whether objective is + minimizing or maximizing the metric attribute. + points_to_evaluate: Initial parameter suggestions to be run + first. This is for when you already have some good parameters + you want to run first to help the algorithm make better suggestions + for future parameters. Needs to be a list of dicts containing the + configurations. + + Tune automatically converts search spaces to Nevergrad's format: + + .. code-block:: python + + import nevergrad as ng + + config = { + "width": tune.uniform(0, 20), + "height": tune.uniform(-100, 100), + "activation": tune.choice(["relu", "tanh"]) + } + + current_best_params = [{ + "width": 10, + "height": 0, + "activation": relu", + }] + + ng_search = NevergradSearch( + optimizer=ng.optimizers.OnePlusOne, + metric="mean_loss", + mode="min", + points_to_evaluate=current_best_params) + + run(my_trainable, config=config, search_alg=ng_search) + + If you would like to pass the search space manually, the code would + look like this: + + .. code-block:: python + + import nevergrad as ng + + space = ng.p.Dict( + width=ng.p.Scalar(lower=0, upper=20), + height=ng.p.Scalar(lower=-100, upper=100), + activation=ng.p.Choice(choices=["relu", "tanh"]) + ) + + ng_search = NevergradSearch( + optimizer=ng.optimizers.OnePlusOne, + space=space, + metric="mean_loss", + mode="min") + + run(my_trainable, search_alg=ng_search) + + """ + + def __init__( + self, + optimizer: Optional[ + Union[Optimizer, Type[Optimizer], ConfiguredOptimizer] + ] = None, + optimizer_kwargs: Optional[Dict] = None, + space: Optional[Union[Dict, Parameter]] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + points_to_evaluate: Optional[List[Dict]] = None, + ): + assert ( + ng is not None + ), """Nevergrad must be installed! + You can install Nevergrad with the command: + `pip install nevergrad`.""" + if mode: + assert mode in ["min", "max"], "`mode` must be 'min' or 'max'." + + super(NevergradSearch, self).__init__(metric=metric, mode=mode) + + self._space = None + self._opt_factory = None + self._nevergrad_opt = None + self._optimizer_kwargs = optimizer_kwargs or {} + + if points_to_evaluate is None: + self._points_to_evaluate = None + elif not isinstance(points_to_evaluate, Sequence): + raise ValueError( + "Invalid object type passed for `points_to_evaluate`: " + f"{type(points_to_evaluate)}. " + "Please pass a list of points (dictionaries) instead." + ) + else: + self._points_to_evaluate = list(points_to_evaluate) + + if isinstance(space, dict) and space: + resolved_vars, domain_vars, grid_vars = parse_spec_vars(space) + if domain_vars or grid_vars: + logger.warning( + UNRESOLVED_SEARCH_SPACE.format(par="space", cls=type(self)) + ) + space = self.convert_search_space(space) + + if isinstance(optimizer, Optimizer): + if space is not None and not isinstance(space, list): + raise ValueError( + "If you pass a configured optimizer to Nevergrad, either " + "pass a list of parameter names or None as the `space` " + "parameter." + ) + if self._optimizer_kwargs: + raise ValueError( + "If you pass in optimizer kwargs, either pass " + "an `Optimizer` subclass or an instance of " + "`ConfiguredOptimizer`." + ) + + self._parameters = space + self._nevergrad_opt = optimizer + elif ( + inspect.isclass(optimizer) and issubclass(optimizer, Optimizer) + ) or isinstance(optimizer, ConfiguredOptimizer): + self._opt_factory = optimizer + self._parameters = None + self._space = space + else: + raise ValueError( + "The `optimizer` argument passed to NevergradSearch must be " + "either an `Optimizer` or a `ConfiguredOptimizer`." + ) + + self._live_trial_mapping = {} + + if self._nevergrad_opt or self._space: + self._setup_nevergrad() + + def _setup_nevergrad(self): + if self._opt_factory: + self._nevergrad_opt = self._opt_factory( + self._space, **self._optimizer_kwargs + ) + + # nevergrad.tell internally minimizes, so "max" => -1 + if self._mode == "max": + self._metric_op = -1.0 + elif self._mode == "min": + self._metric_op = 1.0 + + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + if hasattr(self._nevergrad_opt, "instrumentation"): # added in v0.2.0 + if self._nevergrad_opt.instrumentation.kwargs: + if self._nevergrad_opt.instrumentation.args: + raise ValueError("Instrumented optimizers should use kwargs only") + if self._parameters is not None: + raise ValueError( + "Instrumented optimizers should provide " + "None as parameter_names" + ) + else: + if self._parameters is None: + raise ValueError( + "Non-instrumented optimizers should have " + "a list of parameter_names" + ) + if len(self._nevergrad_opt.instrumentation.args) != 1: + raise ValueError("Instrumented optimizers should use kwargs only") + if self._parameters is not None and self._nevergrad_opt.dimension != len( + self._parameters + ): + raise ValueError( + "len(parameters_names) must match optimizer " + "dimension for non-instrumented optimizers" + ) + + if self._points_to_evaluate: + # Nevergrad is LIFO, so we add the points to evaluate in reverse + # order. + for i in range(len(self._points_to_evaluate) - 1, -1, -1): + self._nevergrad_opt.suggest(self._points_to_evaluate[i]) + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ) -> bool: + if self._nevergrad_opt or self._space: + return False + space = self.convert_search_space(config) + self._space = space + + if metric: + self._metric = metric + if mode: + self._mode = mode + + self._setup_nevergrad() + return True + + def suggest(self, trial_id: str) -> Optional[Dict]: + if not self._nevergrad_opt: + raise RuntimeError( + UNDEFINED_SEARCH_SPACE.format( + cls=self.__class__.__name__, space="space" + ) + ) + if not self._metric or not self._mode: + raise RuntimeError( + UNDEFINED_METRIC_MODE.format( + cls=self.__class__.__name__, metric=self._metric, mode=self._mode + ) + ) + + suggested_config = self._nevergrad_opt.ask() + + self._live_trial_mapping[trial_id] = suggested_config + # in v0.2.0+, output of ask() is a Candidate, + # with fields args and kwargs + if not suggested_config.kwargs: + if self._parameters: + return unflatten_dict( + dict(zip(self._parameters, suggested_config.args[0])) + ) + return unflatten_dict(suggested_config.value) + else: + return unflatten_dict(suggested_config.kwargs) + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ): + """Notification for the completion of trial. + + The result is internally negated when interacting with Nevergrad + so that Nevergrad Optimizers can "maximize" this value, + as it minimizes on default. + """ + if result: + self._process_result(trial_id, result) + + self._live_trial_mapping.pop(trial_id) + + def _process_result(self, trial_id: str, result: Dict): + ng_trial_info = self._live_trial_mapping[trial_id] + self._nevergrad_opt.tell(ng_trial_info, self._metric_op * result[self._metric]) + + def save(self, checkpoint_path: str): + save_object = self.__dict__ + with open(checkpoint_path, "wb") as outputFile: + pickle.dump(save_object, outputFile) + + def restore(self, checkpoint_path: str): + with open(checkpoint_path, "rb") as inputFile: + save_object = pickle.load(inputFile) + self.__dict__.update(save_object) + + @staticmethod + def convert_search_space(spec: Dict) -> Parameter: + resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec) + + if grid_vars: + raise ValueError( + "Grid search parameters cannot be automatically converted " + "to a Nevergrad search space." + ) + + # Flatten and resolve again after checking for grid search. + spec = flatten_dict(spec, prevent_delimiter=True) + resolved_vars, domain_vars, grid_vars = parse_spec_vars(spec) + + def resolve_value(domain: Domain) -> Parameter: + sampler = domain.get_sampler() + if isinstance(sampler, Quantized): + logger.warning( + "Nevergrad does not support quantization. Dropped quantization." + ) + sampler = sampler.get_sampler() + + if isinstance(domain, Float): + if isinstance(sampler, LogUniform): + return ng.p.Log( + lower=domain.lower, upper=domain.upper, exponent=math.e + ) + return ng.p.Scalar(lower=domain.lower, upper=domain.upper) + + elif isinstance(domain, Integer): + if isinstance(sampler, LogUniform): + return ng.p.Log( + lower=domain.lower, + upper=domain.upper - 1, # Upper bound exclusive + exponent=math.e, + ).set_integer_casting() + return ng.p.Scalar( + lower=domain.lower, + upper=domain.upper - 1, # Upper bound exclusive + ).set_integer_casting() + + elif isinstance(domain, Categorical): + return ng.p.Choice(choices=domain.categories) + + raise ValueError( + "Nevergrad does not support parameters of type " + "`{}` with samplers of type `{}`".format( + type(domain).__name__, type(domain.sampler).__name__ + ) + ) + + # Parameter name is e.g. "a/b/c" for nested dicts + space = {"/".join(path): resolve_value(domain) for path, domain in domain_vars} + + return ng.p.Dict(**space) diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/optuna/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/search/optuna/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..74b450f2e684c73a0dd6178763839ba0bd3cf03a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/optuna/__init__.py @@ -0,0 +1,3 @@ +from ray.tune.search.optuna.optuna_search import OptunaSearch + +__all__ = ["OptunaSearch"] diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/optuna/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/optuna/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8be127785eab1152bc1d712eefc2bc19109e7c57 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/optuna/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/optuna/__pycache__/optuna_search.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/optuna/__pycache__/optuna_search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b4309cb41a35194f7884f6df443fe2cd5a0bf02 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/optuna/__pycache__/optuna_search.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/repeater.py b/venv/lib/python3.10/site-packages/ray/tune/search/repeater.py new file mode 100644 index 0000000000000000000000000000000000000000..c9de4a156091971ba326c6e0cfca4678d6dc2261 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/repeater.py @@ -0,0 +1,199 @@ +import copy +import logging +from typing import Dict, List, Optional + +import numpy as np + +from ray.tune.search.searcher import Searcher +from ray.tune.search.util import _set_search_properties_backwards_compatible +from ray.util import PublicAPI + +logger = logging.getLogger(__name__) + +TRIAL_INDEX = "__trial_index__" +"""str: A constant value representing the repeat index of the trial.""" + + +def _warn_num_samples(searcher: Searcher, num_samples: int): + if isinstance(searcher, Repeater) and num_samples % searcher.repeat: + logger.warning( + "`num_samples` is now expected to be the total number of trials, " + "including the repeat trials. For example, set num_samples=15 if " + "you intend to obtain 3 search algorithm suggestions and repeat " + "each suggestion 5 times. Any leftover trials " + "(num_samples mod repeat) will be ignored." + ) + + +class _TrialGroup: + """Internal class for grouping trials of same parameters. + + This is used when repeating trials for reducing training variance. + + Args: + primary_trial_id: Trial ID of the "primary trial". + This trial is the one that the Searcher is aware of. + config: Suggested configuration shared across all trials + in the trial group. + max_trials: Max number of trials to execute within this group. + + """ + + def __init__(self, primary_trial_id: str, config: Dict, max_trials: int = 1): + assert type(config) is dict, "config is not a dict, got {}".format(config) + self.primary_trial_id = primary_trial_id + self.config = config + self._trials = {primary_trial_id: None} + self.max_trials = max_trials + + def add(self, trial_id: str): + assert len(self._trials) < self.max_trials + self._trials.setdefault(trial_id, None) + + def full(self) -> bool: + return len(self._trials) == self.max_trials + + def report(self, trial_id: str, score: float): + assert trial_id in self._trials + if score is None: + raise ValueError("Internal Error: Score cannot be None.") + self._trials[trial_id] = score + + def finished_reporting(self) -> bool: + return ( + None not in self._trials.values() and len(self._trials) == self.max_trials + ) + + def scores(self) -> List[Optional[float]]: + return list(self._trials.values()) + + def count(self) -> int: + return len(self._trials) + + +@PublicAPI +class Repeater(Searcher): + """A wrapper algorithm for repeating trials of same parameters. + + Set tune.TuneConfig(num_samples=...) to be a multiple of `repeat`. For example, + set num_samples=15 if you intend to obtain 3 search algorithm suggestions + and repeat each suggestion 5 times. Any leftover trials + (num_samples mod repeat) will be ignored. + + It is recommended that you do not run an early-stopping TrialScheduler + simultaneously. + + Args: + searcher: Searcher object that the + Repeater will optimize. Note that the Searcher + will only see 1 trial among multiple repeated trials. + The result/metric passed to the Searcher upon + trial completion will be averaged among all repeats. + repeat: Number of times to generate a trial with a repeated + configuration. Defaults to 1. + set_index: Sets a tune.search.repeater.TRIAL_INDEX in + Trainable/Function config which corresponds to the index of the + repeated trial. This can be used for seeds. Defaults to True. + + Example: + + .. code-block:: python + + from ray.tune.search import Repeater + + search_alg = BayesOptSearch(...) + re_search_alg = Repeater(search_alg, repeat=10) + + # Repeat 2 samples 10 times each. + tuner = tune.Tuner( + trainable, + tune_config=tune.TuneConfig( + search_alg=re_search_alg, + num_samples=20, + ), + ) + tuner.fit() + + """ + + def __init__(self, searcher: Searcher, repeat: int = 1, set_index: bool = True): + self.searcher = searcher + self.repeat = repeat + self._set_index = set_index + self._groups = [] + self._trial_id_to_group = {} + self._current_group = None + super(Repeater, self).__init__( + metric=self.searcher.metric, mode=self.searcher.mode + ) + + def suggest(self, trial_id: str) -> Optional[Dict]: + if self._current_group is None or self._current_group.full(): + config = self.searcher.suggest(trial_id) + if config is None: + return config + self._current_group = _TrialGroup( + trial_id, copy.deepcopy(config), max_trials=self.repeat + ) + self._groups.append(self._current_group) + index_in_group = 0 + else: + index_in_group = self._current_group.count() + self._current_group.add(trial_id) + + config = self._current_group.config.copy() + if self._set_index: + config[TRIAL_INDEX] = index_in_group + self._trial_id_to_group[trial_id] = self._current_group + return config + + def on_trial_complete(self, trial_id: str, result: Optional[Dict] = None, **kwargs): + """Stores the score for and keeps track of a completed trial. + + Stores the metric of a trial as nan if any of the following conditions + are met: + + 1. ``result`` is empty or not provided. + 2. ``result`` is provided but no metric was provided. + + """ + if trial_id not in self._trial_id_to_group: + logger.error( + "Trial {} not in group; cannot report score. " + "Seen trials: {}".format(trial_id, list(self._trial_id_to_group)) + ) + trial_group = self._trial_id_to_group[trial_id] + if not result or self.searcher.metric not in result: + score = np.nan + else: + score = result[self.searcher.metric] + trial_group.report(trial_id, score) + + if trial_group.finished_reporting(): + scores = trial_group.scores() + self.searcher.on_trial_complete( + trial_group.primary_trial_id, + result={self.searcher.metric: np.nanmean(scores)}, + **kwargs + ) + + def get_state(self) -> Dict: + self_state = self.__dict__.copy() + del self_state["searcher"] + return self_state + + def set_state(self, state: Dict): + self.__dict__.update(state) + + def save(self, checkpoint_path: str): + self.searcher.save(checkpoint_path) + + def restore(self, checkpoint_path: str): + self.searcher.restore(checkpoint_path) + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ) -> bool: + return _set_search_properties_backwards_compatible( + self.searcher.set_search_properties, metric, mode, config, **spec + ) diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/sample.py b/venv/lib/python3.10/site-packages/ray/tune/search/sample.py new file mode 100644 index 0000000000000000000000000000000000000000..ccf65034a4a0edb3d0397c9fa7268536e4d03476 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/sample.py @@ -0,0 +1,767 @@ +import logging +import warnings +from copy import copy +from inspect import signature +from math import isclose +from typing import Any, Callable, Dict, List, Optional, Sequence, Union + +import numpy as np + +# Backwards compatibility +from ray.util.annotations import DeveloperAPI, PublicAPI, RayDeprecationWarning + +try: + # Added in numpy>=1.17 but we require numpy>=1.16 + np_random_generator = np.random.Generator + LEGACY_RNG = False +except AttributeError: + + class np_random_generator: + pass + + LEGACY_RNG = True + +logger = logging.getLogger(__name__) + + +_MISSING = object() # Sentinel for missing parameters. + + +def _warn_for_base() -> None: + warnings.warn( + ( + "The `base` argument is deprecated. " + "Please remove it as it is not actually needed in this method." + ), + RayDeprecationWarning, + stacklevel=2, + ) + + +class _BackwardsCompatibleNumpyRng: + """Thin wrapper to ensure backwards compatibility between + new and old numpy randomness generators. + """ + + _rng = None + + def __init__( + self, + generator_or_seed: Optional[ + Union["np_random_generator", np.random.RandomState, int] + ] = None, + ): + if generator_or_seed is None or isinstance( + generator_or_seed, (np.random.RandomState, np_random_generator) + ): + self._rng = generator_or_seed + elif LEGACY_RNG: + self._rng = np.random.RandomState(generator_or_seed) + else: + self._rng = np.random.default_rng(generator_or_seed) + + @property + def legacy_rng(self) -> bool: + return not isinstance(self._rng, np_random_generator) + + @property + def rng(self): + # don't set self._rng to np.random to avoid picking issues + return self._rng if self._rng is not None else np.random + + def __getattr__(self, name: str) -> Any: + # https://numpy.org/doc/stable/reference/random/new-or-different.html + if self.legacy_rng: + if name == "integers": + name = "randint" + elif name == "random": + name = "rand" + return getattr(self.rng, name) + + +RandomState = Union[ + None, _BackwardsCompatibleNumpyRng, np_random_generator, np.random.RandomState, int +] + + +@DeveloperAPI +class Domain: + """Base class to specify a type and valid range to sample parameters from. + + This base class is implemented by parameter spaces, like float ranges + (``Float``), integer ranges (``Integer``), or categorical variables + (``Categorical``). The ``Domain`` object contains information about + valid values (e.g. minimum and maximum values), and exposes methods that + allow specification of specific samplers (e.g. ``uniform()`` or + ``loguniform()``). + + """ + + sampler = None + default_sampler_cls = None + + def cast(self, value): + """Cast value to domain type""" + return value + + def set_sampler(self, sampler, allow_override=False): + if self.sampler and not allow_override: + raise ValueError( + "You can only choose one sampler for parameter " + "domains. Existing sampler for parameter {}: " + "{}. Tried to add {}".format( + self.__class__.__name__, self.sampler, sampler + ) + ) + self.sampler = sampler + + def get_sampler(self): + sampler = self.sampler + if not sampler: + sampler = self.default_sampler_cls() + return sampler + + def sample( + self, + config: Optional[Union[List[Dict], Dict]] = None, + size: int = 1, + random_state: "RandomState" = None, + ): + if not isinstance(random_state, _BackwardsCompatibleNumpyRng): + random_state = _BackwardsCompatibleNumpyRng(random_state) + sampler = self.get_sampler() + return sampler.sample(self, config=config, size=size, random_state=random_state) + + def is_grid(self): + return isinstance(self.sampler, Grid) + + def is_function(self): + return False + + def is_valid(self, value: Any): + """Returns True if `value` is a valid value in this domain.""" + raise NotImplementedError + + @property + def domain_str(self): + return "(unknown)" + + +@DeveloperAPI +class Sampler: + def sample( + self, + domain: Domain, + config: Optional[Union[List[Dict], Dict]] = None, + size: int = 1, + random_state: "RandomState" = None, + ): + raise NotImplementedError + + +@DeveloperAPI +class BaseSampler(Sampler): + def __str__(self): + return "Base" + + +@DeveloperAPI +class Uniform(Sampler): + def __str__(self): + return "Uniform" + + +@DeveloperAPI +class LogUniform(Sampler): + def __init__(self, base: object = _MISSING): + if base is not _MISSING: + _warn_for_base() + + def __str__(self): + return "LogUniform" + + +@DeveloperAPI +class Normal(Sampler): + def __init__(self, mean: float = 0.0, sd: float = 0.0): + self.mean = mean + self.sd = sd + + assert self.sd > 0, "SD has to be strictly greater than 0" + + def __str__(self): + return "Normal" + + +@DeveloperAPI +class Grid(Sampler): + """Dummy sampler used for grid search""" + + def sample( + self, + domain: Domain, + config: Optional[Union[List[Dict], Dict]] = None, + size: int = 1, + random_state: "RandomState" = None, + ): + return RuntimeError("Do not call `sample()` on grid.") + + +@DeveloperAPI +class Float(Domain): + class _Uniform(Uniform): + def sample( + self, + domain: "Float", + config: Optional[Union[List[Dict], Dict]] = None, + size: int = 1, + random_state: "RandomState" = None, + ): + if not isinstance(random_state, _BackwardsCompatibleNumpyRng): + random_state = _BackwardsCompatibleNumpyRng(random_state) + assert domain.lower > float("-inf"), "Uniform needs a lower bound" + assert domain.upper < float("inf"), "Uniform needs a upper bound" + items = random_state.uniform(domain.lower, domain.upper, size=size) + return items if len(items) > 1 else domain.cast(items[0]) + + class _LogUniform(LogUniform): + def sample( + self, + domain: "Float", + config: Optional[Union[List[Dict], Dict]] = None, + size: int = 1, + random_state: "RandomState" = None, + ): + if not isinstance(random_state, _BackwardsCompatibleNumpyRng): + random_state = _BackwardsCompatibleNumpyRng(random_state) + assert domain.lower > 0, "LogUniform needs a lower bound greater than 0" + assert ( + 0 < domain.upper < float("inf") + ), "LogUniform needs a upper bound greater than 0" + logmin = np.log(domain.lower) + logmax = np.log(domain.upper) + + items = np.exp(random_state.uniform(logmin, logmax, size=size)) + return items if len(items) > 1 else domain.cast(items[0]) + + class _Normal(Normal): + def sample( + self, + domain: "Float", + config: Optional[Union[List[Dict], Dict]] = None, + size: int = 1, + random_state: "RandomState" = None, + ): + if not isinstance(random_state, _BackwardsCompatibleNumpyRng): + random_state = _BackwardsCompatibleNumpyRng(random_state) + assert not domain.lower or domain.lower == float( + "-inf" + ), "Normal sampling does not allow a lower value bound." + assert not domain.upper or domain.upper == float( + "inf" + ), "Normal sampling does not allow a upper value bound." + items = random_state.normal(self.mean, self.sd, size=size) + return items if len(items) > 1 else domain.cast(items[0]) + + default_sampler_cls = _Uniform + + def __init__(self, lower: Optional[float], upper: Optional[float]): + # Need to explicitly check for None + self.lower = lower if lower is not None else float("-inf") + self.upper = upper if upper is not None else float("inf") + + def cast(self, value): + return float(value) + + def uniform(self): + if not self.lower > float("-inf"): + raise ValueError( + "Uniform requires a lower bound. Make sure to set the " + "`lower` parameter of `Float()`." + ) + if not self.upper < float("inf"): + raise ValueError( + "Uniform requires a upper bound. Make sure to set the " + "`upper` parameter of `Float()`." + ) + new = copy(self) + new.set_sampler(self._Uniform()) + return new + + def loguniform(self, base: object = _MISSING): + if base is not _MISSING: + _warn_for_base() + if not self.lower > 0: + raise ValueError( + "LogUniform requires a lower bound greater than 0." + f"Got: {self.lower}. Did you pass a variable that has " + "been log-transformed? If so, pass the non-transformed value " + "instead." + ) + if not 0 < self.upper < float("inf"): + raise ValueError( + "LogUniform requires a upper bound greater than 0. " + f"Got: {self.lower}. Did you pass a variable that has " + "been log-transformed? If so, pass the non-transformed value " + "instead." + ) + new = copy(self) + new.set_sampler(self._LogUniform()) + return new + + def normal(self, mean=0.0, sd=1.0): + new = copy(self) + new.set_sampler(self._Normal(mean, sd)) + return new + + def quantized(self, q: float): + if self.lower > float("-inf") and not isclose( + self.lower / q, round(self.lower / q) + ): + raise ValueError( + f"Your lower variable bound {self.lower} is not divisible by " + f"quantization factor {q}." + ) + if self.upper < float("inf") and not isclose( + self.upper / q, round(self.upper / q) + ): + raise ValueError( + f"Your upper variable bound {self.upper} is not divisible by " + f"quantization factor {q}." + ) + + new = copy(self) + new.set_sampler(Quantized(new.get_sampler(), q), allow_override=True) + return new + + def is_valid(self, value: float): + return self.lower <= value <= self.upper + + @property + def domain_str(self): + return f"({self.lower}, {self.upper})" + + +@DeveloperAPI +class Integer(Domain): + class _Uniform(Uniform): + def sample( + self, + domain: "Integer", + config: Optional[Union[List[Dict], Dict]] = None, + size: int = 1, + random_state: "RandomState" = None, + ): + if not isinstance(random_state, _BackwardsCompatibleNumpyRng): + random_state = _BackwardsCompatibleNumpyRng(random_state) + items = random_state.integers(domain.lower, domain.upper, size=size) + return items if len(items) > 1 else domain.cast(items[0]) + + class _LogUniform(LogUniform): + def sample( + self, + domain: "Integer", + config: Optional[Union[List[Dict], Dict]] = None, + size: int = 1, + random_state: "RandomState" = None, + ): + if not isinstance(random_state, _BackwardsCompatibleNumpyRng): + random_state = _BackwardsCompatibleNumpyRng(random_state) + assert domain.lower > 0, "LogUniform needs a lower bound greater than 0" + assert ( + 0 < domain.upper < float("inf") + ), "LogUniform needs a upper bound greater than 0" + logmin = np.log(domain.lower) + logmax = np.log(domain.upper) + + items = np.exp(random_state.uniform(logmin, logmax, size=size)) + items = np.floor(items).astype(int) + return items if len(items) > 1 else domain.cast(items[0]) + + default_sampler_cls = _Uniform + + def __init__(self, lower, upper): + self.lower = lower + self.upper = upper + + def cast(self, value): + return int(value) + + def quantized(self, q: int): + new = copy(self) + new.set_sampler(Quantized(new.get_sampler(), q), allow_override=True) + return new + + def uniform(self): + new = copy(self) + new.set_sampler(self._Uniform()) + return new + + def loguniform(self, base: object = _MISSING): + if base is not _MISSING: + _warn_for_base() + if not self.lower > 0: + raise ValueError( + "LogUniform requires a lower bound greater than 0." + f"Got: {self.lower}. Did you pass a variable that has " + "been log-transformed? If so, pass the non-transformed value " + "instead." + ) + if not 0 < self.upper < float("inf"): + raise ValueError( + "LogUniform requires a upper bound greater than 0. " + f"Got: {self.lower}. Did you pass a variable that has " + "been log-transformed? If so, pass the non-transformed value " + "instead." + ) + new = copy(self) + new.set_sampler(self._LogUniform()) + return new + + def is_valid(self, value: int): + return self.lower <= value <= self.upper + + @property + def domain_str(self): + return f"({self.lower}, {self.upper})" + + +@DeveloperAPI +class Categorical(Domain): + class _Uniform(Uniform): + def sample( + self, + domain: "Categorical", + config: Optional[Union[List[Dict], Dict]] = None, + size: int = 1, + random_state: "RandomState" = None, + ): + if not isinstance(random_state, _BackwardsCompatibleNumpyRng): + random_state = _BackwardsCompatibleNumpyRng(random_state) + # do not use .choice() directly on domain.categories + # as that will coerce them to a single dtype + indices = random_state.choice( + np.arange(0, len(domain.categories)), size=size + ) + items = [domain.categories[index] for index in indices] + return items if len(items) > 1 else domain.cast(items[0]) + + default_sampler_cls = _Uniform + + def __init__(self, categories: Sequence): + self.categories = list(categories) + + def uniform(self): + new = copy(self) + new.set_sampler(self._Uniform()) + return new + + def grid(self): + new = copy(self) + new.set_sampler(Grid()) + return new + + def __len__(self): + return len(self.categories) + + def __getitem__(self, item): + return self.categories[item] + + def is_valid(self, value: Any): + return value in self.categories + + @property + def domain_str(self): + return f"{self.categories}" + + +@DeveloperAPI +class Function(Domain): + class _CallSampler(BaseSampler): + def __try_fn(self, domain: "Function", config: Dict[str, Any]): + try: + return domain.func(config) + except (AttributeError, KeyError): + from ray.tune.search.variant_generator import _UnresolvedAccessGuard + + r = domain.func(_UnresolvedAccessGuard({"config": config})) + logger.warning( + "sample_from functions that take a spec dict are " + "deprecated. Please update your function to work with " + "the config dict directly." + ) + return r + + def sample( + self, + domain: "Function", + config: Optional[Union[List[Dict], Dict]] = None, + size: int = 1, + random_state: "RandomState" = None, + ): + if not isinstance(random_state, _BackwardsCompatibleNumpyRng): + random_state = _BackwardsCompatibleNumpyRng(random_state) + if domain.pass_config: + items = [ + ( + self.__try_fn(domain, config[i]) + if isinstance(config, list) + else self.__try_fn(domain, config) + ) + for i in range(size) + ] + else: + items = [domain.func() for i in range(size)] + + return items if len(items) > 1 else domain.cast(items[0]) + + default_sampler_cls = _CallSampler + + def __init__(self, func: Callable): + sig = signature(func) + + pass_config = True # whether we should pass `config` when calling `func` + try: + sig.bind({}) + except TypeError: + pass_config = False + + if not pass_config: + try: + sig.bind() + except TypeError as exc: + raise ValueError( + "The function passed to a `Function` parameter must be " + "callable with either 0 or 1 parameters." + ) from exc + + self.pass_config = pass_config + self.func = func + + def is_function(self): + return True + + def is_valid(self, value: Any): + return True # This is user-defined, so lets not assume anything + + @property + def domain_str(self): + return f"{self.func}()" + + +@DeveloperAPI +class Quantized(Sampler): + def __init__(self, sampler: Sampler, q: Union[float, int]): + self.sampler = sampler + self.q = q + + assert self.sampler, "Quantized() expects a sampler instance" + + def get_sampler(self): + return self.sampler + + def sample( + self, + domain: Domain, + config: Optional[Union[List[Dict], Dict]] = None, + size: int = 1, + random_state: "RandomState" = None, + ): + if not isinstance(random_state, _BackwardsCompatibleNumpyRng): + random_state = _BackwardsCompatibleNumpyRng(random_state) + + if self.q == 1: + return self.sampler.sample(domain, config, size, random_state=random_state) + + quantized_domain = copy(domain) + quantized_domain.lower = np.ceil(domain.lower / self.q) * self.q + quantized_domain.upper = np.floor(domain.upper / self.q) * self.q + values = self.sampler.sample( + quantized_domain, config, size, random_state=random_state + ) + quantized = np.round(np.divide(values, self.q)) * self.q + + if not isinstance(quantized, np.ndarray): + return domain.cast(quantized) + return list(quantized) + + +@PublicAPI +def sample_from(func: Callable[[Dict], Any]): + """Specify that tune should sample configuration values from this function. + + Arguments: + func: An callable function to draw a sample from. + """ + return Function(func) + + +@PublicAPI +def uniform(lower: float, upper: float): + """Sample a float value uniformly between ``lower`` and ``upper``. + + Sampling from ``tune.uniform(1, 10)`` is equivalent to sampling from + ``np.random.uniform(1, 10))`` + + """ + return Float(lower, upper).uniform() + + +@PublicAPI +def quniform(lower: float, upper: float, q: float): + """Sample a quantized float value uniformly between ``lower`` and ``upper``. + + Sampling from ``tune.uniform(1, 10)`` is equivalent to sampling from + ``np.random.uniform(1, 10))`` + + The value will be quantized, i.e. rounded to an integer increment of ``q``. + Quantization makes the upper bound inclusive. + + """ + return Float(lower, upper).uniform().quantized(q) + + +@PublicAPI +def loguniform(lower: float, upper: float, base: object = _MISSING): + """Sugar for sampling in different orders of magnitude. + + Args: + lower: Lower boundary of the output interval (e.g. 1e-4) + upper: Upper boundary of the output interval (e.g. 1e-2) + + """ + if base is not _MISSING: + _warn_for_base() + return Float(lower, upper).loguniform() + + +@PublicAPI +def qloguniform(lower: float, upper: float, q: float, base: object = _MISSING): + """Sugar for sampling in different orders of magnitude. + + The value will be quantized, i.e. rounded to an integer increment of ``q``. + + Quantization makes the upper bound inclusive. + + Args: + lower: Lower boundary of the output interval (e.g. 1e-4) + upper: Upper boundary of the output interval (e.g. 1e-2) + q: Quantization number. The result will be rounded to an + integer increment of this value. + + """ + if base is not _MISSING: + _warn_for_base() + return Float(lower, upper).loguniform().quantized(q) + + +@PublicAPI +def choice(categories: Sequence): + """Sample a categorical value. + + Sampling from ``tune.choice([1, 2])`` is equivalent to sampling from + ``np.random.choice([1, 2])`` + + """ + return Categorical(categories).uniform() + + +@PublicAPI +def randint(lower: int, upper: int): + """Sample an integer value uniformly between ``lower`` and ``upper``. + + ``lower`` is inclusive, ``upper`` is exclusive. + + Sampling from ``tune.randint(10)`` is equivalent to sampling from + ``np.random.randint(10)`` + + .. versionchanged:: 1.5.0 + When converting Ray Tune configs to searcher-specific search spaces, + the lower and upper limits are adjusted to keep compatibility with + the bounds stated in the docstring above. + + """ + return Integer(lower, upper).uniform() + + +@PublicAPI +def lograndint(lower: int, upper: int, base: object = _MISSING): + """Sample an integer value log-uniformly between ``lower`` and ``upper``. + + ``lower`` is inclusive, ``upper`` is exclusive. + + .. versionchanged:: 1.5.0 + When converting Ray Tune configs to searcher-specific search spaces, + the lower and upper limits are adjusted to keep compatibility with + the bounds stated in the docstring above. + + """ + if base is not _MISSING: + _warn_for_base() + return Integer(lower, upper).loguniform() + + +@PublicAPI +def qrandint(lower: int, upper: int, q: int = 1): + """Sample an integer value uniformly between ``lower`` and ``upper``. + + ``lower`` is inclusive, ``upper`` is also inclusive (!). + + The value will be quantized, i.e. rounded to an integer increment of ``q``. + Quantization makes the upper bound inclusive. + + .. versionchanged:: 1.5.0 + When converting Ray Tune configs to searcher-specific search spaces, + the lower and upper limits are adjusted to keep compatibility with + the bounds stated in the docstring above. + + """ + return Integer(lower, upper).uniform().quantized(q) + + +@PublicAPI +def qlograndint(lower: int, upper: int, q: int, base: object = _MISSING): + """Sample an integer value log-uniformly between ``lower`` and ``upper``. + + ``lower`` is inclusive, ``upper`` is also inclusive (!). + + The value will be quantized, i.e. rounded to an integer increment of ``q``. + Quantization makes the upper bound inclusive. + + .. versionchanged:: 1.5.0 + When converting Ray Tune configs to searcher-specific search spaces, + the lower and upper limits are adjusted to keep compatibility with + the bounds stated in the docstring above. + + """ + if base is not _MISSING: + _warn_for_base() + return Integer(lower, upper).loguniform().quantized(q) + + +@PublicAPI +def randn(mean: float = 0.0, sd: float = 1.0): + """Sample a float value normally with ``mean`` and ``sd``. + + Args: + mean: Mean of the normal distribution. Defaults to 0. + sd: SD of the normal distribution. Defaults to 1. + + """ + return Float(None, None).normal(mean, sd) + + +@PublicAPI +def qrandn(mean: float, sd: float, q: float): + """Sample a float value normally with ``mean`` and ``sd``. + + The value will be quantized, i.e. rounded to an integer increment of ``q``. + + Args: + mean: Mean of the normal distribution. + sd: SD of the normal distribution. + q: Quantization number. The result will be rounded to an + integer increment of this value. + + """ + return Float(None, None).normal(mean, sd).quantized(q) diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/search_algorithm.py b/venv/lib/python3.10/site-packages/ray/tune/search/search_algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..8ae5154c976bd4e6632089d604a0080223c2292b --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/search_algorithm.py @@ -0,0 +1,127 @@ +from typing import TYPE_CHECKING, Dict, List, Optional, Union + +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + from ray.tune.experiment import Experiment + + +@DeveloperAPI +class SearchAlgorithm: + """Interface of an event handler API for hyperparameter search. + + Unlike TrialSchedulers, SearchAlgorithms will not have the ability + to modify the execution (i.e., stop and pause trials). + + Trials added manually (i.e., via the Client API) will also notify + this class upon new events, so custom search algorithms should + maintain a list of trials ID generated from this class. + + See also: `ray.tune.search.BasicVariantGenerator`. + """ + + _finished = False + + _metric = None + + @property + def metric(self): + return self._metric + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ) -> bool: + """Pass search properties to search algorithm. + + This method acts as an alternative to instantiating search algorithms + with their own specific search spaces. Instead they can accept a + Tune config through this method. + + The search algorithm will usually pass this method to their + ``Searcher`` instance. + + Args: + metric: Metric to optimize + mode: One of ["min", "max"]. Direction to optimize. + config: Tune config dict. + **spec: Any kwargs for forward compatiblity. + Info like Experiment.PUBLIC_KEYS is provided through here. + """ + if self._metric and metric: + return False + if metric: + self._metric = metric + return True + + @property + def total_samples(self): + """Get number of total trials to be generated""" + return 0 + + def add_configurations( + self, experiments: Union["Experiment", List["Experiment"], Dict[str, Dict]] + ): + """Tracks given experiment specifications. + + Arguments: + experiments: Experiments to run. + """ + raise NotImplementedError + + def next_trial(self): + """Returns single Trial object to be queued into the TrialRunner. + + Returns: + trial: Returns a Trial object. + """ + raise NotImplementedError + + def on_trial_result(self, trial_id: str, result: Dict): + """Called on each intermediate result returned by a trial. + + This will only be called when the trial is in the RUNNING state. + + Arguments: + trial_id: Identifier for the trial. + result: Result dictionary. + """ + pass + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ): + """Notification for the completion of trial. + + Arguments: + trial_id: Identifier for the trial. + result: Defaults to None. A dict will + be provided with this notification when the trial is in + the RUNNING state AND either completes naturally or + by manual termination. + error: Defaults to False. True if the trial is in + the RUNNING state and errors. + """ + pass + + def is_finished(self) -> bool: + """Returns True if no trials left to be queued into TrialRunner. + + Can return True before all trials have finished executing. + """ + return self._finished + + def set_finished(self): + """Marks the search algorithm as finished.""" + self._finished = True + + def has_checkpoint(self, dirpath: str) -> bool: + """Should return False if restoring is not implemented.""" + return False + + def save_to_dir(self, dirpath: str, **kwargs): + """Saves a search algorithm.""" + pass + + def restore_from_dir(self, dirpath: str): + """Restores a search algorithm along with its wrapped state.""" + pass diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/search_generator.py b/venv/lib/python3.10/site-packages/ray/tune/search/search_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..41f267f4521447856304da745fcaab9aec896fe6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/search_generator.py @@ -0,0 +1,222 @@ +import copy +import logging +from typing import Dict, List, Optional, Union + +from ray.tune.error import TuneError +from ray.tune.experiment import Experiment, Trial, _convert_to_experiment_list +from ray.tune.experiment.config_parser import _create_trial_from_spec, _make_parser +from ray.tune.search.search_algorithm import SearchAlgorithm +from ray.tune.search.searcher import Searcher +from ray.tune.search.util import _set_search_properties_backwards_compatible +from ray.tune.search.variant_generator import _resolve_nested_dict, format_vars +from ray.tune.utils.util import ( + _atomic_save, + _load_newest_checkpoint, + flatten_dict, + merge_dicts, +) +from ray.util.annotations import DeveloperAPI + +logger = logging.getLogger(__name__) + + +def _warn_on_repeater(searcher, total_samples): + from ray.tune.search.repeater import _warn_num_samples + + _warn_num_samples(searcher, total_samples) + + +@DeveloperAPI +class SearchGenerator(SearchAlgorithm): + """Generates trials to be passed to the TrialRunner. + + Uses the provided ``searcher`` object to generate trials. This class + transparently handles repeating trials with score aggregation + without embedding logic into the Searcher. + + Args: + searcher: Search object that subclasses the Searcher base class. This + is then used for generating new hyperparameter samples. + """ + + CKPT_FILE_TMPL = "search_gen_state-{}.json" + + def __init__(self, searcher: Searcher): + assert issubclass( + type(searcher), Searcher + ), "Searcher should be subclassing Searcher." + self.searcher = searcher + self._parser = _make_parser() + self._experiment = None + self._counter = 0 # Keeps track of number of trials created. + self._total_samples = 0 # int: total samples to evaluate. + self._finished = False + + @property + def metric(self): + return self.searcher.metric + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ) -> bool: + return _set_search_properties_backwards_compatible( + self.searcher.set_search_properties, metric, mode, config, **spec + ) + + @property + def total_samples(self): + return self._total_samples + + def add_configurations( + self, experiments: Union[Experiment, List[Experiment], Dict[str, Dict]] + ): + """Registers experiment specifications. + + Arguments: + experiments: Experiments to run. + """ + assert not self._experiment + logger.debug("added configurations") + experiment_list = _convert_to_experiment_list(experiments) + assert ( + len(experiment_list) == 1 + ), "SearchAlgorithms can only support 1 experiment at a time." + self._experiment = experiment_list[0] + experiment_spec = self._experiment.spec + self._total_samples = self._experiment.spec.get("num_samples", 1) + + _warn_on_repeater(self.searcher, self._total_samples) + if "run" not in experiment_spec: + raise TuneError("Must specify `run` in {}".format(experiment_spec)) + + def next_trial(self): + """Provides one Trial object to be queued into the TrialRunner. + + Returns: + Trial: Returns a single trial. + """ + if not self.is_finished(): + return self.create_trial_if_possible(self._experiment.spec) + return None + + def create_trial_if_possible(self, experiment_spec: Dict) -> Optional[Trial]: + logger.debug("creating trial") + trial_id = Trial.generate_id() + suggested_config = self.searcher.suggest(trial_id) + if suggested_config == Searcher.FINISHED: + self._finished = True + logger.debug("Searcher has finished.") + return + + if suggested_config is None: + return + spec = copy.deepcopy(experiment_spec) + spec["config"] = merge_dicts(spec["config"], copy.deepcopy(suggested_config)) + + # Create a new trial_id if duplicate trial is created + flattened_config = _resolve_nested_dict(spec["config"]) + self._counter += 1 + tag = "{0}_{1}".format(str(self._counter), format_vars(flattened_config)) + trial = _create_trial_from_spec( + spec, + self._parser, + evaluated_params=flatten_dict(suggested_config), + experiment_tag=tag, + trial_id=trial_id, + ) + return trial + + def on_trial_result(self, trial_id: str, result: Dict): + """Notifies the underlying searcher.""" + self.searcher.on_trial_result(trial_id, result) + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ): + self.searcher.on_trial_complete(trial_id=trial_id, result=result, error=error) + + def is_finished(self) -> bool: + return self._counter >= self._total_samples or self._finished + + def get_state(self) -> Dict: + return { + "counter": self._counter, + "total_samples": self._total_samples, + "finished": self._finished, + "experiment": self._experiment, + } + + def set_state(self, state: Dict): + self._counter = state["counter"] + self._total_samples = state["total_samples"] + self._finished = state["finished"] + self._experiment = state["experiment"] + + def has_checkpoint(self, dirpath: str): + return bool(_load_newest_checkpoint(dirpath, self.CKPT_FILE_TMPL.format("*"))) + + def save_to_dir(self, dirpath: str, session_str: str): + """Saves self + searcher to dir. + + Separates the "searcher" from its wrappers (concurrency, repeating). + This allows the user to easily restore a given searcher. + + The save operation is atomic (write/swap). + + Args: + dirpath: Filepath to experiment dir. + session_str: Unique identifier of the current run + session. + """ + searcher = self.searcher + search_alg_state = self.get_state() + while hasattr(searcher, "searcher"): + searcher_name = type(searcher).__name__ + if searcher_name in search_alg_state: + logger.warning( + "There was a duplicate when saving {}. " + "Restore may not work properly.".format(searcher_name) + ) + else: + search_alg_state["name:" + searcher_name] = searcher.get_state() + searcher = searcher.searcher + base_searcher = searcher + # We save the base searcher separately for users to easily + # separate the searcher. + base_searcher.save_to_dir(dirpath, session_str) + _atomic_save( + state=search_alg_state, + checkpoint_dir=dirpath, + file_name=self.CKPT_FILE_TMPL.format(session_str), + tmp_file_name=".tmp_search_generator_ckpt", + ) + + def restore_from_dir(self, dirpath: str): + """Restores self + searcher + search wrappers from dirpath.""" + + searcher = self.searcher + search_alg_state = _load_newest_checkpoint( + dirpath, self.CKPT_FILE_TMPL.format("*") + ) + if not search_alg_state: + raise RuntimeError("Unable to find checkpoint in {}.".format(dirpath)) + while hasattr(searcher, "searcher"): + searcher_name = "name:" + type(searcher).__name__ + if searcher_name not in search_alg_state: + names = [ + key.split("name:")[1] + for key in search_alg_state + if key.startswith("name:") + ] + logger.warning( + "{} was not found in the experiment " + "state when restoring. Found {}.".format(searcher_name, names) + ) + else: + searcher.set_state(search_alg_state.pop(searcher_name)) + searcher = searcher.searcher + base_searcher = searcher + + logger.debug(f"searching base {base_searcher}") + base_searcher.restore_from_dir(dirpath) + self.set_state(search_alg_state) diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/searcher.py b/venv/lib/python3.10/site-packages/ray/tune/search/searcher.py new file mode 100644 index 0000000000000000000000000000000000000000..2d0209a1df208708b26a10646bedcd00e00e3847 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/searcher.py @@ -0,0 +1,597 @@ +import copy +import glob +import logging +import os +import warnings +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union + +from ray.air._internal.usage import tag_searcher +from ray.tune.search.util import _set_search_properties_backwards_compatible +from ray.util.annotations import DeveloperAPI, PublicAPI +from ray.util.debug import log_once + +if TYPE_CHECKING: + from ray.tune.analysis import ExperimentAnalysis + from ray.tune.experiment import Trial + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class Searcher: + """Abstract class for wrapping suggesting algorithms. + + Custom algorithms can extend this class easily by overriding the + `suggest` method provide generated parameters for the trials. + + Any subclass that implements ``__init__`` must also call the + constructor of this class: ``super(Subclass, self).__init__(...)``. + + To track suggestions and their corresponding evaluations, the method + `suggest` will be passed a trial_id, which will be used in + subsequent notifications. + + Not all implementations support multi objectives. + + Note to Tune developers: If a new searcher is added, please update + `air/_internal/usage.py`. + + Args: + metric: The training result objective value attribute. If + list then list of training result objective value attributes + mode: If string One of {min, max}. If list then + list of max and min, determines whether objective is minimizing + or maximizing the metric attribute. Must match type of metric. + + .. code-block:: python + + class ExampleSearch(Searcher): + def __init__(self, metric="mean_loss", mode="min", **kwargs): + super(ExampleSearch, self).__init__( + metric=metric, mode=mode, **kwargs) + self.optimizer = Optimizer() + self.configurations = {} + + def suggest(self, trial_id): + configuration = self.optimizer.query() + self.configurations[trial_id] = configuration + + def on_trial_complete(self, trial_id, result, **kwargs): + configuration = self.configurations[trial_id] + if result and self.metric in result: + self.optimizer.update(configuration, result[self.metric]) + + tuner = tune.Tuner( + trainable_function, + tune_config=tune.TuneConfig( + search_alg=ExampleSearch() + ) + ) + tuner.fit() + + + """ + + FINISHED = "FINISHED" + CKPT_FILE_TMPL = "searcher-state-{}.pkl" + + def __init__( + self, + metric: Optional[str] = None, + mode: Optional[str] = None, + ): + tag_searcher(self) + self._metric = metric + self._mode = mode + + if not mode or not metric: + # Early return to avoid assertions + return + + assert isinstance( + metric, type(mode) + ), "metric and mode must be of the same type" + if isinstance(mode, str): + assert mode in ["min", "max"], "if `mode` is a str must be 'min' or 'max'!" + elif isinstance(mode, list): + assert len(mode) == len(metric), "Metric and mode must be the same length" + assert all( + mod in ["min", "max", "obs"] for mod in mode + ), "All of mode must be 'min' or 'max' or 'obs'!" + else: + raise ValueError("Mode most either be a list or string") + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ) -> bool: + """Pass search properties to searcher. + + This method acts as an alternative to instantiating search algorithms + with their own specific search spaces. Instead they can accept a + Tune config through this method. A searcher should return ``True`` + if setting the config was successful, or ``False`` if it was + unsuccessful, e.g. when the search space has already been set. + + Args: + metric: Metric to optimize + mode: One of ["min", "max"]. Direction to optimize. + config: Tune config dict. + **spec: Any kwargs for forward compatiblity. + Info like Experiment.PUBLIC_KEYS is provided through here. + """ + return False + + def on_trial_result(self, trial_id: str, result: Dict) -> None: + """Optional notification for result during training. + + Note that by default, the result dict may include NaNs or + may not include the optimization metric. It is up to the + subclass implementation to preprocess the result to + avoid breaking the optimization process. + + Args: + trial_id: A unique string ID for the trial. + result: Dictionary of metrics for current training progress. + Note that the result dict may include NaNs or + may not include the optimization metric. It is up to the + subclass implementation to preprocess the result to + avoid breaking the optimization process. + """ + pass + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ) -> None: + """Notification for the completion of trial. + + Typically, this method is used for notifying the underlying + optimizer of the result. + + Args: + trial_id: A unique string ID for the trial. + result: Dictionary of metrics for current training progress. + Note that the result dict may include NaNs or + may not include the optimization metric. It is up to the + subclass implementation to preprocess the result to + avoid breaking the optimization process. Upon errors, this + may also be None. + error: True if the training process raised an error. + + """ + raise NotImplementedError + + def suggest(self, trial_id: str) -> Optional[Dict]: + """Queries the algorithm to retrieve the next set of parameters. + + Arguments: + trial_id: Trial ID used for subsequent notifications. + + Returns: + dict | FINISHED | None: Configuration for a trial, if possible. + If FINISHED is returned, Tune will be notified that + no more suggestions/configurations will be provided. + If None is returned, Tune will skip the querying of the + searcher for this step. + + """ + raise NotImplementedError + + def add_evaluated_point( + self, + parameters: Dict, + value: float, + error: bool = False, + pruned: bool = False, + intermediate_values: Optional[List[float]] = None, + ): + """Pass results from a point that has been evaluated separately. + + This method allows for information from outside the + suggest - on_trial_complete loop to be passed to the search + algorithm. + This functionality depends on the underlying search algorithm + and may not be always available. + + Args: + parameters: Parameters used for the trial. + value: Metric value obtained in the trial. + error: True if the training process raised an error. + pruned: True if trial was pruned. + intermediate_values: List of metric values for + intermediate iterations of the result. None if not + applicable. + + """ + raise NotImplementedError + + def add_evaluated_trials( + self, + trials_or_analysis: Union["Trial", List["Trial"], "ExperimentAnalysis"], + metric: str, + ): + """Pass results from trials that have been evaluated separately. + + This method allows for information from outside the + suggest - on_trial_complete loop to be passed to the search + algorithm. + This functionality depends on the underlying search algorithm + and may not be always available (same as ``add_evaluated_point``.) + + Args: + trials_or_analysis: Trials to pass results form to the searcher. + metric: Metric name reported by trials used for + determining the objective value. + + """ + if self.add_evaluated_point == Searcher.add_evaluated_point: + raise NotImplementedError + + # lazy imports to avoid circular dependencies + from ray.tune.analysis import ExperimentAnalysis + from ray.tune.experiment import Trial + from ray.tune.result import DONE + + if isinstance(trials_or_analysis, (list, tuple)): + trials = trials_or_analysis + elif isinstance(trials_or_analysis, Trial): + trials = [trials_or_analysis] + elif isinstance(trials_or_analysis, ExperimentAnalysis): + trials = trials_or_analysis.trials + else: + raise NotImplementedError( + "Expected input to be a `Trial`, a list of `Trial`s, or " + f"`ExperimentAnalysis`, got: {trials_or_analysis}" + ) + + any_trial_had_metric = False + + def trial_to_points(trial: Trial) -> Dict[str, Any]: + nonlocal any_trial_had_metric + has_trial_been_pruned = ( + trial.status == Trial.TERMINATED + and not trial.last_result.get(DONE, False) + ) + has_trial_finished = ( + trial.status == Trial.TERMINATED and trial.last_result.get(DONE, False) + ) + if not any_trial_had_metric: + any_trial_had_metric = ( + metric in trial.last_result and has_trial_finished + ) + if Trial.TERMINATED and metric not in trial.last_result: + return None + return dict( + parameters=trial.config, + value=trial.last_result.get(metric, None), + error=trial.status == Trial.ERROR, + pruned=has_trial_been_pruned, + intermediate_values=None, # we do not save those + ) + + for trial in trials: + kwargs = trial_to_points(trial) + if kwargs: + self.add_evaluated_point(**kwargs) + + if not any_trial_had_metric: + warnings.warn( + "No completed trial returned the specified metric. " + "Make sure the name you have passed is correct. " + ) + + def save(self, checkpoint_path: str): + """Save state to path for this search algorithm. + + Args: + checkpoint_path: File where the search algorithm + state is saved. This path should be used later when + restoring from file. + + Example: + + .. code-block:: python + + search_alg = Searcher(...) + + tuner = tune.Tuner( + cost, + tune_config=tune.TuneConfig( + search_alg=search_alg, + num_samples=5 + ), + param_space=config + ) + results = tuner.fit() + + search_alg.save("./my_favorite_path.pkl") + + .. versionchanged:: 0.8.7 + Save is automatically called by `Tuner().fit()`. You can use + `Tuner().restore()` to restore from an experiment directory + such as `~/ray_results/trainable`. + + """ + raise NotImplementedError + + def restore(self, checkpoint_path: str): + """Restore state for this search algorithm + + + Args: + checkpoint_path: File where the search algorithm + state is saved. This path should be the same + as the one provided to "save". + + Example: + + .. code-block:: python + + search_alg.save("./my_favorite_path.pkl") + + search_alg2 = Searcher(...) + search_alg2 = ConcurrencyLimiter(search_alg2, 1) + search_alg2.restore(checkpoint_path) + tuner = tune.Tuner( + cost, + tune_config=tune.TuneConfig( + search_alg=search_alg2, + num_samples=5 + ), + ) + tuner.fit() + + """ + raise NotImplementedError + + def set_max_concurrency(self, max_concurrent: int) -> bool: + """Set max concurrent trials this searcher can run. + + This method will be called on the wrapped searcher by the + ``ConcurrencyLimiter``. It is intended to allow for searchers + which have custom, internal logic handling max concurrent trials + to inherit the value passed to ``ConcurrencyLimiter``. + + If this method returns False, it signifies that no special + logic for handling this case is present in the searcher. + + Args: + max_concurrent: Number of maximum concurrent trials. + """ + return False + + def get_state(self) -> Dict: + raise NotImplementedError + + def set_state(self, state: Dict): + raise NotImplementedError + + def save_to_dir(self, checkpoint_dir: str, session_str: str = "default"): + """Automatically saves the given searcher to the checkpoint_dir. + + This is automatically used by Tuner().fit() during a Tune job. + + Args: + checkpoint_dir: Filepath to experiment dir. + session_str: Unique identifier of the current run + session. + """ + tmp_search_ckpt_path = os.path.join(checkpoint_dir, ".tmp_searcher_ckpt") + success = True + try: + self.save(tmp_search_ckpt_path) + except NotImplementedError: + if log_once("suggest:save_to_dir"): + logger.warning("save not implemented for Searcher. Skipping save.") + success = False + + if success and os.path.exists(tmp_search_ckpt_path): + os.replace( + tmp_search_ckpt_path, + os.path.join(checkpoint_dir, self.CKPT_FILE_TMPL.format(session_str)), + ) + + def restore_from_dir(self, checkpoint_dir: str): + """Restores the state of a searcher from a given checkpoint_dir. + + Typically, you should use this function to restore from an + experiment directory such as `~/ray_results/trainable`. + + .. code-block:: python + + tuner = tune.Tuner( + cost, + run_config=tune.RunConfig( + name=self.experiment_name, + storage_path="~/my_results", + ), + tune_config=tune.TuneConfig( + search_alg=search_alg, + num_samples=5 + ), + param_space=config + ) + tuner.fit() + + search_alg2 = Searcher() + search_alg2.restore_from_dir( + os.path.join("~/my_results", self.experiment_name) + """ + + pattern = self.CKPT_FILE_TMPL.format("*") + full_paths = glob.glob(os.path.join(checkpoint_dir, pattern)) + if not full_paths: + raise RuntimeError( + "Searcher unable to find checkpoint in {}".format(checkpoint_dir) + ) # TODO + most_recent_checkpoint = max(full_paths) + self.restore(most_recent_checkpoint) + + @property + def metric(self) -> str: + """The training result objective value attribute.""" + return self._metric + + @property + def mode(self) -> str: + """Specifies if minimizing or maximizing the metric.""" + return self._mode + + +@PublicAPI +class ConcurrencyLimiter(Searcher): + """A wrapper algorithm for limiting the number of concurrent trials. + + Certain Searchers have their own internal logic for limiting + the number of concurrent trials. If such a Searcher is passed to a + ``ConcurrencyLimiter``, the ``max_concurrent`` of the + ``ConcurrencyLimiter`` will override the ``max_concurrent`` value + of the Searcher. The ``ConcurrencyLimiter`` will then let the + Searcher's internal logic take over. + + Args: + searcher: Searcher object that the + ConcurrencyLimiter will manage. + max_concurrent: Maximum concurrent samples from the underlying + searcher. + batch: Whether to wait for all concurrent samples + to finish before updating the underlying searcher. + + Example: + + .. code-block:: python + + from ray.tune.search import ConcurrencyLimiter + search_alg = HyperOptSearch(metric="accuracy") + search_alg = ConcurrencyLimiter(search_alg, max_concurrent=2) + tuner = tune.Tuner( + trainable_function, + tune_config=tune.TuneConfig( + search_alg=search_alg + ), + ) + tuner.fit() + + """ + + def __init__(self, searcher: Searcher, max_concurrent: int, batch: bool = False): + assert type(max_concurrent) is int and max_concurrent > 0 + self.searcher = searcher + self.max_concurrent = max_concurrent + self.batch = batch + self.live_trials = set() + self.num_unfinished_live_trials = 0 + self.cached_results = {} + self._limit_concurrency = True + + if not isinstance(searcher, Searcher): + raise RuntimeError( + f"The `ConcurrencyLimiter` only works with `Searcher` " + f"objects (got {type(searcher)}). Please try to pass " + f"`max_concurrent` to the search generator directly." + ) + + self._set_searcher_max_concurrency() + + super(ConcurrencyLimiter, self).__init__( + metric=self.searcher.metric, mode=self.searcher.mode + ) + + def _set_searcher_max_concurrency(self): + # If the searcher has special logic for handling max concurrency, + # we do not do anything inside the ConcurrencyLimiter + self._limit_concurrency = not self.searcher.set_max_concurrency( + self.max_concurrent + ) + + def set_max_concurrency(self, max_concurrent: int) -> bool: + # Determine if this behavior is acceptable, or if it should + # raise an exception. + self.max_concurrent = max_concurrent + return True + + def set_search_properties( + self, metric: Optional[str], mode: Optional[str], config: Dict, **spec + ) -> bool: + self._set_searcher_max_concurrency() + return _set_search_properties_backwards_compatible( + self.searcher.set_search_properties, metric, mode, config, **spec + ) + + def suggest(self, trial_id: str) -> Optional[Dict]: + if not self._limit_concurrency: + return self.searcher.suggest(trial_id) + + assert ( + trial_id not in self.live_trials + ), f"Trial ID {trial_id} must be unique: already found in set." + if len(self.live_trials) >= self.max_concurrent: + logger.debug( + f"Not providing a suggestion for {trial_id} due to " + "concurrency limit: %s/%s.", + len(self.live_trials), + self.max_concurrent, + ) + return + + suggestion = self.searcher.suggest(trial_id) + if suggestion not in (None, Searcher.FINISHED): + self.live_trials.add(trial_id) + self.num_unfinished_live_trials += 1 + return suggestion + + def on_trial_complete( + self, trial_id: str, result: Optional[Dict] = None, error: bool = False + ): + if not self._limit_concurrency: + return self.searcher.on_trial_complete(trial_id, result=result, error=error) + + if trial_id not in self.live_trials: + return + elif self.batch: + self.cached_results[trial_id] = (result, error) + self.num_unfinished_live_trials -= 1 + if self.num_unfinished_live_trials <= 0: + # Update the underlying searcher once the + # full batch is completed. + for trial_id, (result, error) in self.cached_results.items(): + self.searcher.on_trial_complete( + trial_id, result=result, error=error + ) + self.live_trials.remove(trial_id) + self.cached_results = {} + self.num_unfinished_live_trials = 0 + else: + return + else: + self.searcher.on_trial_complete(trial_id, result=result, error=error) + self.live_trials.remove(trial_id) + self.num_unfinished_live_trials -= 1 + + def on_trial_result(self, trial_id: str, result: Dict) -> None: + self.searcher.on_trial_result(trial_id, result) + + def add_evaluated_point( + self, + parameters: Dict, + value: float, + error: bool = False, + pruned: bool = False, + intermediate_values: Optional[List[float]] = None, + ): + return self.searcher.add_evaluated_point( + parameters, value, error, pruned, intermediate_values + ) + + def get_state(self) -> Dict: + state = self.__dict__.copy() + del state["searcher"] + return copy.deepcopy(state) + + def set_state(self, state: Dict): + self.__dict__.update(state) + + def save(self, checkpoint_path: str): + self.searcher.save(checkpoint_path) + + def restore(self, checkpoint_path: str): + self.searcher.restore(checkpoint_path) diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/util.py b/venv/lib/python3.10/site-packages/ray/tune/search/util.py new file mode 100644 index 0000000000000000000000000000000000000000..9358bd32af6373aa62ee60b1d197544b10691608 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/util.py @@ -0,0 +1,31 @@ +import logging +from typing import Dict, Optional + +logger = logging.getLogger(__name__) + + +def _set_search_properties_backwards_compatible( + set_search_properties_func, + metric: Optional[str], + mode: Optional[str], + config: Dict, + **spec +) -> bool: + """Wraps around set_search_properties() so that it is backward compatible. + + Also outputs a warning to encourage custom searchers to be updated. + """ + try: + return set_search_properties_func(metric, mode, config, **spec) + except TypeError as e: + if str(e).startswith( + "set_search_properties() got an unexpected keyword argument" + ): + logger.warning( + "Please update custom Searcher to take in function signature " + "as ``def set_search_properties(metric, mode, config, " + "**spec) -> bool``." + ) + return set_search_properties_func(metric, mode, config) + else: + raise e diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/variant_generator.py b/venv/lib/python3.10/site-packages/ray/tune/search/variant_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..4da50c92e4af56374e4874c5cf3d9bc6fd27dddf --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/variant_generator.py @@ -0,0 +1,523 @@ +import copy +import logging +import random +import re +from collections.abc import Mapping +from typing import Any, Dict, Generator, Iterable, List, Optional, Tuple + +import numpy + +from ray.tune.search.sample import Categorical, Domain, Function, RandomState +from ray.util.annotations import DeveloperAPI, PublicAPI + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +def generate_variants( + unresolved_spec: Dict, + constant_grid_search: bool = False, + random_state: "RandomState" = None, +) -> Generator[Tuple[Dict, Dict], None, None]: + """Generates variants from a spec (dict) with unresolved values. + + There are two types of unresolved values: + + Grid search: These define a grid search over values. For example, the + following grid search values in a spec will produce six distinct + variants in combination: + + "activation": grid_search(["relu", "tanh"]) + "learning_rate": grid_search([1e-3, 1e-4, 1e-5]) + + Lambda functions: These are evaluated to produce a concrete value, and + can express dependencies or conditional distributions between values. + They can also be used to express random search (e.g., by calling + into the `random` or `np` module). + + "cpu": lambda spec: spec.config.num_workers + "batch_size": lambda spec: random.uniform(1, 1000) + + Finally, to support defining specs in plain JSON / YAML, grid search + and lambda functions can also be defined alternatively as follows: + + "activation": {"grid_search": ["relu", "tanh"]} + "cpu": {"eval": "spec.config.num_workers"} + + Use `format_vars` to format the returned dict of hyperparameters. + + Yields: + (Dict of resolved variables, Spec object) + """ + for resolved_vars, spec in _generate_variants_internal( + unresolved_spec, + constant_grid_search=constant_grid_search, + random_state=random_state, + ): + assert not _unresolved_values(spec) + yield resolved_vars, spec + + +@PublicAPI(stability="beta") +def grid_search(values: Iterable) -> Dict[str, Iterable]: + """Specify a grid of values to search over. + + Values specified in a grid search are guaranteed to be sampled. + + If multiple grid search variables are defined, they are combined with the + combinatorial product. This means every possible combination of values will + be sampled. + + Example: + + >>> from ray import tune + >>> param_space={ + ... "x": tune.grid_search([10, 20]), + ... "y": tune.grid_search(["a", "b", "c"]) + ... } + + This will create a grid of 6 samples: + ``{"x": 10, "y": "a"}``, ``{"x": 10, "y": "b"}``, etc. + + When specifying ``num_samples`` in the + :class:`TuneConfig `, this will specify + the number of random samples per grid search combination. + + For instance, in the example above, if ``num_samples=4``, + a total of 24 trials will be started - + 4 trials for each of the 6 grid search combinations. + + Args: + values: An iterable whose parameters will be used for creating a trial grid. + + """ + return {"grid_search": values} + + +_STANDARD_IMPORTS = { + "random": random, + "np": numpy, +} + +_MAX_RESOLUTION_PASSES = 20 + + +def _resolve_nested_dict(nested_dict: Dict) -> Dict[Tuple, Any]: + """Flattens a nested dict by joining keys into tuple of paths. + + Can then be passed into `format_vars`. + """ + res = {} + for k, v in nested_dict.items(): + if isinstance(v, dict): + for k_, v_ in _resolve_nested_dict(v).items(): + res[(k,) + k_] = v_ + else: + res[(k,)] = v + return res + + +@DeveloperAPI +def format_vars(resolved_vars: Dict) -> str: + """Format variables to be used as experiment tags. + + Experiment tags are used in directory names, so this method makes sure + the resulting tags can be legally used in directory names on all systems. + + The input to this function is a dict of the form + ``{("nested", "config", "path"): "value"}``. The output will be a comma + separated string of the form ``last_key=value``, so in this example + ``path=value``. + + Note that the sanitizing implies that empty strings are possible return + values. This is expected and acceptable, as it is not a common case and + the resulting directory names will still be valid. + + Args: + resolved_vars: Dictionary mapping from config path tuples to a value. + + Returns: + Comma-separated key=value string. + """ + vars = resolved_vars.copy() + # TrialRunner already has these in the experiment_tag + for v in ["run", "env", "resources_per_trial"]: + vars.pop(v, None) + + return ",".join( + f"{_clean_value(k[-1])}={_clean_value(v)}" for k, v in sorted(vars.items()) + ) + + +def _flatten_resolved_vars(resolved_vars: Dict) -> Dict: + """Formats the resolved variable dict into a mapping of (str -> value).""" + flattened_resolved_vars_dict = {} + for pieces, value in resolved_vars.items(): + if pieces[0] == "config": + pieces = pieces[1:] + pieces = [str(piece) for piece in pieces] + flattened_resolved_vars_dict["/".join(pieces)] = value + return flattened_resolved_vars_dict + + +def _clean_value(value: Any) -> str: + """Format floats and replace invalid string characters with ``_``.""" + if isinstance(value, float): + return f"{value:.4f}" + else: + # Define an invalid alphabet, which is the inverse of the + # stated regex characters + invalid_alphabet = r"[^a-zA-Z0-9_-]+" + return re.sub(invalid_alphabet, "_", str(value)).strip("_") + + +@DeveloperAPI +def parse_spec_vars( + spec: Dict, +) -> Tuple[List[Tuple[Tuple, Any]], List[Tuple[Tuple, Any]], List[Tuple[Tuple, Any]]]: + resolved, unresolved = _split_resolved_unresolved_values(spec) + resolved_vars = list(resolved.items()) + + if not unresolved: + return resolved_vars, [], [] + + grid_vars = [] + domain_vars = [] + for path, value in unresolved.items(): + if value.is_grid(): + grid_vars.append((path, value)) + else: + domain_vars.append((path, value)) + grid_vars.sort() + + return resolved_vars, domain_vars, grid_vars + + +def _count_spec_samples(spec: Dict, num_samples=1) -> int: + """Count samples for a specific spec""" + _, domain_vars, grid_vars = parse_spec_vars(spec) + grid_count = 1 + for path, domain in grid_vars: + grid_count *= len(domain.categories) + return num_samples * grid_count + + +def _count_variants(spec: Dict, presets: Optional[List[Dict]] = None) -> int: + # Helper function: Deep update dictionary + def deep_update(d, u): + for k, v in u.items(): + if isinstance(v, Mapping): + d[k] = deep_update(d.get(k, {}), v) + else: + d[k] = v + return d + + total_samples = 0 + total_num_samples = spec.get("num_samples", 1) + # For each preset, overwrite the spec and count the samples generated + # for this preset + for preset in presets: + preset_spec = copy.deepcopy(spec) + deep_update(preset_spec["config"], preset) + total_samples += _count_spec_samples(preset_spec, 1) + total_num_samples -= 1 + + # Add the remaining samples + if total_num_samples > 0: + total_samples += _count_spec_samples(spec, total_num_samples) + return total_samples + + +def _generate_variants_internal( + spec: Dict, constant_grid_search: bool = False, random_state: "RandomState" = None +) -> Tuple[Dict, Dict]: + spec = copy.deepcopy(spec) + _, domain_vars, grid_vars = parse_spec_vars(spec) + + if not domain_vars and not grid_vars: + yield {}, spec + return + + # Variables to resolve + to_resolve = domain_vars + + all_resolved = True + if constant_grid_search: + # In this path, we first sample random variables and keep them constant + # for grid search. + # `_resolve_domain_vars` will alter `spec` directly + all_resolved, resolved_vars = _resolve_domain_vars( + spec, domain_vars, allow_fail=True, random_state=random_state + ) + if not all_resolved: + # Not all variables have been resolved, but remove those that have + # from the `to_resolve` list. + to_resolve = [(r, d) for r, d in to_resolve if r not in resolved_vars] + grid_search = _grid_search_generator(spec, grid_vars) + for resolved_spec in grid_search: + if not constant_grid_search or not all_resolved: + # In this path, we sample the remaining random variables + _, resolved_vars = _resolve_domain_vars( + resolved_spec, to_resolve, random_state=random_state + ) + + for resolved, spec in _generate_variants_internal( + resolved_spec, + constant_grid_search=constant_grid_search, + random_state=random_state, + ): + for path, value in grid_vars: + resolved_vars[path] = _get_value(spec, path) + for k, v in resolved.items(): + if ( + k in resolved_vars + and v != resolved_vars[k] + and _is_resolved(resolved_vars[k]) + ): + raise ValueError( + "The variable `{}` could not be unambiguously " + "resolved to a single value. Consider simplifying " + "your configuration.".format(k) + ) + resolved_vars[k] = v + yield resolved_vars, spec + + +def _get_preset_variants( + spec: Dict, + config: Dict, + constant_grid_search: bool = False, + random_state: "RandomState" = None, +): + """Get variants according to a spec, initialized with a config. + + Variables from the spec are overwritten by the variables in the config. + Thus, we may end up with less sampled parameters. + + This function also checks if values used to overwrite search space + parameters are valid, and logs a warning if not. + """ + spec = copy.deepcopy(spec) + + resolved, _, _ = parse_spec_vars(config) + + for path, val in resolved: + try: + domain = _get_value(spec["config"], path) + if isinstance(domain, dict): + if "grid_search" in domain: + domain = Categorical(domain["grid_search"]) + else: + # If users want to overwrite an entire subdict, + # let them do it. + domain = None + except IndexError as exc: + raise ValueError( + f"Pre-set config key `{'/'.join(path)}` does not correspond " + f"to a valid key in the search space definition. Please add " + f"this path to the `param_space` variable passed to `tune.Tuner()`." + ) from exc + + if domain: + if isinstance(domain, Domain): + if not domain.is_valid(val): + logger.warning( + f"Pre-set value `{val}` is not within valid values of " + f"parameter `{'/'.join(path)}`: {domain.domain_str}" + ) + else: + # domain is actually a fixed value + if domain != val: + logger.warning( + f"Pre-set value `{val}` is not equal to the value of " + f"parameter `{'/'.join(path)}`: {domain}" + ) + assign_value(spec["config"], path, val) + + return _generate_variants_internal( + spec, constant_grid_search=constant_grid_search, random_state=random_state + ) + + +@DeveloperAPI +def assign_value(spec: Dict, path: Tuple, value: Any): + """Assigns a value to a nested dictionary. + + Handles the special case of tuples, in which case the tuples + will be re-constructed to accomodate the updated value. + """ + parent_spec = None + parent_key = None + for k in path[:-1]: + parent_spec = spec + parent_key = k + spec = spec[k] + key = path[-1] + if not isinstance(spec, tuple): + # spec is mutable. Just assign the value. + spec[key] = value + else: + if parent_spec is None: + raise ValueError("Cannot assign value to a tuple.") + assert isinstance(key, int), "Tuple key must be an int." + # Special handling since tuples are immutable. + parent_spec[parent_key] = spec[:key] + (value,) + spec[key + 1 :] + + +def _get_value(spec: Dict, path: Tuple) -> Any: + for k in path: + spec = spec[k] + return spec + + +def _resolve_domain_vars( + spec: Dict, + domain_vars: List[Tuple[Tuple, Domain]], + allow_fail: bool = False, + random_state: "RandomState" = None, +) -> Tuple[bool, Dict]: + resolved = {} + error = True + num_passes = 0 + while error and num_passes < _MAX_RESOLUTION_PASSES: + num_passes += 1 + error = False + for path, domain in domain_vars: + if path in resolved: + continue + try: + value = domain.sample( + _UnresolvedAccessGuard(spec), random_state=random_state + ) + except RecursiveDependencyError as e: + error = e + except Exception: + raise ValueError( + "Failed to evaluate expression: {}: {}".format(path, domain) + ) + else: + assign_value(spec, path, value) + resolved[path] = value + if error: + if not allow_fail: + raise error + else: + return False, resolved + return True, resolved + + +def _grid_search_generator( + unresolved_spec: Dict, grid_vars: List +) -> Generator[Dict, None, None]: + value_indices = [0] * len(grid_vars) + + def increment(i): + value_indices[i] += 1 + if value_indices[i] >= len(grid_vars[i][1]): + value_indices[i] = 0 + if i + 1 < len(value_indices): + return increment(i + 1) + else: + return True + return False + + if not grid_vars: + yield unresolved_spec + return + + while value_indices[-1] < len(grid_vars[-1][1]): + spec = copy.deepcopy(unresolved_spec) + for i, (path, values) in enumerate(grid_vars): + assign_value(spec, path, values[value_indices[i]]) + yield spec + if grid_vars: + done = increment(0) + if done: + break + + +def _is_resolved(v) -> bool: + resolved, _ = _try_resolve(v) + return resolved + + +def _try_resolve(v) -> Tuple[bool, Any]: + if isinstance(v, Domain): + # Domain to sample from + return False, v + elif isinstance(v, dict) and len(v) == 1 and "eval" in v: + # Lambda function in eval syntax + return False, Function( + lambda spec: eval(v["eval"], _STANDARD_IMPORTS, {"spec": spec}) + ) + elif isinstance(v, dict) and len(v) == 1 and "grid_search" in v: + # Grid search values + grid_values = v["grid_search"] + return False, Categorical(grid_values).grid() + return True, v + + +def _split_resolved_unresolved_values( + spec: Dict, +) -> Tuple[Dict[Tuple, Any], Dict[Tuple, Any]]: + resolved_vars = {} + unresolved_vars = {} + for k, v in spec.items(): + resolved, v = _try_resolve(v) + if not resolved: + unresolved_vars[(k,)] = v + elif isinstance(v, dict): + # Recurse into a dict + ( + _resolved_children, + _unresolved_children, + ) = _split_resolved_unresolved_values(v) + for path, value in _resolved_children.items(): + resolved_vars[(k,) + path] = value + for path, value in _unresolved_children.items(): + unresolved_vars[(k,) + path] = value + elif isinstance(v, (list, tuple)): + # Recurse into a list + for i, elem in enumerate(v): + ( + _resolved_children, + _unresolved_children, + ) = _split_resolved_unresolved_values({i: elem}) + for path, value in _resolved_children.items(): + resolved_vars[(k,) + path] = value + for path, value in _unresolved_children.items(): + unresolved_vars[(k,) + path] = value + else: + resolved_vars[(k,)] = v + return resolved_vars, unresolved_vars + + +def _unresolved_values(spec: Dict) -> Dict[Tuple, Any]: + return _split_resolved_unresolved_values(spec)[1] + + +def _has_unresolved_values(spec: Dict) -> bool: + return True if _unresolved_values(spec) else False + + +class _UnresolvedAccessGuard(dict): + def __init__(self, *args, **kwds): + super(_UnresolvedAccessGuard, self).__init__(*args, **kwds) + self.__dict__ = self + + def __getattribute__(self, item): + value = dict.__getattribute__(self, item) + if not _is_resolved(value): + raise RecursiveDependencyError( + "`{}` recursively depends on {}".format(item, value) + ) + elif isinstance(value, dict): + return _UnresolvedAccessGuard(value) + else: + return value + + +@DeveloperAPI +class RecursiveDependencyError(Exception): + def __init__(self, msg: str): + Exception.__init__(self, msg) diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/zoopt/__init__.py b/venv/lib/python3.10/site-packages/ray/tune/search/zoopt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..44ab8e345754da48205fbe712e4bb787a5ddfc2a --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/search/zoopt/__init__.py @@ -0,0 +1,3 @@ +from ray.tune.search.zoopt.zoopt_search import ZOOptSearch + +__all__ = ["ZOOptSearch"] diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/zoopt/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/zoopt/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9a95c70514d8d22f73a1d903312f0a39446391a Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/zoopt/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/search/zoopt/__pycache__/zoopt_search.cpython-310.pyc b/venv/lib/python3.10/site-packages/ray/tune/search/zoopt/__pycache__/zoopt_search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d93f533257818d1bdaa5749efb3abc7b3c419b57 Binary files /dev/null and b/venv/lib/python3.10/site-packages/ray/tune/search/zoopt/__pycache__/zoopt_search.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/ray/tune/syncer.py b/venv/lib/python3.10/site-packages/ray/tune/syncer.py new file mode 100644 index 0000000000000000000000000000000000000000..890d06593b582204c4ddfd7c46a928a20208d55f --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/syncer.py @@ -0,0 +1,46 @@ +import logging +from dataclasses import dataclass + +from ray.train._internal.syncer import SyncConfig as TrainSyncConfig +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="beta") +@dataclass +class SyncConfig(TrainSyncConfig): + """Configuration object for Tune file syncing to `RunConfig(storage_path)`. + + In Ray Tune, here is where syncing (mainly uploading) happens: + + The experiment driver (on the head node) syncs the experiment directory to storage + (which includes experiment state such as searcher state, the list of trials + and their statuses, and trial metadata). + + It's also possible to sync artifacts from the trial directory to storage + by setting `sync_artifacts=True`. + For a Ray Tune run with many trials, each trial will upload its trial directory + to storage, which includes arbitrary files that you dumped during the run. + + Args: + sync_period: Minimum time in seconds to wait between two sync operations. + A smaller ``sync_period`` will have the data in storage updated more often + but introduces more syncing overhead. Defaults to 5 minutes. + sync_timeout: Maximum time in seconds to wait for a sync process + to finish running. A sync operation will run for at most this long + before raising a `TimeoutError`. Defaults to 30 minutes. + sync_artifacts: [Beta] Whether or not to sync artifacts that are saved to the + trial directory (accessed via `ray.tune.get_context().get_trial_dir()`) + to the persistent storage configured via `tune.RunConfig(storage_path)`. + The trial or remote worker will try to launch an artifact syncing + operation every time `tune.report` happens, subject to `sync_period` + and `sync_artifacts_on_checkpoint`. + Defaults to False -- no artifacts are persisted by default. + sync_artifacts_on_checkpoint: If True, trial/worker artifacts are + forcefully synced on every reported checkpoint. + This only has an effect if `sync_artifacts` is True. + Defaults to True. + """ + + pass diff --git a/venv/lib/python3.10/site-packages/ray/tune/tune.py b/venv/lib/python3.10/site-packages/ray/tune/tune.py new file mode 100644 index 0000000000000000000000000000000000000000..ac61a9ddacf81b983b98b7413311a0f312671ad4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/tune.py @@ -0,0 +1,1161 @@ +import abc +import copy +import datetime +import logging +import os +import signal +import sys +import threading +import time +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Mapping, + Optional, + Sequence, + Type, + Union, +) + +import ray +from ray.air._internal import usage as air_usage +from ray.air._internal.usage import AirEntrypoint +from ray.air.util.node import _force_on_current_node +from ray.train.constants import _DEPRECATED_VALUE, RAY_CHDIR_TO_TRIAL_DIR +from ray.tune import CheckpointConfig, SyncConfig +from ray.tune.analysis import ExperimentAnalysis +from ray.tune.callback import Callback +from ray.tune.error import TuneError +from ray.tune.execution.placement_groups import PlacementGroupFactory +from ray.tune.execution.tune_controller import TuneController +from ray.tune.experiment import Experiment, Trial, _convert_to_experiment_list +from ray.tune.experimental.output import IS_NOTEBOOK, AirVerbosity, get_air_verbosity +from ray.tune.impl.placeholder import create_resolvers_map, inject_placeholders +from ray.tune.logger import TBXLoggerCallback +from ray.tune.progress_reporter import ( + ProgressReporter, + _detect_progress_metrics, + _detect_reporter, + _prepare_progress_reporter_for_ray_client, + _stream_client_output, +) +from ray.tune.registry import get_trainable_cls + +# Must come last to avoid circular imports +from ray.tune.schedulers import ( + FIFOScheduler, + PopulationBasedTraining, + PopulationBasedTrainingReplay, + TrialScheduler, +) +from ray.tune.schedulers.util import ( + _set_search_properties_backwards_compatible as scheduler_set_search_props, +) +from ray.tune.search import ( + BasicVariantGenerator, + ConcurrencyLimiter, + SearchAlgorithm, + Searcher, + SearchGenerator, + create_searcher, +) +from ray.tune.search.util import ( + _set_search_properties_backwards_compatible as searcher_set_search_props, +) +from ray.tune.search.variant_generator import _has_unresolved_values +from ray.tune.stopper import Stopper +from ray.tune.trainable import Trainable +from ray.tune.tune_config import ResumeConfig +from ray.tune.utils.callback import _create_default_callbacks +from ray.tune.utils.log import Verbosity, has_verbosity, set_verbosity +from ray.util.annotations import PublicAPI +from ray.util.queue import Queue + +if TYPE_CHECKING: + import pyarrow.fs + + from ray.tune.experimental.output import ProgressReporter as AirProgressReporter + +logger = logging.getLogger(__name__) + + +def _get_trainable( + run_identifier: Union[Experiment, str, Type, Callable] +) -> Optional[Type[Trainable]]: + if isinstance(run_identifier, Experiment): + run_identifier = run_identifier.run_identifier + + if isinstance(run_identifier, type): + if not issubclass(run_identifier, Trainable): + # If obscure dtype, assume it is overridden. + return None + trainable_cls = run_identifier + elif callable(run_identifier): + trainable_cls = run_identifier + elif isinstance(run_identifier, str): + trainable_cls = get_trainable_cls(run_identifier) + else: + return None + + return trainable_cls + + +def _build_resume_config_from_legacy_config( + resume: Union[str, bool] +) -> Optional[ResumeConfig]: + """Converts the legacy resume (str, bool) to a ResumeConfig object. + Returns None if resume is False. + """ + if resume is False: + return None + if resume is True: + return ResumeConfig() + + # Parse resume string, e.g. AUTO+ERRORED + resume_settings = resume.split("+") + resume_str = resume_settings[0] + + if resume_str in ("LOCAL", "REMOTE", "PROMPT", "ERRORED_ONLY"): + raise DeprecationWarning( + f"'{resume_str}' is deprecated. " + "Please pass in one of (True, False, 'AUTO')." + ) + + resume_config = ResumeConfig() + for setting in resume_settings[1:]: + if setting == "ERRORED": + resume_config = ResumeConfig(errored=ResumeConfig.ResumeType.RESUME) + elif setting == "RESTART_ERRORED": + resume_config = ResumeConfig(errored=ResumeConfig.ResumeType.RESTART) + elif setting == "ERRORED_ONLY": + resume_config = ResumeConfig( + unfinished=ResumeConfig.ResumeType.SKIP, + errored=ResumeConfig.ResumeType.RESUME, + ) + elif setting == "RESTART_ERRORED_ONLY": + resume_config = ResumeConfig( + unfinished=ResumeConfig.ResumeType.SKIP, + errored=ResumeConfig.ResumeType.RESTART, + ) + else: + raise ValueError(f"Invalid resume setting: '{setting}'") + + return resume_config + + +def _check_default_resources_override( + run_identifier: Union[Experiment, str, Type, Callable] +) -> bool: + trainable_cls = _get_trainable(run_identifier) + if not trainable_cls: + # If no trainable, assume override + return True + + return hasattr(trainable_cls, "default_resource_request") and ( + trainable_cls.default_resource_request.__code__ + != Trainable.default_resource_request.__code__ + ) + + +def _check_mixin(run_identifier: Union[Experiment, str, Type, Callable]) -> bool: + trainable_cls = _get_trainable(run_identifier) + if not trainable_cls: + # Default to True + return True + + return hasattr(trainable_cls, "__mixins__") or getattr( + trainable_cls, "_is_mixin", False + ) + + +def _check_gpus_in_resources( + resources: Optional[Union[Dict, PlacementGroupFactory]] +) -> bool: + if not resources: + return False + + if isinstance(resources, PlacementGroupFactory): + return bool(resources.required_resources.get("GPU", None)) + + if isinstance(resources, dict): + return bool(resources.get("gpu", None)) + + +def _report_progress( + runner: TuneController, reporter: ProgressReporter, done: bool = False +): + """Reports experiment progress. + + Args: + runner: Trial runner to report on. + reporter: Progress reporter. + done: Whether this is the last progress report attempt. + """ + trials = runner.get_trials() + if reporter.should_report(trials, done=done): + sched_debug_str = runner.scheduler_alg.debug_string() + used_resources_str = runner._used_resources_string() + reporter.report(trials, done, sched_debug_str, used_resources_str) + + +def _report_air_progress( + runner: TuneController, reporter: "AirProgressReporter", force: bool = False +): + trials = runner.get_trials() + reporter_args = [] + used_resources_string = runner._used_resources_string() + reporter_args.append(used_resources_string) + reporter.print_heartbeat(trials, *reporter_args, force=force) + + +def _setup_signal_catching() -> threading.Event: + original_handler = signal.getsignal(signal.SIGINT) + experiment_interrupted_event = threading.Event() + + def signal_interrupt_tune_run(sig: int, frame): + logger.warning( + "Stop signal received (e.g. via SIGINT/Ctrl+C), ending Ray Tune run. " + "This will try to checkpoint the experiment state one last time. " + "Press CTRL+C (or send SIGINT/SIGKILL/SIGTERM) " + "to skip. " + ) + experiment_interrupted_event.set() + # Restore original signal handler to react to future SIGINT signals. + signal.signal(signal.SIGINT, original_handler) + + # We should only install the handler when it is safe to do so. + # When tune.run() is called from worker thread, signal.signal will + # fail. + allow_signal_catching = True + if threading.current_thread() != threading.main_thread(): + allow_signal_catching = False + + if allow_signal_catching: + if not int(os.getenv("TUNE_DISABLE_SIGINT_HANDLER", "0")): + signal.signal(signal.SIGINT, signal_interrupt_tune_run) + + # Always register SIGUSR1 if available (not available e.g. on Windows) + if hasattr(signal, "SIGUSR1"): + signal.signal(signal.SIGUSR1, signal_interrupt_tune_run) + + return experiment_interrupted_event + + +def _ray_auto_init(entrypoint: str): + """Initialize Ray unless already configured.""" + if os.environ.get("TUNE_DISABLE_AUTO_INIT") == "1": + logger.info("'TUNE_DISABLE_AUTO_INIT=1' detected.") + elif not ray.is_initialized(): + ray.init() + logger.info( + "Initializing Ray automatically. " + "For cluster usage or custom Ray initialization, " + f"call `ray.init(...)` before `{entrypoint}`." + ) + + +class _Config(abc.ABC): + def to_dict(self) -> dict: + """Converts this configuration to a dict format.""" + raise NotImplementedError + + +@PublicAPI +def run( + run_or_experiment: Union[str, Callable, Type], + *, + name: Optional[str] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + stop: Optional[Union[Mapping, Stopper, Callable[[str, Mapping], bool]]] = None, + time_budget_s: Optional[Union[int, float, datetime.timedelta]] = None, + config: Optional[Dict[str, Any]] = None, + resources_per_trial: Union[ + None, Mapping[str, Union[float, int, Mapping]], PlacementGroupFactory + ] = None, + num_samples: int = 1, + storage_path: Optional[str] = None, + storage_filesystem: Optional["pyarrow.fs.FileSystem"] = None, + search_alg: Optional[Union[Searcher, SearchAlgorithm, str]] = None, + scheduler: Optional[Union[TrialScheduler, str]] = None, + checkpoint_config: Optional[CheckpointConfig] = None, + verbose: Optional[Union[int, AirVerbosity, Verbosity]] = None, + progress_reporter: Optional[ProgressReporter] = None, + log_to_file: bool = False, + trial_name_creator: Optional[Callable[[Trial], str]] = None, + trial_dirname_creator: Optional[Callable[[Trial], str]] = None, + sync_config: Optional[SyncConfig] = None, + export_formats: Optional[Sequence] = None, + max_failures: int = 0, + fail_fast: bool = False, + restore: Optional[str] = None, + resume: Optional[Union[bool, str]] = None, + resume_config: Optional[ResumeConfig] = None, + reuse_actors: bool = False, + raise_on_failed_trial: bool = True, + callbacks: Optional[Sequence[Callback]] = None, + max_concurrent_trials: Optional[int] = None, + # Deprecated + keep_checkpoints_num: Optional[int] = None, # Deprecated (2.7) + checkpoint_score_attr: Optional[str] = None, # Deprecated (2.7) + checkpoint_freq: int = 0, # Deprecated (2.7) + checkpoint_at_end: bool = False, # Deprecated (2.7) + chdir_to_trial_dir: bool = _DEPRECATED_VALUE, # Deprecated (2.8) + local_dir: Optional[str] = None, + # == internal only == + _remote: Optional[bool] = None, + # Passed by the Tuner. + _remote_string_queue: Optional[Queue] = None, + # Todo (krfricke): Find a better way to pass entrypoint information, e.g. + # a context object or similar. + _entrypoint: AirEntrypoint = AirEntrypoint.TUNE_RUN, +) -> ExperimentAnalysis: + """Executes training. + + When a SIGINT signal is received (e.g. through Ctrl+C), the tuning run + will gracefully shut down and checkpoint the latest experiment state. + Sending SIGINT again (or SIGKILL/SIGTERM instead) will skip this step. + + Many aspects of Tune, such as the frequency of global checkpointing, + maximum pending placement group trials and the path of the result + directory be configured through environment variables. Refer to + :ref:`tune-env-vars` for a list of environment variables available. + + Examples: + + .. code-block:: python + + # Run 10 trials (each trial is one instance of a Trainable). Tune runs + # in parallel and automatically determines concurrency. + tune.run(trainable, num_samples=10) + + # Run 1 trial, stop when trial has reached 10 iterations + tune.run(my_trainable, stop={"training_iteration": 10}) + + # automatically retry failed trials up to 3 times + tune.run(my_trainable, stop={"training_iteration": 10}, max_failures=3) + + # Run 1 trial, search over hyperparameters, stop after 10 iterations. + space = {"lr": tune.uniform(0, 1), "momentum": tune.uniform(0, 1)} + tune.run(my_trainable, config=space, stop={"training_iteration": 10}) + + # Resumes training if a previous machine crashed + tune.run( + my_trainable, config=space, + storage_path=, name=, resume=True + ) + + Args: + run_or_experiment: If function|class|str, this is the algorithm or + model to train. This may refer to the name of a built-on algorithm + (e.g. RLlib's DQN or PPO), a user-defined trainable + function or class, or the string identifier of a + trainable function or class registered in the tune registry. + If Experiment, then Tune will execute training based on + Experiment.spec. If you want to pass in a Python lambda, you + will need to first register the function: + ``tune.register_trainable("lambda_id", lambda x: ...)``. You can + then use ``tune.run("lambda_id")``. + metric: Metric to optimize. This metric should be reported + with `tune.report()`. If set, will be passed to the search + algorithm and scheduler. + mode: Must be one of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. If set, will be + passed to the search algorithm and scheduler. + name: Name of experiment. + stop: Stopping criteria. If dict, + the keys may be any field in the return result of 'train()', + whichever is reached first. If function, it must take (trial_id, + result) as arguments and return a boolean (True if trial should be + stopped, False otherwise). This can also be a subclass of + ``ray.tune.Stopper``, which allows users to implement + custom experiment-wide stopping (i.e., stopping an entire Tune + run based on some time constraint). + time_budget_s: Global time budget in + seconds after which all trials are stopped. Can also be a + ``datetime.timedelta`` object. + config: Algorithm-specific configuration for Tune variant + generation (e.g. env, hyperparams). Defaults to empty dict. + Custom search algorithms may ignore this. + resources_per_trial: Machine resources + to allocate per trial, e.g. ``{"cpu": 64, "gpu": 8}``. + Note that GPUs will not be assigned unless you specify them here. + Defaults to 1 CPU and 0 GPUs in + ``Trainable.default_resource_request()``. This can also + be a PlacementGroupFactory object wrapping arguments to create a + per-trial placement group. + num_samples: Number of times to sample from the + hyperparameter space. Defaults to 1. If `grid_search` is + provided as an argument, the grid will be repeated + `num_samples` of times. If this is -1, (virtually) infinite + samples are generated until a stopping condition is met. + storage_path: Path to store results at. Can be a local directory or + a destination on cloud storage. Defaults to + the local ``~/ray_results`` directory. + search_alg: Search algorithm for + optimization. You can also use the name of the algorithm. + scheduler: Scheduler for executing + the experiment. Choose among FIFO (default), MedianStopping, + AsyncHyperBand, HyperBand and PopulationBasedTraining. Refer to + ray.tune.schedulers for more options. You can also use the + name of the scheduler. + verbose: 0, 1, or 2. Verbosity mode. + 0 = silent, 1 = default, 2 = verbose. Defaults to 1. + If the ``RAY_AIR_NEW_OUTPUT=1`` environment variable is set, + uses the old verbosity settings: + 0 = silent, 1 = only status updates, 2 = status and brief + results, 3 = status and detailed results. + progress_reporter: Progress reporter for reporting + intermediate experiment progress. Defaults to CLIReporter if + running in command-line, or JupyterNotebookReporter if running in + a Jupyter notebook. + log_to_file: Log stdout and stderr to files in + Tune's trial directories. If this is `False` (default), no files + are written. If `true`, outputs are written to `trialdir/stdout` + and `trialdir/stderr`, respectively. If this is a single string, + this is interpreted as a file relative to the trialdir, to which + both streams are written. If this is a Sequence (e.g. a Tuple), + it has to have length 2 and the elements indicate the files to + which stdout and stderr are written, respectively. + trial_name_creator: Optional function that takes in a Trial and returns + its name (i.e. its string representation). Be sure to include some unique + identifier (such as `Trial.trial_id`) in each trial's name. + trial_dirname_creator: Optional function that takes in a trial and + generates its trial directory name as a string. Be sure to include some + unique identifier (such as `Trial.trial_id`) is used in each trial's + directory name. Otherwise, trials could overwrite artifacts and checkpoints + of other trials. The return value cannot be a path. + chdir_to_trial_dir: Deprecated. Set the `RAY_CHDIR_TO_TRIAL_DIR` env var instead + sync_config: Configuration object for syncing. See tune.SyncConfig. + export_formats: List of formats that exported at the end of + the experiment. Default is None. + max_failures: Try to recover a trial at least this many times. + Ray will recover from the latest checkpoint if present. + Setting to -1 will lead to infinite recovery retries. + Setting to 0 will disable retries. Defaults to 0. + fail_fast: Whether to fail upon the first error. + If fail_fast='raise' provided, Tune will automatically + raise the exception received by the Trainable. fail_fast='raise' + can easily leak resources and should be used with caution (it + is best used with `ray.init(local_mode=True)`). + restore: Path to checkpoint. Only makes sense to set if + running 1 trial. Defaults to None. + resume: One of [True, False, "AUTO"]. Can + be suffixed with one or more of ["+ERRORED", "+ERRORED_ONLY", + "+RESTART_ERRORED", "+RESTART_ERRORED_ONLY"] (e.g. ``AUTO+ERRORED``). + `resume=True` and `resume="AUTO"` will attempt to resume from a + checkpoint and otherwise start a new experiment. + The suffix "+ERRORED" resets and reruns errored trials upon resume - + previous trial artifacts will be left untouched. It will try to continue + from the last observed checkpoint. + The suffix "+RESTART_ERRORED" will instead start the errored trials from + scratch. "+ERRORED_ONLY" and "+RESTART_ERRORED_ONLY" will disable + resuming non-errored trials - they will be added as finished instead. New + trials can still be generated by the search algorithm. + resume_config: [Experimental] Config object that controls how to resume + trials of different statuses. Can be used as a substitute to the + `resume` suffixes described above. + reuse_actors: Whether to reuse actors between different trials + when possible. This can drastically speed up experiments that start + and stop actors often (e.g., PBT in time-multiplexing mode). This + requires trials to have the same resource requirements. + Defaults to ``False``. + raise_on_failed_trial: Raise TuneError if there exists failed + trial (of ERROR state) when the experiments complete. + callbacks: List of callbacks that will be called at different + times in the training loop. Must be instances of the + ``ray.tune.callback.Callback`` class. If not passed, + `LoggerCallback` (json/csv/tensorboard) callbacks are automatically added. + max_concurrent_trials: Maximum number of trials to run + concurrently. Must be non-negative. If None or 0, no limit will + be applied. This is achieved by wrapping the ``search_alg`` in + a :class:`ConcurrencyLimiter`, and thus setting this argument + will raise an exception if the ``search_alg`` is already a + :class:`ConcurrencyLimiter`. Defaults to None. + _remote: Whether to run the Tune driver in a remote function. + This is disabled automatically if a custom trial executor is + passed in. This is enabled by default in Ray client mode. + local_dir: Deprecated. Use `storage_path` instead. + keep_checkpoints_num: Deprecated. use checkpoint_config instead. + checkpoint_score_attr: Deprecated. use checkpoint_config instead. + checkpoint_freq: Deprecated. use checkpoint_config instead. + checkpoint_at_end: Deprecated. use checkpoint_config instead. + checkpoint_keep_all_ranks: Deprecated. use checkpoint_config instead. + checkpoint_upload_from_workers: Deprecated. use checkpoint_config instead. + + Returns: + ExperimentAnalysis: Object for experiment analysis. + + Raises: + TuneError: Any trials failed and `raise_on_failed_trial` is True. + """ + # NO CODE IS TO BE ADDED ABOVE THIS COMMENT + # remote_run_kwargs must be defined before any other + # code is ran to ensure that at this point, + # `locals()` is equal to args and kwargs + remote_run_kwargs = locals().copy() + remote_run_kwargs.pop("_remote") + + if _entrypoint == AirEntrypoint.TRAINER: + error_message_map = { + "entrypoint": "(...)", + "search_space_arg": "param_space", + "restore_entrypoint": '.restore(path="{path}", ...)', + } + elif _entrypoint == AirEntrypoint.TUNER: + error_message_map = { + "entrypoint": "Tuner(...)", + "search_space_arg": "param_space", + "restore_entrypoint": 'Tuner.restore(path="{path}", trainable=...)', + } + elif _entrypoint == AirEntrypoint.TUNE_RUN_EXPERIMENTS: + error_message_map = { + "entrypoint": "tune.run_experiments(...)", + "search_space_arg": "experiment=Experiment(config)", + "restore_entrypoint": "tune.run_experiments(..., resume=True)", + } + else: + error_message_map = { + "entrypoint": "tune.run(...)", + "search_space_arg": "config", + "restore_entrypoint": "tune.run(..., resume=True)", + } + + _ray_auto_init(entrypoint=error_message_map["entrypoint"]) + + if _remote is None: + _remote = ray.util.client.ray.is_connected() + + if verbose is None: + # Default `verbose` value. For new output engine, this is AirVerbosity.VERBOSE. + # For old output engine, this is Verbosity.V3_TRIAL_DETAILS + verbose = get_air_verbosity(AirVerbosity.VERBOSE) or Verbosity.V3_TRIAL_DETAILS + + if _remote: + if get_air_verbosity(verbose) is not None: + logger.info( + "[output] This uses the legacy output and progress reporter, " + "as Ray client is not supported by the new engine. " + "For more information, see " + "https://github.com/ray-project/ray/issues/36949" + ) + + remote_run = ray.remote(num_cpus=0)(run) + + # Make sure tune.run is called on the sever node. + remote_run = _force_on_current_node(remote_run) + + progress_reporter, string_queue = _prepare_progress_reporter_for_ray_client( + progress_reporter, verbose, _remote_string_queue + ) + + # Override with detected progress reporter + remote_run_kwargs["progress_reporter"] = progress_reporter + + remote_future = remote_run.remote(_remote=False, **remote_run_kwargs) + + _stream_client_output( + remote_future, + progress_reporter, + string_queue, + ) + return ray.get(remote_future) + + del remote_run_kwargs + + # TODO(justinvyu): [Deprecated] Remove in 2.30 + ENV_VAR_DEPRECATION_MESSAGE = ( + "The environment variable `{}` is deprecated. " + "It is no longer used and will not have any effect. " + "You should set the `storage_path` instead. Files will no longer be " + "written to `~/ray_results` as long as `storage_path` is set." + "See the docs: https://docs.ray.io/en/latest/train/user-guides/" + "persistent-storage.html#setting-the-local-staging-directory" + ) + if os.environ.get("TUNE_RESULT_DIR"): + raise DeprecationWarning(ENV_VAR_DEPRECATION_MESSAGE.format("TUNE_RESULT_DIR")) + + if os.environ.get("RAY_AIR_LOCAL_CACHE_DIR"): + raise DeprecationWarning( + ENV_VAR_DEPRECATION_MESSAGE.format("RAY_AIR_LOCAL_CACHE_DIR") + ) + + if local_dir is not None: + raise DeprecationWarning( + "The `local_dir` argument is deprecated. " + "You should set the `storage_path` instead. " + "See the docs: https://docs.ray.io/en/latest/train/user-guides/" + "persistent-storage.html#setting-the-local-staging-directory" + ) + + ray._private.usage.usage_lib.record_library_usage("tune") + + # Tracking environment variable usage here will also catch: + # 1.) Tuner.fit() usage + # 2.) Trainer.fit() usage + # 3.) Ray client usage (env variables are inherited by the Ray runtime env) + air_usage.tag_ray_air_env_vars() + + # Track the entrypoint to AIR: + # Tuner.fit / Trainer.fit / tune.run / tune.run_experiments + air_usage.tag_air_entrypoint(_entrypoint) + + all_start = time.time() + + if mode and mode not in ["min", "max"]: + raise ValueError( + f"The `mode` parameter passed to `{error_message_map['entrypoint']}` " + "must be one of ['min', 'max']" + ) + + air_verbosity = get_air_verbosity(verbose) + if air_verbosity is not None and IS_NOTEBOOK: + logger.info( + "[output] This uses the legacy output and progress reporter, " + "as Jupyter notebooks are not supported by the new engine, yet. " + "For more information, please see " + "https://github.com/ray-project/ray/issues/36949" + ) + air_verbosity = None + + if air_verbosity is not None: + # Disable old output engine + set_verbosity(0) + else: + # Use old output engine + set_verbosity(verbose) + + config = config or {} + if isinstance(config, _Config): + config = config.to_dict() + if not isinstance(config, dict): + raise ValueError( + f"The `{error_message_map['search_space_arg']}` passed to " + f"`{error_message_map['entrypoint']}` must be a dict. " + f"Got '{type(config)}' instead." + ) + + sync_config = sync_config or SyncConfig() + checkpoint_config = checkpoint_config or CheckpointConfig() + + # For backward compatibility + # TODO(jungong): remove after 2.7 release. + if keep_checkpoints_num is not None: + warnings.warn( + "keep_checkpoints_num is deprecated and will be removed. " + "use checkpoint_config.num_to_keep instead.", + DeprecationWarning, + ) + checkpoint_config.num_to_keep = keep_checkpoints_num + if checkpoint_score_attr is not None: + warnings.warn( + "checkpoint_score_attr is deprecated and will be removed. " + "use checkpoint_config.checkpoint_score_attribute instead.", + DeprecationWarning, + ) + + if checkpoint_score_attr.startswith("min-"): + warnings.warn( + "using min- and max- prefixes to specify checkpoint score " + "order is deprecated. Use CheckpointConfig.checkpoint_score_order " + "instead", + DeprecationWarning, + ) + checkpoint_config.checkpoint_score_attribute = checkpoint_score_attr[4:] + checkpoint_config.checkpoint_score_order = "min" + else: + checkpoint_config.checkpoint_score_attribute = checkpoint_score_attr + checkpoint_config.checkpoint_score_order = "max" + + checkpoint_config.score_attr = checkpoint_score_attr + if checkpoint_freq > 0: + warnings.warn( + "checkpoint_freq is deprecated and will be removed. " + "use checkpoint_config.checkpoint_frequency instead.", + DeprecationWarning, + ) + checkpoint_config.checkpoint_frequency = checkpoint_freq + if checkpoint_at_end: + warnings.warn( + "checkpoint_at_end is deprecated and will be removed. " + "use checkpoint_config.checkpoint_at_end instead.", + DeprecationWarning, + ) + checkpoint_config.checkpoint_at_end = checkpoint_at_end + + # TODO(justinvyu): [Deprecated] Remove in 2.11. + if chdir_to_trial_dir != _DEPRECATED_VALUE: + raise DeprecationWarning( + "`chdir_to_trial_dir` is deprecated. " + f"Use the {RAY_CHDIR_TO_TRIAL_DIR} environment variable instead. " + "Set it to 0 to disable the default behavior of changing the " + "working directory.", + DeprecationWarning, + ) + + if num_samples == -1: + num_samples = sys.maxsize + + # Create scheduler here as we need access to some of its properties + if isinstance(scheduler, str): + # importing at top level causes a recursive dependency + from ray.tune.schedulers import create_scheduler + + scheduler = create_scheduler(scheduler) + scheduler = scheduler or FIFOScheduler() + + if not scheduler.supports_buffered_results: + # Result buffering with e.g. a Hyperband scheduler is a bad idea, as + # hyperband tries to stop trials when processing brackets. With result + # buffering, we might trigger this multiple times when evaluating + # a single trial, which leads to unexpected behavior. + env_result_buffer_length = os.getenv("TUNE_RESULT_BUFFER_LENGTH", "") + if env_result_buffer_length: + warnings.warn( + f"You are using a {type(scheduler)} scheduler, but " + f"TUNE_RESULT_BUFFER_LENGTH is set " + f"({env_result_buffer_length}). This can lead to undesired " + f"and faulty behavior, so the buffer length was forcibly set " + f"to 1 instead." + ) + os.environ["TUNE_RESULT_BUFFER_LENGTH"] = "1" + + if ( + isinstance(scheduler, (PopulationBasedTraining, PopulationBasedTrainingReplay)) + and not reuse_actors + ): + warnings.warn( + "Consider boosting PBT performance by enabling `reuse_actors` as " + "well as implementing `reset_config` for Trainable." + ) + + # Before experiments are created, we first clean up the passed in + # Config dictionary by replacing all the non-primitive config values + # with placeholders. This serves two purposes: + # 1. we can replace and "fix" these objects if a Trial is restored. + # 2. the config dictionary will then be compatible with all supported + # search algorithms, since a lot of them do not support non-primitive + # config values. + placeholder_resolvers = create_resolvers_map() + config = inject_placeholders( + # Make a deep copy here to avoid modifying the original config dict. + copy.deepcopy(config), + placeholder_resolvers, + ) + + # TODO(justinvyu): We should remove the ability to pass a list of + # trainables to tune.run. + if isinstance(run_or_experiment, list): + experiments = run_or_experiment + else: + experiments = [run_or_experiment] + + for i, exp in enumerate(experiments): + if not isinstance(exp, Experiment): + experiments[i] = Experiment( + name=name, + run=exp, + stop=stop, + time_budget_s=time_budget_s, + config=config, + resources_per_trial=resources_per_trial, + num_samples=num_samples, + storage_path=storage_path, + storage_filesystem=storage_filesystem, + sync_config=sync_config, + checkpoint_config=checkpoint_config, + trial_name_creator=trial_name_creator, + trial_dirname_creator=trial_dirname_creator, + log_to_file=log_to_file, + export_formats=export_formats, + max_failures=max_failures, + restore=restore, + ) + + if fail_fast and max_failures != 0: + raise ValueError("max_failures must be 0 if fail_fast=True.") + + if isinstance(search_alg, str): + search_alg = create_searcher(search_alg) + + # if local_mode=True is set during ray.init(). + is_local_mode = ray._private.worker._mode() == ray._private.worker.LOCAL_MODE + + if is_local_mode: + max_concurrent_trials = 1 + + if not search_alg: + search_alg = BasicVariantGenerator(max_concurrent=max_concurrent_trials or 0) + elif max_concurrent_trials or is_local_mode: + if isinstance(search_alg, ConcurrencyLimiter): + if not is_local_mode: + if search_alg.max_concurrent != max_concurrent_trials: + raise ValueError( + "You have specified `max_concurrent_trials=" + f"{max_concurrent_trials}`, but the `search_alg` is " + "already a `ConcurrencyLimiter` with `max_concurrent=" + f"{search_alg.max_concurrent}. FIX THIS by setting " + "`max_concurrent_trials=None`." + ) + else: + logger.warning( + "You have specified `max_concurrent_trials=" + f"{max_concurrent_trials}`, but the `search_alg` is " + "already a `ConcurrencyLimiter`. " + "`max_concurrent_trials` will be ignored." + ) + else: + if max_concurrent_trials < 1: + raise ValueError( + "`max_concurrent_trials` must be greater or equal than 1, " + f"got {max_concurrent_trials}." + ) + if isinstance(search_alg, Searcher): + search_alg = ConcurrencyLimiter( + search_alg, max_concurrent=max_concurrent_trials + ) + elif not is_local_mode: + logger.warning( + "You have passed a `SearchGenerator` instance as the " + "`search_alg`, but `max_concurrent_trials` requires a " + "`Searcher` instance`. `max_concurrent_trials` " + "will be ignored." + ) + + if isinstance(search_alg, Searcher): + search_alg = SearchGenerator(search_alg) + + if config and not searcher_set_search_props( + search_alg.set_search_properties, + metric, + mode, + config, + **experiments[0].public_spec, + ): + if _has_unresolved_values(config): + raise ValueError( + f"You passed a `{error_message_map['search_space_arg']}` parameter to " + f"`{error_message_map['entrypoint']}` with " + "unresolved parameters, but the search algorithm was already " + "instantiated with a search space. Make sure that `config` " + "does not contain any more parameter definitions - include " + "them in the search algorithm's search space if necessary." + ) + + if not scheduler_set_search_props( + scheduler.set_search_properties, metric, mode, **experiments[0].public_spec + ): + raise ValueError( + "You passed a `metric` or `mode` argument to " + f"`{error_message_map['entrypoint']}`, but " + "the scheduler you are using was already instantiated with their " + "own `metric` and `mode` parameters. Either remove the arguments " + f"from your scheduler or from `{error_message_map['entrypoint']}` args." + ) + + progress_metrics = _detect_progress_metrics(_get_trainable(run_or_experiment)) + + air_usage.tag_storage_type(experiments[0].storage) + + # NOTE: Report callback telemetry before populating the list with default callbacks. + # This tracks user-specified callback usage. + air_usage.tag_callbacks(callbacks) + + # Create default logging + syncer callbacks + callbacks = _create_default_callbacks( + callbacks, + air_verbosity=air_verbosity, + entrypoint=_entrypoint, + config=config, + metric=metric, + mode=mode, + progress_metrics=progress_metrics, + ) + + # User Warning for GPUs + if ray.cluster_resources().get("GPU", 0): + if _check_gpus_in_resources(resources=resources_per_trial): + # "gpu" is manually set. + pass + elif _check_default_resources_override(experiments[0].run_identifier): + # "default_resources" is manually overridden. + pass + else: + logger.warning( + "Tune detects GPUs, but no trials are using GPUs. " + "To enable trials to use GPUs, wrap `train_func` with " + "`tune.with_resources(train_func, resources_per_trial={'gpu': 1})` " + "which allows Tune to expose 1 GPU to each trial. " + "For Ray Train Trainers, you can specify GPU resources " + "through `ScalingConfig(use_gpu=True)`. " + "You can also override " + "`Trainable.default_resource_request` if using the " + "Trainable API." + ) + + experiment_interrupted_event = _setup_signal_catching() + + if progress_reporter and air_verbosity is not None: + logger.warning( + "AIR_VERBOSITY is set, ignoring passed-in ProgressReporter for now." + ) + progress_reporter = None + + if air_verbosity is None: + is_trainer = _entrypoint == AirEntrypoint.TRAINER + progress_reporter = progress_reporter or _detect_reporter( + _trainer_api=is_trainer + ) + + if resume is not None: + resume_config = resume_config or _build_resume_config_from_legacy_config(resume) + + runner_kwargs = dict( + search_alg=search_alg, + placeholder_resolvers=placeholder_resolvers, + scheduler=scheduler, + stopper=experiments[0].stopper, + resume_config=resume_config, + fail_fast=fail_fast, + callbacks=callbacks, + metric=metric, + trial_checkpoint_config=experiments[0].checkpoint_config, + reuse_actors=reuse_actors, + storage=experiments[0].storage, + _trainer_api=_entrypoint == AirEntrypoint.TRAINER, + ) + + runner = TuneController(**runner_kwargs) + + if not runner.resumed: + for exp in experiments: + search_alg.add_configurations([exp]) + # search_alg.total_samples has been updated, so we should + # update the number of pending trials + runner.update_max_pending_trials() + else: + logger.debug( + "You have resumed the Tune run, which means that any newly specified " + "`Experiment`s will be ignored. " + "Tune will just continue what was previously running." + ) + if resources_per_trial: + runner.update_pending_trial_resources(resources_per_trial) + + # Calls setup on callbacks + runner.setup_experiments( + experiments=experiments, total_num_samples=search_alg.total_samples + ) + + tune_start = time.time() + + air_progress_reporter = None + if air_verbosity is None: + progress_reporter.setup( + start_time=tune_start, + total_samples=search_alg.total_samples, + metric=metric, + mode=mode, + ) + else: + from ray.tune.experimental.output import ProgressReporter as AirProgressReporter + + for callback in callbacks: + if isinstance(callback, AirProgressReporter): + air_progress_reporter = callback + air_progress_reporter.setup( + start_time=tune_start, total_samples=search_alg.total_samples + ) + break + + experiment_local_path = runner._storage.experiment_driver_staging_path + experiment_dir_name = runner._storage.experiment_dir_name + + if any(isinstance(cb, TBXLoggerCallback) for cb in callbacks): + tensorboard_path = experiment_local_path + else: + tensorboard_path = None + + if air_progress_reporter: + air_progress_reporter.experiment_started( + experiment_name=experiment_dir_name, + experiment_path=runner.experiment_path, + searcher_str=search_alg.__class__.__name__, + scheduler_str=scheduler.__class__.__name__, + total_num_samples=search_alg.total_samples, + tensorboard_path=tensorboard_path, + ) + + try: + while not runner.is_finished() and not experiment_interrupted_event.is_set(): + runner.step() + if has_verbosity(Verbosity.V1_EXPERIMENT): + _report_progress(runner, progress_reporter) + + if air_verbosity is not None: + _report_air_progress(runner, air_progress_reporter) + except Exception: + runner.cleanup() + raise + + tune_taken = time.time() - tune_start + + final_sync_start = time.time() + try: + runner.checkpoint(force=True, wait=True) + logger.info( + "Wrote the latest version of all result files and experiment state to " + f"'{runner.experiment_path}' in {time.time() - final_sync_start:.4f}s." + ) + except Exception: + logger.error( + "Experiment state snapshotting failed:", exc_info=True, stack_info=True + ) + + if has_verbosity(Verbosity.V1_EXPERIMENT): + _report_progress(runner, progress_reporter, done=True) + + if air_verbosity is not None: + _report_air_progress(runner, air_progress_reporter, force=True) + + all_trials = runner.get_trials() + + runner.cleanup() + + incomplete_trials = [] + for trial in all_trials: + if trial.status != Trial.TERMINATED: + incomplete_trials += [trial] + + if incomplete_trials: + if raise_on_failed_trial and not experiment_interrupted_event.is_set(): + raise TuneError("Trials did not complete", incomplete_trials) + else: + logger.error("Trials did not complete: %s", incomplete_trials) + + all_taken = time.time() - all_start + if has_verbosity(Verbosity.V1_EXPERIMENT): + logger.info( + f"Total run time: {all_taken:.2f} seconds " + f"({tune_taken:.2f} seconds for the tuning loop)." + ) + + if experiment_interrupted_event.is_set(): + restore_entrypoint = error_message_map["restore_entrypoint"].format( + path=runner.experiment_path, + ) + if _entrypoint == AirEntrypoint.TRAINER: + logger.warning( + f"Training has been interrupted, but the most recent state was saved.\n" + f"Resume training with: {restore_entrypoint}" + ) + else: + logger.warning( + f"Experiment has been interrupted, but the most recent state was " + f"saved.\nResume experiment with: {restore_entrypoint}" + ) + + return ExperimentAnalysis( + experiment_checkpoint_path=runner.experiment_path, + default_metric=metric, + default_mode=mode, + trials=all_trials, + storage_filesystem=experiments[0].storage.storage_filesystem, + ) + + +@PublicAPI +def run_experiments( + experiments: Union[Experiment, Mapping, Sequence[Union[Experiment, Mapping]]], + scheduler: Optional[TrialScheduler] = None, + verbose: Optional[Union[int, AirVerbosity, Verbosity]] = None, + progress_reporter: Optional[ProgressReporter] = None, + resume: Optional[Union[bool, str]] = None, + resume_config: Optional[ResumeConfig] = None, + reuse_actors: bool = False, + raise_on_failed_trial: bool = True, + concurrent: bool = True, + callbacks: Optional[Sequence[Callback]] = None, + _remote: Optional[bool] = None, +): + """Runs and blocks until all trials finish. + + Example: + >>> from ray.tune.experiment import Experiment + >>> from ray.tune.tune import run_experiments + >>> def my_func(config): return {"score": 0} + >>> experiment_spec = Experiment("experiment", my_func) # doctest: +SKIP + >>> run_experiments(experiments=experiment_spec) # doctest: +SKIP + >>> experiment_spec = {"experiment": {"run": my_func}} # doctest: +SKIP + >>> run_experiments(experiments=experiment_spec) # doctest: +SKIP + + Returns: + List of Trial objects, holding data for each executed trial. + + """ + if _remote is None: + _remote = ray.util.client.ray.is_connected() + + _ray_auto_init(entrypoint="tune.run_experiments(...)") + + if verbose is None: + # Default `verbose` value. For new output engine, this is AirVerbosity.VERBOSE. + # For old output engine, this is Verbosity.V3_TRIAL_DETAILS + verbose = get_air_verbosity(AirVerbosity.VERBOSE) or Verbosity.V3_TRIAL_DETAILS + + if _remote: + if get_air_verbosity(verbose) is not None: + logger.info( + "[output] This uses the legacy output and progress reporter, " + "as Ray client is not supported by the new engine. " + "For more information, see " + "https://github.com/ray-project/ray/issues/36949" + ) + remote_run = ray.remote(num_cpus=0)(run_experiments) + + # Make sure tune.run_experiments is run on the server node. + remote_run = _force_on_current_node(remote_run) + + return ray.get( + remote_run.remote( + experiments, + scheduler, + verbose, + progress_reporter, + resume, + resume_config, + reuse_actors, + raise_on_failed_trial, + concurrent, + callbacks, + _remote=False, + ) + ) + + # This is important to do this here + # because it schematize the experiments + # and it conducts the implicit registration. + experiments = _convert_to_experiment_list(experiments) + + tune_run_params = dict( + verbose=verbose, + progress_reporter=progress_reporter, + resume=resume, + resume_config=resume_config, + reuse_actors=reuse_actors, + raise_on_failed_trial=raise_on_failed_trial, + scheduler=scheduler, + callbacks=callbacks, + _entrypoint=AirEntrypoint.TUNE_RUN_EXPERIMENTS, + ) + + if concurrent: + return run(experiments, **tune_run_params).trials + else: + trials = [] + for exp in experiments: + trials += run(exp, **tune_run_params).trials + return trials diff --git a/venv/lib/python3.10/site-packages/ray/tune/tune_config.py b/venv/lib/python3.10/site-packages/ray/tune/tune_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ebaba70cdef8ee9495406bed1d6db30b74a1ac26 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/tune_config.py @@ -0,0 +1,99 @@ +import datetime +from dataclasses import dataclass +from enum import Enum +from typing import Callable, Optional, Union + +from ray.train.constants import _DEPRECATED_VALUE +from ray.tune.experiment.trial import Trial +from ray.tune.schedulers import TrialScheduler +from ray.tune.search import SearchAlgorithm, Searcher +from ray.util.annotations import DeveloperAPI, PublicAPI + + +@dataclass +@PublicAPI(stability="beta") +class TuneConfig: + """Tune specific configs. + + Args: + metric: Metric to optimize. This metric should be reported + with `tune.report()`. If set, will be passed to the search + algorithm and scheduler. + mode: Must be one of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. If set, will be + passed to the search algorithm and scheduler. + search_alg: Search algorithm for optimization. Default to + random search. + scheduler: Scheduler for executing the experiment. + Choose among FIFO (default), MedianStopping, + AsyncHyperBand, HyperBand and PopulationBasedTraining. Refer to + ray.tune.schedulers for more options. + num_samples: Number of times to sample from the + hyperparameter space. Defaults to 1. If `grid_search` is + provided as an argument, the grid will be repeated + `num_samples` of times. If this is -1, (virtually) infinite + samples are generated until a stopping condition is met. + max_concurrent_trials: Maximum number of trials to run + concurrently. Must be non-negative. If None or 0, no limit will + be applied. This is achieved by wrapping the ``search_alg`` in + a :class:`ConcurrencyLimiter`, and thus setting this argument + will raise an exception if the ``search_alg`` is already a + :class:`ConcurrencyLimiter`. Defaults to None. + time_budget_s: Global time budget in + seconds after which all trials are stopped. Can also be a + ``datetime.timedelta`` object. + reuse_actors: Whether to reuse actors between different trials + when possible. This can drastically speed up experiments that start + and stop actors often (e.g., PBT in time-multiplexing mode). This + requires trials to have the same resource requirements. + Defaults to ``False``. + trial_name_creator: Optional function that takes in a Trial and returns + its name (i.e. its string representation). Be sure to include some unique + identifier (such as `Trial.trial_id`) in each trial's name. + NOTE: This API is in alpha and subject to change. + trial_dirname_creator: Optional function that takes in a trial and + generates its trial directory name as a string. Be sure to include some + unique identifier (such as `Trial.trial_id`) is used in each trial's + directory name. Otherwise, trials could overwrite artifacts and checkpoints + of other trials. The return value cannot be a path. + NOTE: This API is in alpha and subject to change. + chdir_to_trial_dir: Deprecated. Set the `RAY_CHDIR_TO_TRIAL_DIR` env var instead + """ + + # Currently this is not at feature parity with `tune.run`, nor should it be. + # The goal is to reach a fine balance between API flexibility and conciseness. + # We should carefully introduce arguments here instead of just dumping everything. + mode: Optional[str] = None + metric: Optional[str] = None + search_alg: Optional[Union[Searcher, SearchAlgorithm]] = None + scheduler: Optional[TrialScheduler] = None + num_samples: int = 1 + max_concurrent_trials: Optional[int] = None + time_budget_s: Optional[Union[int, float, datetime.timedelta]] = None + reuse_actors: bool = False + trial_name_creator: Optional[Callable[[Trial], str]] = None + trial_dirname_creator: Optional[Callable[[Trial], str]] = None + chdir_to_trial_dir: bool = _DEPRECATED_VALUE + + +@DeveloperAPI +@dataclass +class ResumeConfig: + """[Experimental] This config is used to specify how to resume Tune trials.""" + + class ResumeType(Enum): + """An enumeration to define resume types for various trial states. + + Members: + RESUME: Resume from the latest checkpoint. + RESTART: Restart from the beginning (with no checkpoint). + SKIP: Skip this trial when resuming by treating it as terminated. + """ + + RESUME = "resume" + RESTART = "restart" + SKIP = "skip" + + finished: str = ResumeType.SKIP + unfinished: str = ResumeType.RESUME + errored: str = ResumeType.SKIP diff --git a/venv/lib/python3.10/site-packages/ray/tune/tuner.py b/venv/lib/python3.10/site-packages/ray/tune/tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..b4012f93d56056e5f82c552ee39317ba77e65db1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/ray/tune/tuner.py @@ -0,0 +1,402 @@ +import logging +import os +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Type, Union + +import pyarrow.fs + +import ray +from ray.air._internal.usage import AirEntrypoint +from ray.air.util.node import _force_on_current_node +from ray.train._internal.storage import _exists_at_fs_path, get_fs_and_path +from ray.tune import ResumeConfig, RunConfig +from ray.tune.experimental.output import get_air_verbosity +from ray.tune.impl.tuner_internal import _TUNER_PKL, TunerInternal +from ray.tune.progress_reporter import ( + _prepare_progress_reporter_for_ray_client, + _stream_client_output, +) +from ray.tune.result_grid import ResultGrid +from ray.tune.trainable import Trainable +from ray.tune.tune_config import TuneConfig +from ray.util import PublicAPI + +logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from ray.train.base_trainer import BaseTrainer + +ClientActorHandle = Any + +# try: +# # Breaks lint right now. +# from ray.util.client.common import ClientActorHandle +# except Exception: +# pass + +# The magic key that is used when instantiating Tuner during resume. +_TUNER_INTERNAL = "_tuner_internal" +_SELF = "self" + + +@PublicAPI(stability="beta") +class Tuner: + """Tuner is the recommended way of launching hyperparameter tuning jobs with Ray Tune. + + Args: + trainable: The trainable to be tuned. + param_space: Search space of the tuning job. See :ref:`tune-search-space-tutorial`. + tune_config: Tuning specific configs, such as setting custom + :ref:`search algorithms ` and + :ref:`trial scheduling algorithms `. + run_config: Job-level run configuration, which includes configs for + persistent storage, checkpointing, fault tolerance, etc. + + Usage pattern: + + .. code-block:: python + + import ray.tune + + def trainable(config): + # Your training logic here + ray.tune.report({"accuracy": 0.8}) + + tuner = Tuner( + trainable=trainable, + param_space={"lr": ray.tune.grid_search([0.001, 0.01])}, + run_config=ray.tune.RunConfig(name="my_tune_run"), + ) + results = tuner.fit() + + To retry a failed Tune run, you can then do + + .. code-block:: python + + tuner = Tuner.restore(results.experiment_path, trainable=trainable) + tuner.fit() + + ``results.experiment_path`` can be retrieved from the + :ref:`ResultGrid object `. It can + also be easily seen in the log output from your first run. + + """ + + # One of the following is assigned. + _local_tuner: Optional[TunerInternal] # Only used in none ray client mode. + _remote_tuner: Optional[ClientActorHandle] # Only used in ray client mode. + + def __init__( + self, + trainable: Optional[ + Union[str, Callable, Type[Trainable], "BaseTrainer"] + ] = None, + *, + param_space: Optional[Dict[str, Any]] = None, + tune_config: Optional[TuneConfig] = None, + run_config: Optional[RunConfig] = None, + # This is internal only arg. + # Only for dogfooding purposes. We can slowly promote these args + # to RunConfig or TuneConfig as needed. + # TODO(xwjiang): Remove this later. + _tuner_kwargs: Optional[Dict] = None, + _tuner_internal: Optional[TunerInternal] = None, + _entrypoint: AirEntrypoint = AirEntrypoint.TUNER, + ): + """Configure and construct a tune run.""" + kwargs = locals().copy() + self._is_ray_client = ray.util.client.ray.is_connected() + if self._is_ray_client: + _run_config = run_config or RunConfig() + if get_air_verbosity(_run_config.verbose) is not None: + logger.info( + "[output] This uses the legacy output and progress reporter, " + "as Ray client is not supported by the new engine. " + "For more information, see " + "https://github.com/ray-project/ray/issues/36949" + ) + + if _tuner_internal: + if not self._is_ray_client: + self._local_tuner = kwargs[_TUNER_INTERNAL] + else: + self._remote_tuner = kwargs[_TUNER_INTERNAL] + else: + kwargs.pop(_TUNER_INTERNAL, None) + kwargs.pop(_SELF, None) + if not self._is_ray_client: + self._local_tuner = TunerInternal(**kwargs) + else: + self._remote_tuner = _force_on_current_node( + ray.remote(num_cpus=0)(TunerInternal) + ).remote(**kwargs) + + @classmethod + def restore( + cls, + path: str, + trainable: Union[str, Callable, Type[Trainable], "BaseTrainer"], + resume_unfinished: bool = True, + resume_errored: bool = False, + restart_errored: bool = False, + param_space: Optional[Dict[str, Any]] = None, + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + _resume_config: Optional[ResumeConfig] = None, + ) -> "Tuner": + """Restores Tuner after a previously failed run. + + All trials from the existing run will be added to the result table. The + argument flags control how existing but unfinished or errored trials are + resumed. + + Finished trials are always added to the overview table. They will not be + resumed. + + Unfinished trials can be controlled with the ``resume_unfinished`` flag. + If ``True`` (default), they will be continued. If ``False``, they will + be added as terminated trials (even if they were only created and never + trained). + + Errored trials can be controlled with the ``resume_errored`` and + ``restart_errored`` flags. The former will resume errored trials from + their latest checkpoints. The latter will restart errored trials from + scratch and prevent loading their last checkpoints. + + .. note:: + + Restoring an experiment from a path that's pointing to a *different* + location than the original experiment path is supported. + However, Ray Tune assumes that the full experiment directory is available + (including checkpoints) so that it's possible to resume trials from their + latest state. + + For example, if the original experiment path was run locally, + then the results are uploaded to cloud storage, Ray Tune expects the full + contents to be available in cloud storage if attempting to resume + via ``Tuner.restore("s3://...")``. The restored run will continue + writing results to the same cloud storage location. + + Args: + path: The local or remote path of the experiment directory + for an interrupted or failed run. + Note that an experiment where all trials finished will not be resumed. + This information could be easily located near the end of the + console output of previous run. + trainable: The trainable to use upon resuming the experiment. + This should be the same trainable that was used to initialize + the original Tuner. + param_space: The same `param_space` that was passed to + the original Tuner. This can be optionally re-specified due + to the `param_space` potentially containing Ray object + references (tuning over Datasets or tuning over + several `ray.put` object references). **Tune expects the + `param_space` to be unmodified**, and the only part that + will be used during restore are the updated object references. + Changing the hyperparameter search space then resuming is NOT + supported by this API. + resume_unfinished: If True, will continue to run unfinished trials. + resume_errored: If True, will re-schedule errored trials and try to + restore from their latest checkpoints. + restart_errored: If True, will re-schedule errored trials but force + restarting them from scratch (no checkpoint will be loaded). + storage_filesystem: Custom ``pyarrow.fs.FileSystem`` + corresponding to the ``path``. This may be necessary if the original + experiment passed in a custom filesystem. + _resume_config: [Experimental] Config object that controls how to resume + trials of different statuses. Can be used as a substitute to + `resume_*` and `restart_*` flags above. + """ + unfinished = ( + ResumeConfig.ResumeType.RESUME + if resume_unfinished + else ResumeConfig.ResumeType.SKIP + ) + errored = ResumeConfig.ResumeType.SKIP + if resume_errored: + errored = ResumeConfig.ResumeType.RESUME + elif restart_errored: + errored = ResumeConfig.ResumeType.RESTART + + resume_config = _resume_config or ResumeConfig( + unfinished=unfinished, errored=errored + ) + + if not ray.util.client.ray.is_connected(): + tuner_internal = TunerInternal( + restore_path=path, + resume_config=resume_config, + trainable=trainable, + param_space=param_space, + storage_filesystem=storage_filesystem, + ) + return Tuner(_tuner_internal=tuner_internal) + else: + tuner_internal = _force_on_current_node( + ray.remote(num_cpus=0)(TunerInternal) + ).remote( + restore_path=path, + resume_config=resume_config, + trainable=trainable, + param_space=param_space, + storage_filesystem=storage_filesystem, + ) + return Tuner(_tuner_internal=tuner_internal) + + @classmethod + def can_restore( + cls, + path: Union[str, os.PathLike], + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + ) -> bool: + """Checks whether a given directory contains a restorable Tune experiment. + + Usage Pattern: + + Use this utility to switch between starting a new Tune experiment + and restoring when possible. This is useful for experiment fault-tolerance + when re-running a failed tuning script. + + .. code-block:: python + + import os + + from ray.tune import Tuner, RunConfig + + def train_fn(config): + # Make sure to implement checkpointing so that progress gets + # saved on restore. + pass + + name = "exp_name" + storage_path = os.path.expanduser("~/ray_results") + exp_dir = os.path.join(storage_path, name) + + if Tuner.can_restore(exp_dir): + tuner = Tuner.restore( + exp_dir, + trainable=train_fn, + resume_errored=True, + ) + else: + tuner = Tuner( + train_fn, + run_config=RunConfig(name=name, storage_path=storage_path), + ) + tuner.fit() + + Args: + path: The path to the experiment directory of the Tune experiment. + This can be either a local directory or a remote URI + (e.g. s3://bucket/exp_name). + + Returns: + bool: True if this path exists and contains the Tuner state to resume from + """ + fs, fs_path = get_fs_and_path(path, storage_filesystem) + return _exists_at_fs_path(fs, Path(fs_path, _TUNER_PKL).as_posix()) + + def _prepare_remote_tuner_for_jupyter_progress_reporting(self): + run_config: RunConfig = ray.get(self._remote_tuner.get_run_config.remote()) + progress_reporter, string_queue = _prepare_progress_reporter_for_ray_client( + run_config.progress_reporter, run_config.verbose + ) + run_config.progress_reporter = progress_reporter + ray.get( + self._remote_tuner.set_run_config_and_remote_string_queue.remote( + run_config, string_queue + ) + ) + + return progress_reporter, string_queue + + def fit(self) -> ResultGrid: + """Executes hyperparameter tuning job as configured and returns result. + + Failure handling: + For the kind of exception that happens during the execution of a trial, + one may inspect it together with stacktrace through the returned result grid. + See ``ResultGrid`` for reference. Each trial may fail up to a certain number. + This is configured by ``RunConfig.FailureConfig.max_failures``. + + Exception that happens beyond trials will be thrown by this method as well. + In such cases, there will be instruction like the following printed out + at the end of console output to inform users on how to resume. + + Please use `Tuner.restore` to resume. + + .. code-block:: python + + import os + from ray.tune import Tuner + + trainable = ... + + tuner = Tuner.restore( + os.path.expanduser("~/ray_results/tuner_resume"), + trainable=trainable + ) + tuner.fit() + + Raises: + RayTaskError: If user-provided trainable raises an exception + """ + + if not self._is_ray_client: + return self._local_tuner.fit() + else: + ( + progress_reporter, + string_queue, + ) = self._prepare_remote_tuner_for_jupyter_progress_reporting() + fit_future = self._remote_tuner.fit.remote() + _stream_client_output( + fit_future, + progress_reporter, + string_queue, + ) + return ray.get(fit_future) + + def get_results(self) -> ResultGrid: + """Get results of a hyperparameter tuning run. + + This method returns the same results as :meth:`~ray.tune.Tuner.fit` + and can be used to retrieve the results after restoring a tuner without + calling ``fit()`` again. + + If the tuner has not been fit before, an error will be raised. + + .. code-block:: python + + from ray.tune import Tuner + + # `trainable` is what was passed in to the original `Tuner` + tuner = Tuner.restore("/path/to/experiment', trainable=trainable) + results = tuner.get_results() + + Returns: + Result grid of a previously fitted tuning run. + + """ + if not self._is_ray_client: + return self._local_tuner.get_results() + else: + ( + progress_reporter, + string_queue, + ) = self._prepare_remote_tuner_for_jupyter_progress_reporting() + get_results_future = self._remote_tuner.get_results.remote() + _stream_client_output( + get_results_future, + progress_reporter, + string_queue, + ) + return ray.get(get_results_future) + + def __getattribute__(self, item): + if item == "restore": + raise AttributeError( + "`Tuner.restore()` is a classmethod and cannot be called on an " + "instance. Use `tuner = Tuner.restore(...)` to instantiate the " + "Tuner instead." + ) + return super().__getattribute__(item)