diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/__init__.py b/vllm/lib/python3.10/site-packages/ray/dashboard/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/agent.py b/vllm/lib/python3.10/site-packages/ray/dashboard/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..11b2d5397473ba0abf4ffe0ff1aa8f7ea6fc1684 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/agent.py @@ -0,0 +1,456 @@ +import argparse +import asyncio +import json +import logging +import logging.handlers +import os +import pathlib +import signal +import sys + +import ray +import ray._private.ray_constants as ray_constants +import ray._private.services +import ray._private.utils +import ray.dashboard.consts as dashboard_consts +import ray.dashboard.utils as dashboard_utils +from ray._private.gcs_utils import GcsAioClient +from ray._private.process_watcher import create_check_raylet_task +from ray._private.ray_constants import AGENT_GRPC_MAX_MESSAGE_LENGTH +from ray._private.ray_logging import configure_log_file, setup_component_logger + +logger = logging.getLogger(__name__) + + +class DashboardAgent: + def __init__( + self, + node_ip_address, + dashboard_agent_port, + gcs_address, + cluster_id_hex, + minimal, + metrics_export_port=None, + node_manager_port=None, + listen_port=ray_constants.DEFAULT_DASHBOARD_AGENT_LISTEN_PORT, + disable_metrics_collection: bool = False, + *, # the following are required kwargs + object_store_name: str, + raylet_name: str, + log_dir: str, + temp_dir: str, + session_dir: str, + logging_params: dict, + agent_id: int, + session_name: str, + ): + """Initialize the DashboardAgent object.""" + # Public attributes are accessible for all agent modules. + self.ip = node_ip_address + self.minimal = minimal + + assert gcs_address is not None + self.gcs_address = gcs_address + self.cluster_id_hex = cluster_id_hex + + self.temp_dir = temp_dir + self.session_dir = session_dir + self.log_dir = log_dir + self.dashboard_agent_port = dashboard_agent_port + self.metrics_export_port = metrics_export_port + self.node_manager_port = node_manager_port + self.listen_port = listen_port + self.object_store_name = object_store_name + self.raylet_name = raylet_name + self.logging_params = logging_params + self.node_id = os.environ["RAY_NODE_ID"] + self.metrics_collection_disabled = disable_metrics_collection + self.agent_id = agent_id + self.session_name = session_name + + # grpc server is None in mininal. + self.server = None + # http_server is None in minimal. + self.http_server = None + + # Used by the agent and sub-modules. + self.gcs_aio_client = GcsAioClient( + address=self.gcs_address, + nums_reconnect_retry=ray._config.gcs_rpc_server_reconnect_timeout_s(), + cluster_id=self.cluster_id_hex, + ) + + if not self.minimal: + self._init_non_minimal() + + def _init_non_minimal(self): + from ray._private.gcs_pubsub import GcsAioPublisher + from ray.dashboard.http_server_agent import HttpServerAgent + + self.aio_publisher = GcsAioPublisher(address=self.gcs_address) + + try: + from grpc import aio as aiogrpc + except ImportError: + from grpc.experimental import aio as aiogrpc + + # We would want to suppress deprecating warnings from aiogrpc library + # with the usage of asyncio.get_event_loop() in python version >=3.10 + # This could be removed once https://github.com/grpc/grpc/issues/32526 + # is released, and we used higher versions of grpcio that that. + if sys.version_info.major >= 3 and sys.version_info.minor >= 10: + import warnings + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + aiogrpc.init_grpc_aio() + else: + aiogrpc.init_grpc_aio() + + self.server = aiogrpc.server( + options=( + ("grpc.so_reuseport", 0), + ( + "grpc.max_send_message_length", + AGENT_GRPC_MAX_MESSAGE_LENGTH, + ), # noqa + ( + "grpc.max_receive_message_length", + AGENT_GRPC_MAX_MESSAGE_LENGTH, + ), + ) # noqa + ) + grpc_ip = "127.0.0.1" if self.ip == "127.0.0.1" else "0.0.0.0" + try: + self.grpc_port = ray._private.tls_utils.add_port_to_grpc_server( + self.server, f"{grpc_ip}:{self.dashboard_agent_port}" + ) + except Exception: + # TODO(SongGuyang): Catch the exception here because there is + # port conflict issue which brought from static port. We should + # remove this after we find better port resolution. + logger.exception( + "Failed to add port to grpc server. Agent will stay alive but " + "disable the grpc service." + ) + self.server = None + self.grpc_port = None + else: + logger.info("Dashboard agent grpc address: %s:%s", grpc_ip, self.grpc_port) + + # If the agent is not minimal it should start the http server + # to communicate with the dashboard in a head node. + # Http server is not started in the minimal version because + # it requires additional dependencies that are not + # included in the minimal ray package. + self.http_server = HttpServerAgent(self.ip, self.listen_port) + + def _load_modules(self): + """Load dashboard agent modules.""" + modules = [] + agent_cls_list = dashboard_utils.get_all_modules( + dashboard_utils.DashboardAgentModule + ) + for cls in agent_cls_list: + logger.info( + "Loading %s: %s", dashboard_utils.DashboardAgentModule.__name__, cls + ) + c = cls(self) + modules.append(c) + logger.info("Loaded %d modules.", len(modules)) + return modules + + @property + def http_session(self): + assert ( + self.http_server + ), "Accessing unsupported API (HttpServerAgent) in a minimal ray." + return self.http_server.http_session + + @property + def publisher(self): + assert ( + self.aio_publisher + ), "Accessing unsupported API (GcsAioPublisher) in a minimal ray." + return self.aio_publisher + + def get_node_id(self) -> str: + return self.node_id + + async def run(self): + # Start a grpc asyncio server. + if self.server: + await self.server.start() + + modules = self._load_modules() + + if self.http_server: + try: + await self.http_server.start(modules) + except Exception: + # TODO(SongGuyang): Catch the exception here because there is + # port conflict issue which brought from static port. We should + # remove this after we find better port resolution. + logger.exception( + "Failed to start http server. Agent will stay alive but " + "disable the http service." + ) + + # Write the dashboard agent port to kv. + # TODO: Use async version if performance is an issue + # -1 should indicate that http server is not started. + http_port = -1 if not self.http_server else self.http_server.http_port + grpc_port = -1 if not self.server else self.grpc_port + await self.gcs_aio_client.internal_kv_put( + f"{dashboard_consts.DASHBOARD_AGENT_PORT_PREFIX}{self.node_id}".encode(), + json.dumps([http_port, grpc_port]).encode(), + True, + namespace=ray_constants.KV_NAMESPACE_DASHBOARD, + ) + + tasks = [m.run(self.server) for m in modules] + + if sys.platform not in ["win32", "cygwin"]: + + def callback(msg): + logger.info( + f"Terminated Raylet: ip={self.ip}, node_id={self.node_id}. {msg}" + ) + + check_parent_task = create_check_raylet_task( + self.log_dir, self.gcs_address, callback, loop + ) + tasks.append(check_parent_task) + + if self.server: + tasks.append(self.server.wait_for_termination()) + else: + + async def wait_forever(): + while True: + await asyncio.sleep(3600) + + tasks.append(wait_forever()) + + await asyncio.gather(*tasks) + + if self.http_server: + await self.http_server.cleanup() + + +def open_capture_files(log_dir): + filename = f"agent-{args.agent_id}" + return ( + ray._private.utils.open_log(pathlib.Path(log_dir) / f"{filename}.out"), + ray._private.utils.open_log(pathlib.Path(log_dir) / f"{filename}.err"), + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Dashboard agent.") + parser.add_argument( + "--node-ip-address", + required=True, + type=str, + help="the IP address of this node.", + ) + parser.add_argument( + "--gcs-address", required=True, type=str, help="The address (ip:port) of GCS." + ) + parser.add_argument( + "--cluster-id-hex", + required=True, + type=str, + help="The cluster id in hex.", + ) + parser.add_argument( + "--metrics-export-port", + required=True, + type=int, + help="The port to expose metrics through Prometheus.", + ) + parser.add_argument( + "--dashboard-agent-port", + required=True, + type=int, + help="The port on which the dashboard agent will receive GRPCs.", + ) + parser.add_argument( + "--node-manager-port", + required=True, + type=int, + help="The port to use for starting the node manager", + ) + parser.add_argument( + "--object-store-name", + required=True, + type=str, + default=None, + help="The socket name of the plasma store", + ) + parser.add_argument( + "--listen-port", + required=False, + type=int, + default=ray_constants.DEFAULT_DASHBOARD_AGENT_LISTEN_PORT, + help="Port for HTTP server to listen on", + ) + parser.add_argument( + "--raylet-name", + required=True, + type=str, + default=None, + help="The socket path of the raylet process", + ) + parser.add_argument( + "--logging-level", + required=False, + type=lambda s: logging.getLevelName(s.upper()), + default=ray_constants.LOGGER_LEVEL, + choices=ray_constants.LOGGER_LEVEL_CHOICES, + help=ray_constants.LOGGER_LEVEL_HELP, + ) + parser.add_argument( + "--logging-format", + required=False, + type=str, + default=ray_constants.LOGGER_FORMAT, + help=ray_constants.LOGGER_FORMAT_HELP, + ) + parser.add_argument( + "--logging-filename", + required=False, + type=str, + default=dashboard_consts.DASHBOARD_AGENT_LOG_FILENAME, + help="Specify the name of log file, " + 'log to stdout if set empty, default is "{}".'.format( + dashboard_consts.DASHBOARD_AGENT_LOG_FILENAME + ), + ) + parser.add_argument( + "--logging-rotate-bytes", + required=False, + type=int, + default=ray_constants.LOGGING_ROTATE_BYTES, + help="Specify the max bytes for rotating " + "log file, default is {} bytes.".format(ray_constants.LOGGING_ROTATE_BYTES), + ) + parser.add_argument( + "--logging-rotate-backup-count", + required=False, + type=int, + default=ray_constants.LOGGING_ROTATE_BACKUP_COUNT, + help="Specify the backup count of rotated log file, default is {}.".format( + ray_constants.LOGGING_ROTATE_BACKUP_COUNT + ), + ) + parser.add_argument( + "--log-dir", + required=True, + type=str, + default=None, + help="Specify the path of log directory.", + ) + parser.add_argument( + "--temp-dir", + required=True, + type=str, + default=None, + help="Specify the path of the temporary directory use by Ray process.", + ) + parser.add_argument( + "--session-dir", + required=True, + type=str, + default=None, + help="Specify the path of this session.", + ) + + parser.add_argument( + "--minimal", + action="store_true", + help=( + "Minimal agent only contains a subset of features that don't " + "require additional dependencies installed when ray is installed " + "by `pip install 'ray[default]'`." + ), + ) + parser.add_argument( + "--disable-metrics-collection", + action="store_true", + help=("If this arg is set, metrics report won't be enabled from the agent."), + ) + parser.add_argument( + "--agent-id", + required=True, + type=int, + help="ID to report when registering with raylet", + default=os.getpid(), + ) + parser.add_argument( + "--session-name", + required=False, + type=str, + default=None, + help="The session name (cluster id) of this cluster.", + ) + + args = parser.parse_args() + + try: + logging_params = dict( + logging_level=args.logging_level, + logging_format=args.logging_format, + log_dir=args.log_dir, + filename=args.logging_filename, + max_bytes=args.logging_rotate_bytes, + backup_count=args.logging_rotate_backup_count, + ) + logger = setup_component_logger(**logging_params) + + # Initialize event loop, see Dashboard init code for caveat + # w.r.t grpc server init in the DashboardAgent initializer. + loop = ray._private.utils.get_or_create_event_loop() + + # Setup stdout/stderr redirect files + out_file, err_file = open_capture_files(args.log_dir) + configure_log_file(out_file, err_file) + + agent = DashboardAgent( + args.node_ip_address, + args.dashboard_agent_port, + args.gcs_address, + args.cluster_id_hex, + args.minimal, + temp_dir=args.temp_dir, + session_dir=args.session_dir, + log_dir=args.log_dir, + metrics_export_port=args.metrics_export_port, + node_manager_port=args.node_manager_port, + listen_port=args.listen_port, + object_store_name=args.object_store_name, + raylet_name=args.raylet_name, + logging_params=logging_params, + disable_metrics_collection=args.disable_metrics_collection, + agent_id=args.agent_id, + session_name=args.session_name, + ) + + def sigterm_handler(): + logger.warning("Exiting with SIGTERM immediately...") + # Exit code 0 will be considered as an expected shutdown + os._exit(signal.SIGTERM) + + if sys.platform != "win32": + # TODO(rickyyx): we currently do not have any logic for actual + # graceful termination in the agent. Most of the underlying + # async tasks run by the agent head doesn't handle CancelledError. + # So a truly graceful shutdown is not trivial w/o much refactoring. + # Re-open the issue: https://github.com/ray-project/ray/issues/25518 + # if a truly graceful shutdown is required. + loop.add_signal_handler(signal.SIGTERM, sigterm_handler) + + loop.run_until_complete(agent.run()) + except Exception: + logger.exception("Agent is working abnormally. It will exit immediately.") + exit(1) diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/consts.py b/vllm/lib/python3.10/site-packages/ray/dashboard/consts.py new file mode 100644 index 0000000000000000000000000000000000000000..4c84be6daf5be058081640318418708e3b79fcc4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/consts.py @@ -0,0 +1,90 @@ +import os + +from ray._private.ray_constants import env_bool, env_integer + +DASHBOARD_LOG_FILENAME = "dashboard.log" +DASHBOARD_AGENT_PORT_PREFIX = "DASHBOARD_AGENT_PORT_PREFIX:" +DASHBOARD_AGENT_LOG_FILENAME = "dashboard_agent.log" +DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S_ENV_NAME = ( + "RAY_DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S" # noqa +) +DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S = env_integer( + DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S_ENV_NAME, 0.4 +) +# The maximum time that parent can be considered +# as dead before agent kills itself. +_PARENT_DEATH_THREASHOLD = 5 +RAY_STATE_SERVER_MAX_HTTP_REQUEST_ENV_NAME = "RAY_STATE_SERVER_MAX_HTTP_REQUEST" +# Default number of in-progress requests to the state api server. +RAY_STATE_SERVER_MAX_HTTP_REQUEST = env_integer( + RAY_STATE_SERVER_MAX_HTTP_REQUEST_ENV_NAME, 100 +) +# Max allowed number of in-progress requests could be configured. +RAY_STATE_SERVER_MAX_HTTP_REQUEST_ALLOWED = 1000 + +RAY_DASHBOARD_STATS_PURGING_INTERVAL = env_integer( + "RAY_DASHBOARD_STATS_PURGING_INTERVAL", 60 * 10 +) +RAY_DASHBOARD_STATS_UPDATING_INTERVAL = env_integer( + "RAY_DASHBOARD_STATS_UPDATING_INTERVAL", 15 +) +DASHBOARD_RPC_ADDRESS = "dashboard_rpc" +DASHBOARD_RPC_PORT = env_integer("RAY_DASHBOARD_RPC_PORT", 0) +GCS_SERVER_ADDRESS = "GcsServerAddress" +# GCS check alive +GCS_CHECK_ALIVE_INTERVAL_SECONDS = env_integer("GCS_CHECK_ALIVE_INTERVAL_SECONDS", 5) +GCS_RPC_TIMEOUT_SECONDS = env_integer("RAY_DASHBOARD_GCS_RPC_TIMEOUT_SECONDS", 60) +# aiohttp_cache +AIOHTTP_CACHE_TTL_SECONDS = 2 +AIOHTTP_CACHE_MAX_SIZE = 128 +AIOHTTP_CACHE_DISABLE_ENVIRONMENT_KEY = "RAY_DASHBOARD_NO_CACHE" +# Default value for datacenter (the default value in protobuf) +DEFAULT_LANGUAGE = "PYTHON" +DEFAULT_JOB_ID = "ffff" +# Hook that is invoked on the dashboard `/api/component_activities` endpoint. +# Environment variable stored here should be a callable that does not +# take any arguments and should return a dictionary mapping +# activity component type (str) to +# ray.dashboard.modules.snapshot.snapshot_head.RayActivityResponse. +# Example: "your.module.ray_cluster_activity_hook". +RAY_CLUSTER_ACTIVITY_HOOK = "RAY_CLUSTER_ACTIVITY_HOOK" + +# The number of candidate agents +CANDIDATE_AGENT_NUMBER = max(env_integer("CANDIDATE_AGENT_NUMBER", 1), 1) +# when head receive JobSubmitRequest, maybe not any agent is available, +# we need to wait for agents in other node start +WAIT_AVAILABLE_AGENT_TIMEOUT = 10 +TRY_TO_GET_AGENT_INFO_INTERVAL_SECONDS = 0.5 +RAY_JOB_ALLOW_DRIVER_ON_WORKER_NODES_ENV_VAR = "RAY_JOB_ALLOW_DRIVER_ON_WORKER_NODES" +RAY_STREAM_RUNTIME_ENV_LOG_TO_JOB_DRIVER_LOG_ENV_VAR = ( + "RAY_STREAM_RUNTIME_ENV_LOG_TO_JOB_DRIVER_LOG" +) + +# The max time to wait for the JobSupervisor to start before failing the job. +DEFAULT_JOB_START_TIMEOUT_SECONDS = 60 * 15 +RAY_JOB_START_TIMEOUT_SECONDS_ENV_VAR = "RAY_JOB_START_TIMEOUT_SECONDS" +# Port that dashboard prometheus metrics will be exported to +DASHBOARD_METRIC_PORT = env_integer("DASHBOARD_METRIC_PORT", 44227) + +NODE_TAG_KEYS = ["ip", "Version", "SessionName", "IsHeadNode"] +GPU_TAG_KEYS = NODE_TAG_KEYS + ["GpuDeviceName", "GpuIndex"] +CLUSTER_TAG_KEYS = ["node_type", "Version", "SessionName"] +COMPONENT_METRICS_TAG_KEYS = ["ip", "pid", "Version", "Component", "SessionName"] + +# Dashboard metrics are tracked separately at the dashboard. TODO(sang): Support GCS. +AVAILABLE_COMPONENT_NAMES_FOR_METRICS = { + "workers", + "raylet", + "agent", + "dashboard", + "gcs", +} +METRICS_INPUT_ROOT = os.path.join( + os.path.dirname(__file__), "modules", "metrics", "export" +) +PROMETHEUS_CONFIG_INPUT_PATH = os.path.join( + METRICS_INPUT_ROOT, "prometheus", "prometheus.yml" +) +PARENT_HEALTH_CHECK_BY_PIPE = env_bool( + "RAY_enable_pipe_based_agent_to_parent_health_check", False +) diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/dashboard.py b/vllm/lib/python3.10/site-packages/ray/dashboard/dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..2906aa9198cdb05a445930bfccb99c492ad2286d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/dashboard.py @@ -0,0 +1,275 @@ +import argparse +import logging +import logging.handlers +import os +import platform +import signal +import sys +import traceback +from typing import Optional, Set + +import ray._private.ray_constants as ray_constants +import ray._private.services +import ray._private.utils +import ray.dashboard.consts as dashboard_consts +import ray.dashboard.head as dashboard_head +import ray.dashboard.utils as dashboard_utils +from ray._private.ray_logging import setup_component_logger + +# Logger for this module. It should be configured at the entry point +# into the program using Ray. Ray provides a default configuration at +# entry/init points. +logger = logging.getLogger(__name__) + + +class Dashboard: + """A dashboard process for monitoring Ray nodes. + + This dashboard is made up of a REST API which collates data published by + Reporter processes on nodes into a json structure, and a webserver + which polls said API for display purposes. + + Args: + host: Host address of dashboard aiohttp server. + port: Port number of dashboard aiohttp server. + port_retries: The retry times to select a valid port. + gcs_address: GCS address of the cluster. + cluster_id_hex: Cluster ID hex string. + grpc_port: Port used to listen for gRPC on. + node_ip_address: The IP address of the dashboard. + serve_frontend: If configured, frontend HTML + is not served from the dashboard. + log_dir: Log directory of dashboard. + """ + + def __init__( + self, + host: str, + port: int, + port_retries: int, + gcs_address: str, + cluster_id_hex: str, + grpc_port: int, + node_ip_address: str, + log_dir: str = None, + temp_dir: str = None, + session_dir: str = None, + minimal: bool = False, + serve_frontend: bool = True, + modules_to_load: Optional[Set[str]] = None, + ): + self.dashboard_head = dashboard_head.DashboardHead( + http_host=host, + http_port=port, + http_port_retries=port_retries, + gcs_address=gcs_address, + cluster_id_hex=cluster_id_hex, + node_ip_address=node_ip_address, + grpc_port=grpc_port, + log_dir=log_dir, + temp_dir=temp_dir, + session_dir=session_dir, + minimal=minimal, + serve_frontend=serve_frontend, + modules_to_load=modules_to_load, + ) + + async def run(self): + await self.dashboard_head.run() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Ray dashboard.") + parser.add_argument( + "--host", required=True, type=str, help="The host to use for the HTTP server." + ) + parser.add_argument( + "--port", required=True, type=int, help="The port to use for the HTTP server." + ) + parser.add_argument( + "--port-retries", + required=False, + type=int, + default=0, + help="The retry times to select a valid port.", + ) + parser.add_argument( + "--gcs-address", required=True, type=str, help="The address (ip:port) of GCS." + ) + parser.add_argument( + "--cluster-id-hex", required=True, type=str, help="The cluster ID in hex." + ) + parser.add_argument( + "--grpc-port", + required=False, + type=int, + default=dashboard_consts.DASHBOARD_RPC_PORT, + help="The port for the dashboard to listen for gRPC on.", + ) + parser.add_argument( + "--node-ip-address", + required=True, + type=str, + help="The IP address of the node where this is running.", + ) + parser.add_argument( + "--logging-level", + required=False, + type=lambda s: logging.getLevelName(s.upper()), + default=ray_constants.LOGGER_LEVEL, + choices=ray_constants.LOGGER_LEVEL_CHOICES, + help=ray_constants.LOGGER_LEVEL_HELP, + ) + parser.add_argument( + "--logging-format", + required=False, + type=str, + default=ray_constants.LOGGER_FORMAT, + help=ray_constants.LOGGER_FORMAT_HELP, + ) + parser.add_argument( + "--logging-filename", + required=False, + type=str, + default=dashboard_consts.DASHBOARD_LOG_FILENAME, + help="Specify the name of log file, " + 'log to stdout if set empty, default is "{}"'.format( + dashboard_consts.DASHBOARD_LOG_FILENAME + ), + ) + parser.add_argument( + "--logging-rotate-bytes", + required=False, + type=int, + default=ray_constants.LOGGING_ROTATE_BYTES, + help="Specify the max bytes for rotating " + "log file, default is {} bytes.".format(ray_constants.LOGGING_ROTATE_BYTES), + ) + parser.add_argument( + "--logging-rotate-backup-count", + required=False, + type=int, + default=ray_constants.LOGGING_ROTATE_BACKUP_COUNT, + help="Specify the backup count of rotated log file, default is {}.".format( + ray_constants.LOGGING_ROTATE_BACKUP_COUNT + ), + ) + parser.add_argument( + "--log-dir", + required=True, + type=str, + default=None, + help="Specify the path of log directory.", + ) + parser.add_argument( + "--temp-dir", + required=True, + type=str, + default=None, + help="Specify the path of the temporary directory use by Ray process.", + ) + parser.add_argument( + "--session-dir", + required=True, + type=str, + default=None, + help="Specify the path of the session directory of the cluster.", + ) + parser.add_argument( + "--minimal", + action="store_true", + help=( + "Minimal dashboard only contains a subset of features that don't " + "require additional dependencies installed when ray is installed " + "by `pip install ray[default]`." + ), + ) + parser.add_argument( + "--modules-to-load", + required=False, + default=None, + help=( + "Specify the list of module names in [module_1],[module_2] format." + "E.g., JobHead,StateHead... " + "If nothing is specified, all modules are loaded." + ), + ) + parser.add_argument( + "--disable-frontend", + action="store_true", + help=("If configured, frontend html is not served from the server."), + ) + + args = parser.parse_args() + + try: + setup_component_logger( + logging_level=args.logging_level, + logging_format=args.logging_format, + log_dir=args.log_dir, + filename=args.logging_filename, + max_bytes=args.logging_rotate_bytes, + backup_count=args.logging_rotate_backup_count, + ) + + if args.modules_to_load: + modules_to_load = set(args.modules_to_load.strip(" ,").split(",")) + else: + # None == default. + modules_to_load = None + + # NOTE: Creating and attaching the event loop to the main OS thread be called + # before initializing Dashboard, which will initialize the grpc aio server, + # which assumes a working event loop. Ref: + # https://github.com/grpc/grpc/blob/master/src/python/grpcio/grpc/_cython/_cygrpc/aio/common.pyx.pxi#L174-L188 + loop = ray._private.utils.get_or_create_event_loop() + dashboard = Dashboard( + host=args.host, + port=args.port, + port_retries=args.port_retries, + gcs_address=args.gcs_address, + cluster_id_hex=args.cluster_id_hex, + grpc_port=args.grpc_port, + node_ip_address=args.node_ip_address, + log_dir=args.log_dir, + temp_dir=args.temp_dir, + session_dir=args.session_dir, + minimal=args.minimal, + serve_frontend=(not args.disable_frontend), + modules_to_load=modules_to_load, + ) + + def sigterm_handler(): + logger.warning("Exiting with SIGTERM immediately...") + os._exit(signal.SIGTERM) + + if sys.platform != "win32": + # TODO(rickyyx): we currently do not have any logic for actual + # graceful termination in the dashboard. Most of the underlying + # async tasks run by the dashboard head doesn't handle CancelledError. + # So a truly graceful shutdown is not trivial w/o much refactoring. + # Re-open the issue: https://github.com/ray-project/ray/issues/25518 + # if a truly graceful shutdown is required. + loop.add_signal_handler(signal.SIGTERM, sigterm_handler) + + loop.run_until_complete(dashboard.run()) + except Exception as e: + traceback_str = ray._private.utils.format_error_message(traceback.format_exc()) + message = ( + f"The dashboard on node {platform.uname()[1]} " + f"failed with the following " + f"error:\n{traceback_str}" + ) + if isinstance(e, dashboard_utils.FrontendNotFoundError): + logger.warning(message) + else: + logger.error(message) + raise e + + # Something went wrong, so push an error to all drivers. + gcs_publisher = ray._raylet.GcsPublisher(address=args.gcs_address) + ray._private.utils.publish_error_to_driver( + ray_constants.DASHBOARD_DIED_ERROR, + message, + gcs_publisher=gcs_publisher, + ) diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/dashboard_metrics.py b/vllm/lib/python3.10/site-packages/ray/dashboard/dashboard_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..7f1b6f2b22a9ed826409f80542e333aa51a5b037 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/dashboard_metrics.py @@ -0,0 +1,123 @@ +from typing import Optional + +from ray.dashboard.consts import COMPONENT_METRICS_TAG_KEYS + + +class NullMetric: + """Mock metric class to be used in case of prometheus_client import error.""" + + def set(self, *args, **kwargs): + pass + + def observe(self, *args, **kwargs): + pass + + def inc(self, *args, **kwargs): + pass + + +try: + + from prometheus_client import CollectorRegistry, Counter, Gauge, Histogram + + # The metrics in this class should be kept in sync with + # python/ray/tests/test_metrics_agent.py + class DashboardPrometheusMetrics: + def __init__(self, registry: Optional[CollectorRegistry] = None): + self.registry: CollectorRegistry = registry or CollectorRegistry( + auto_describe=True + ) + # Buckets: 5ms, 10ms, 25ms, 50ms, 75ms + # 100ms, 250ms, 500ms, 750ms + # 1s, 2.5s, 5s, 7.5s, 10s + # 20s, 40s, 60s + # used for API duration + histogram_buckets_s = [ + 0.005, + 0.01, + 0.025, + 0.05, + 0.075, + 0.1, + 0.25, + 0.5, + 0.75, + 1, + 2.5, + 5, + 7.5, + 10, + 20, + 40, + 60, + ] + self.metrics_request_duration = Histogram( + "dashboard_api_requests_duration_seconds", + "Total duration in seconds per endpoint", + ("endpoint", "http_status", "Version", "SessionName", "Component"), + unit="seconds", + namespace="ray", + registry=self.registry, + buckets=histogram_buckets_s, + ) + self.metrics_request_count = Counter( + "dashboard_api_requests_count", + "Total requests count per endpoint", + ( + "method", + "endpoint", + "http_status", + "Version", + "SessionName", + "Component", + ), + unit="requests", + namespace="ray", + registry=self.registry, + ) + self.metrics_event_loop_tasks = Gauge( + "dashboard_event_loop_tasks", + "Number of tasks currently pending in the event loop's queue.", + tuple(COMPONENT_METRICS_TAG_KEYS), + unit="tasks", + namespace="ray", + registry=self.registry, + ) + self.metrics_event_loop_lag = Gauge( + "dashboard_event_loop_lag", + "Event loop lag in seconds.", + tuple(COMPONENT_METRICS_TAG_KEYS), + unit="seconds", + namespace="ray", + registry=self.registry, + ) + self.metrics_dashboard_cpu = Gauge( + "component_cpu", + "Dashboard CPU percentage usage.", + tuple(COMPONENT_METRICS_TAG_KEYS), + unit="percentage", + namespace="ray", + registry=self.registry, + ) + self.metrics_dashboard_mem_uss = Gauge( + "component_uss", + "USS usage of all components on the node.", + tuple(COMPONENT_METRICS_TAG_KEYS), + unit="mb", + namespace="ray", + registry=self.registry, + ) + self.metrics_dashboard_mem_rss = Gauge( + "component_rss", + "RSS usage of all components on the node.", + tuple(COMPONENT_METRICS_TAG_KEYS), + unit="mb", + namespace="ray", + registry=self.registry, + ) + +except ImportError: + + class DashboardPrometheusMetrics(object): + def __getattr__(self, attr): + return NullMetric() diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/datacenter.py b/vllm/lib/python3.10/site-packages/ray/dashboard/datacenter.py new file mode 100644 index 0000000000000000000000000000000000000000..25ca83a8663bb4130b957653e2749c74bb159e4b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/datacenter.py @@ -0,0 +1,288 @@ +import logging +from typing import Any, List, Optional + +import ray.dashboard.consts as dashboard_consts +from ray._private.utils import ( + get_or_create_event_loop, + parse_pg_formatted_resources_to_original, +) +from ray.dashboard.utils import ( + Dict, + MutableNotificationDict, + async_loop_forever, + compose_state_message, +) + +logger = logging.getLogger(__name__) + + +# NOT thread safe. Every assignment must be on the main event loop thread. +class DataSource: + # {node id hex(str): node stats(dict of GetNodeStatsReply + # in node_manager.proto)} + node_stats = Dict() + # {node id hex(str): node physical stats(dict from reporter_agent.py)} + node_physical_stats = Dict() + # {actor id hex(str): actor table data(dict of ActorTableData + # in gcs.proto)} + actors = MutableNotificationDict() + # {job id hex(str): job table data(dict of JobTableData in gcs.proto)} + # {node id hex(str): dashboard agent [http port(int), grpc port(int)]} + agents = Dict() + # {node id hex(str): gcs node info(dict of GcsNodeInfo in gcs.proto)} + nodes = Dict() + # {node id hex(str): worker list} + node_workers = Dict() + # {node id hex(str): {actor id hex(str): actor table data}} + node_actors = MutableNotificationDict() + # {worker id(str): core worker stats} + core_worker_stats = Dict() + # {job id hex(str): {event id(str): event dict}} + events = Dict() + + +class DataOrganizer: + head_node_ip = None + + @staticmethod + @async_loop_forever(dashboard_consts.RAY_DASHBOARD_STATS_PURGING_INTERVAL) + async def purge(): + # Purge data that is out of date. + # These data sources are maintained by DashboardHead, + # we do not needs to purge them: + # * agents + # * nodes + alive_nodes = { + node_id + for node_id, node_info in DataSource.nodes.items() + if node_info["state"] == "ALIVE" + } + for key in DataSource.node_stats.keys() - alive_nodes: + DataSource.node_stats.pop(key) + + for key in DataSource.node_physical_stats.keys() - alive_nodes: + DataSource.node_physical_stats.pop(key) + + @classmethod + @async_loop_forever(dashboard_consts.RAY_DASHBOARD_STATS_UPDATING_INTERVAL) + async def organize(cls, thread_pool_executor): + """ + Organizes data: read from (node_physical_stats, node_stats) and updates + (node_workers, node_worker_stats). + + This methods is not really async, but DataSource is not thread safe so we need + to make sure it's on the main event loop thread. To avoid blocking the main + event loop, we yield after each node processed. + """ + loop = get_or_create_event_loop() + + node_workers = {} + core_worker_stats = {} + + # NOTE: We copy keys of the `DataSource.nodes` to make sure + # it doesn't change during the iteration (since its being updated + # from another async task) + for node_id in list(DataSource.nodes.keys()): + node_physical_stats = DataSource.node_physical_stats.get(node_id, {}) + node_stats = DataSource.node_stats.get(node_id, {}) + # Offloads the blocking operation to a thread pool executor. This also + # yields to the event loop. + workers = await loop.run_in_executor( + thread_pool_executor, + cls._extract_workers_for_node, + node_physical_stats, + node_stats, + ) + + for worker in workers: + for stats in worker.get("coreWorkerStats", []): + worker_id = stats["workerId"] + core_worker_stats[worker_id] = stats + + node_workers[node_id] = workers + + DataSource.node_workers.reset(node_workers) + DataSource.core_worker_stats.reset(core_worker_stats) + + @classmethod + def _extract_workers_for_node(cls, node_physical_stats, node_stats): + workers = [] + # Merge coreWorkerStats (node stats) to workers (node physical stats) + pid_to_worker_stats = {} + pid_to_language = {} + pid_to_job_id = {} + + for core_worker_stats in node_stats.get("coreWorkersStats", []): + pid = core_worker_stats["pid"] + + pid_to_worker_stats[pid] = core_worker_stats + pid_to_language[pid] = core_worker_stats["language"] + pid_to_job_id[pid] = core_worker_stats["jobId"] + + for worker in node_physical_stats.get("workers", []): + worker = dict(worker) + pid = worker["pid"] + + core_worker_stats = pid_to_worker_stats.get(pid) + # Empty list means core worker stats is not available. + worker["coreWorkerStats"] = [core_worker_stats] if core_worker_stats else [] + worker["language"] = pid_to_language.get( + pid, dashboard_consts.DEFAULT_LANGUAGE + ) + worker["jobId"] = pid_to_job_id.get(pid, dashboard_consts.DEFAULT_JOB_ID) + + workers.append(worker) + + return workers + + @classmethod + async def get_node_info(cls, node_id, get_summary=False): + node_physical_stats = dict(DataSource.node_physical_stats.get(node_id, {})) + node_stats = dict(DataSource.node_stats.get(node_id, {})) + node = DataSource.nodes.get(node_id, {}) + + if get_summary: + node_physical_stats.pop("workers", None) + node_stats.pop("workersStats", None) + else: + node_stats.pop("coreWorkersStats", None) + store_stats = node_stats.get("storeStats", {}) + used = int(store_stats.get("objectStoreBytesUsed", 0)) + # objectStoreBytesAvail == total in the object_manager.cc definition. + total = int(store_stats.get("objectStoreBytesAvail", 0)) + ray_stats = { + "object_store_used_memory": used, + "object_store_available_memory": total - used, + } + + node_info = node_physical_stats + # Merge node stats to node physical stats under raylet + node_info["raylet"] = node_stats + node_info["raylet"].update(ray_stats) + + # Merge GcsNodeInfo to node physical stats + node_info["raylet"].update(node) + death_info = node.get("deathInfo", {}) + node_info["raylet"]["stateMessage"] = compose_state_message( + death_info.get("reason", None), death_info.get("reasonMessage", None) + ) + + if not get_summary: + actor_table_entries = DataSource.node_actors.get(node_id, {}) + + # Merge actors to node physical stats + node_info["actors"] = { + actor_id: await DataOrganizer._get_actor_info(actor_table_entry) + for actor_id, actor_table_entry in actor_table_entries.items() + } + + # Update workers to node physical stats + node_info["workers"] = DataSource.node_workers.get(node_id, []) + + return node_info + + @classmethod + async def get_all_node_summary(cls): + return [ + # NOTE: We're intentionally awaiting in a loop to avoid excessive + # concurrency spinning up excessive # of tasks for large clusters + await DataOrganizer.get_node_info(node_id, get_summary=True) + for node_id in DataSource.nodes.keys() + ] + + @classmethod + async def get_agent_infos( + cls, target_node_ids: Optional[List[str]] = None + ) -> Dict[str, Dict[str, Any]]: + """Fetches running Agent (like HTTP/gRPC ports, IP, etc) running on every node + + :param target_node_ids: Target node ids to fetch agent info for. If omitted will + fetch the info for all agents + """ + + # Return all available agent infos in case no target node-ids were provided + target_node_ids = target_node_ids or DataSource.agents.keys() + + missing_node_ids = [ + node_id for node_id in target_node_ids if node_id not in DataSource.agents + ] + if missing_node_ids: + logger.warning( + f"Agent info was not found for {missing_node_ids}" + f" (having agent infos for {list(DataSource.agents.keys())})" + ) + return {} + + def _create_agent_info(node_id: str): + (http_port, grpc_port) = DataSource.agents[node_id] + node_ip = DataSource.nodes[node_id]["nodeManagerAddress"] + + return dict( + ipAddress=node_ip, + httpPort=int(http_port or -1), + grpcPort=int(grpc_port or -1), + httpAddress=f"{node_ip}:{http_port}", + ) + + return {node_id: _create_agent_info(node_id) for node_id in target_node_ids} + + @classmethod + async def get_actor_infos(cls, actor_ids: Optional[List[str]] = None): + target_actor_table_entries: dict[str, Optional[dict]] + if actor_ids is not None: + target_actor_table_entries = { + actor_id: DataSource.actors.get(actor_id) for actor_id in actor_ids + } + else: + target_actor_table_entries = DataSource.actors + + return { + actor_id: await DataOrganizer._get_actor_info(actor_table_entry) + for actor_id, actor_table_entry in target_actor_table_entries.items() + } + + @staticmethod + async def _get_actor_info(actor): + if actor is None: + return None + + actor = dict(actor) + worker_id = actor["address"]["workerId"] + core_worker_stats = DataSource.core_worker_stats.get(worker_id, {}) + actor_constructor = core_worker_stats.get( + "actorTitle", "Unknown actor constructor" + ) + actor["actorConstructor"] = actor_constructor + actor.update(core_worker_stats) + + # TODO(fyrestone): remove this, give a link from actor + # info to worker info in front-end. + node_id = actor["address"]["rayletId"] + pid = core_worker_stats.get("pid") + node_physical_stats = DataSource.node_physical_stats.get(node_id, {}) + actor_process_stats = None + actor_process_gpu_stats = [] + if pid: + for process_stats in node_physical_stats.get("workers", []): + if process_stats["pid"] == pid: + actor_process_stats = process_stats + break + + for gpu_stats in node_physical_stats.get("gpus", []): + # gpu_stats.get("processes") can be None, an empty list or a + # list of dictionaries. + for process in gpu_stats.get("processesPids") or []: + if process["pid"] == pid: + actor_process_gpu_stats.append(gpu_stats) + break + + actor["gpus"] = actor_process_gpu_stats + actor["processStats"] = actor_process_stats + actor["mem"] = node_physical_stats.get("mem", []) + + required_resources = parse_pg_formatted_resources_to_original( + actor["requiredResources"] + ) + actor["requiredResources"] = required_resources + + return actor diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/head.py b/vllm/lib/python3.10/site-packages/ray/dashboard/head.py new file mode 100644 index 0000000000000000000000000000000000000000..4825538a1e6d0fb04813b66722f08db00370cdcb --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/head.py @@ -0,0 +1,344 @@ +import asyncio +import logging +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Optional, Set + +import ray.dashboard.consts as dashboard_consts +import ray.dashboard.utils as dashboard_utils +import ray.experimental.internal_kv as internal_kv +from ray._private import ray_constants +from ray._private.gcs_utils import GcsAioClient +from ray._private.ray_constants import env_integer +from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag +from ray._raylet import GcsClient +from ray.dashboard.consts import DASHBOARD_METRIC_PORT +from ray.dashboard.dashboard_metrics import DashboardPrometheusMetrics +from ray.dashboard.datacenter import DataOrganizer +from ray.dashboard.utils import DashboardHeadModule, async_loop_forever + +try: + import prometheus_client +except ImportError: + prometheus_client = None + + +logger = logging.getLogger(__name__) + +GRPC_CHANNEL_OPTIONS = ( + *ray_constants.GLOBAL_GRPC_OPTIONS, + ("grpc.max_send_message_length", ray_constants.GRPC_CPP_MAX_MESSAGE_SIZE), + ("grpc.max_receive_message_length", ray_constants.GRPC_CPP_MAX_MESSAGE_SIZE), +) + +# NOTE: Executor in this head is intentionally constrained to just 1 thread by +# default to limit its concurrency, therefore reducing potential for +# GIL contention +RAY_DASHBOARD_DASHBOARD_HEAD_TPE_MAX_WORKERS = env_integer( + "RAY_DASHBOARD_DASHBOARD_HEAD_TPE_MAX_WORKERS", 1 +) + + +def initialize_grpc_port_and_server(grpc_ip, grpc_port): + try: + from grpc import aio as aiogrpc + except ImportError: + from grpc.experimental import aio as aiogrpc + + import ray._private.tls_utils + + aiogrpc.init_grpc_aio() + + server = aiogrpc.server(options=(("grpc.so_reuseport", 0),)) + + grpc_port = ray._private.tls_utils.add_port_to_grpc_server( + server, f"{grpc_ip}:{grpc_port}" + ) + + return server, grpc_port + + +class DashboardHead: + def __init__( + self, + http_host: str, + http_port: int, + http_port_retries: int, + gcs_address: str, + cluster_id_hex: str, + node_ip_address: str, + grpc_port: int, + log_dir: str, + temp_dir: str, + session_dir: str, + minimal: bool, + serve_frontend: bool, + modules_to_load: Optional[Set[str]] = None, + ): + """ + Args: + http_host: The host address for the Http server. + http_port: The port for the Http server. + http_port_retries: The maximum retry to bind ports for the Http server. + gcs_address: The GCS address in the {address}:{port} format. + log_dir: The log directory. E.g., /tmp/session_latest/logs. + temp_dir: The temp directory. E.g., /tmp. + session_dir: The session directory. E.g., tmp/session_latest. + minimal: Whether or not it will load the minimal modules. + serve_frontend: If configured, frontend HTML is + served from the dashboard. + grpc_port: The port used to listen for gRPC on. + modules_to_load: A set of module name in string to load. + By default (None), it loads all available modules. + Note that available modules could be changed depending on + minimal flags. + """ + self.minimal = minimal + self.serve_frontend = serve_frontend + # If it is the minimal mode, we shouldn't serve frontend. + if self.minimal: + self.serve_frontend = False + # Public attributes are accessible for all head modules. + # Walkaround for issue: https://github.com/ray-project/ray/issues/7084 + self.http_host = "127.0.0.1" if http_host == "localhost" else http_host + self.http_port = http_port + self.http_port_retries = http_port_retries + self._modules_to_load = modules_to_load + self._modules_loaded = False + + self._executor = ThreadPoolExecutor( + max_workers=RAY_DASHBOARD_DASHBOARD_HEAD_TPE_MAX_WORKERS, + thread_name_prefix="dashboard_head_executor", + ) + + self.gcs_address = None + assert gcs_address is not None + self.gcs_address = gcs_address + self.cluster_id_hex = cluster_id_hex + self.log_dir = log_dir + self.temp_dir = temp_dir + self.session_dir = session_dir + self.session_name = Path(session_dir).name + self.aiogrpc_gcs_channel = None + self.gcs_aio_client = None + self.gcs_error_subscriber = None + self.gcs_log_subscriber = None + self.ip = node_ip_address + DataOrganizer.head_node_ip = self.ip + + if self.minimal: + self.server, self.grpc_port = None, None + else: + grpc_ip = "127.0.0.1" if self.ip == "127.0.0.1" else "0.0.0.0" + self.server, self.grpc_port = initialize_grpc_port_and_server( + grpc_ip, grpc_port + ) + logger.info("Dashboard head grpc address: %s:%s", grpc_ip, self.grpc_port) + # If the dashboard is started as non-minimal version, http server should + # be configured to expose APIs. + self.http_server = None + + async def _configure_http_server(self, modules): + from ray.dashboard.http_server_head import HttpServerDashboardHead + + self.http_server = HttpServerDashboardHead( + self.ip, + self.http_host, + self.http_port, + self.http_port_retries, + self.gcs_address, + self.session_name, + self.metrics, + ) + await self.http_server.run(modules) + + @property + def http_session(self): + if not self._modules_loaded and not self.http_server: + # When the dashboard is still starting up, this property gets + # called as part of the method_route_table_factory magic. In + # this case, the property is not actually used but the magic + # method calls every property to look for a route to add to + # the global route table. It should be okay for http_server + # to still be None at this point. + return None + assert self.http_server, "Accessing unsupported API in a minimal ray." + return self.http_server.http_session + + @async_loop_forever(dashboard_consts.GCS_CHECK_ALIVE_INTERVAL_SECONDS) + async def _gcs_check_alive(self): + try: + # If gcs is permanently dead, gcs client will exit the process + # (see gcs_rpc_client.h) + await self.gcs_aio_client.check_alive(node_ips=[], timeout=None) + except Exception: + logger.warning("Failed to check gcs aliveness, will retry", exc_info=True) + + def _load_modules(self, modules_to_load: Optional[Set[str]] = None): + """Load dashboard head modules. + + Args: + modules: A list of module names to load. By default (None), + it loads all modules. + """ + modules = [] + head_cls_list = dashboard_utils.get_all_modules(DashboardHeadModule) + + # Select modules to load. + modules_to_load = modules_to_load or {m.__name__ for m in head_cls_list} + logger.info("Modules to load: %s", modules_to_load) + + for cls in head_cls_list: + logger.info("Loading %s: %s", DashboardHeadModule.__name__, cls) + if cls.__name__ in modules_to_load: + c = cls(self) + modules.append(c) + + # Verify modules are loaded as expected. + loaded_modules = {type(m).__name__ for m in modules} + if loaded_modules != modules_to_load: + assert False, ( + "Actual loaded modules, {}, doesn't match the requested modules " + "to load, {}".format(loaded_modules, modules_to_load) + ) + + self._modules_loaded = True + logger.info("Loaded %d modules. %s", len(modules), modules) + return modules + + async def _setup_metrics(self, gcs_aio_client): + metrics = DashboardPrometheusMetrics() + + # Setup prometheus metrics export server + assert internal_kv._internal_kv_initialized() + assert gcs_aio_client is not None + address = f"{self.ip}:{DASHBOARD_METRIC_PORT}" + await gcs_aio_client.internal_kv_put( + "DashboardMetricsAddress".encode(), address.encode(), True, namespace=None + ) + if prometheus_client: + try: + logger.info( + "Starting dashboard metrics server on port {}".format( + DASHBOARD_METRIC_PORT + ) + ) + kwargs = {"addr": "127.0.0.1"} if self.ip == "127.0.0.1" else {} + prometheus_client.start_http_server( + port=DASHBOARD_METRIC_PORT, + registry=metrics.registry, + **kwargs, + ) + except Exception: + logger.exception( + "An exception occurred while starting the metrics server." + ) + elif not prometheus_client: + logger.warning( + "`prometheus_client` not found, so metrics will not be exported." + ) + + return metrics + + async def run(self): + gcs_address = self.gcs_address + + # Dashboard will handle connection failure automatically + self.gcs_client = GcsClient( + address=gcs_address, nums_reconnect_retry=0, cluster_id=self.cluster_id_hex + ) + self.gcs_aio_client = GcsAioClient( + address=gcs_address, nums_reconnect_retry=0, cluster_id=self.cluster_id_hex + ) + internal_kv._initialize_internal_kv(self.gcs_client) + + if self.minimal: + self.aiogrpc_gcs_channel = None + self.metrics = None + else: + from ray._private.gcs_utils import GcsChannel + + # TODO(ryw): once we removed the old gcs client, also remove this. + gcs_channel = GcsChannel(gcs_address=gcs_address, aio=True) + gcs_channel.connect() + self.aiogrpc_gcs_channel = gcs_channel.channel() + + self.metrics = await self._setup_metrics(self.gcs_aio_client) + try: + assert internal_kv._internal_kv_initialized() + # Note: We always record the usage, but it is not reported + # if the usage stats is disabled. + record_extra_usage_tag(TagKey.DASHBOARD_USED, "False") + except Exception as e: + logger.warning( + "Failed to record the dashboard usage. " + "This error message is harmless and can be ignored. " + f"Error: {e}" + ) + + # Start a grpc asyncio server. + if self.server: + await self.server.start() + + async def _async_notify(): + """Notify signals from queue.""" + while True: + co = await dashboard_utils.NotifyQueue.get() + try: + await co + except Exception: + logger.exception(f"Error notifying coroutine {co}") + + modules = self._load_modules(self._modules_to_load) + + http_host, http_port = self.http_host, self.http_port + if self.serve_frontend: + logger.info("Initialize the http server.") + await self._configure_http_server(modules) + http_host, http_port = self.http_server.get_address() + logger.info(f"http server initialized at {http_host}:{http_port}") + else: + logger.info("http server disabled.") + + # We need to expose dashboard's node's ip for other worker nodes + # if it's listening to all interfaces. + dashboard_http_host = ( + self.ip + if self.http_host != ray_constants.DEFAULT_DASHBOARD_IP + else http_host + ) + # This synchronous code inside an async context is not great. + # It is however acceptable, because this only gets run once + # during initialization and therefore cannot block the event loop. + # This could be done better in the future, including + # removing the polling on the Ray side, by communicating the + # server address to Ray via stdin / stdout or a pipe. + self.gcs_client.internal_kv_put( + ray_constants.DASHBOARD_ADDRESS.encode(), + f"{dashboard_http_host}:{http_port}".encode(), + True, + namespace=ray_constants.KV_NAMESPACE_DASHBOARD, + ) + self.gcs_client.internal_kv_put( + dashboard_consts.DASHBOARD_RPC_ADDRESS.encode(), + f"{self.ip}:{self.grpc_port}".encode(), + True, + namespace=ray_constants.KV_NAMESPACE_DASHBOARD, + ) + + # Freeze signal after all modules loaded. + dashboard_utils.SignalManager.freeze() + concurrent_tasks = [ + self._gcs_check_alive(), + _async_notify(), + DataOrganizer.purge(), + DataOrganizer.organize(self._executor), + ] + for m in modules: + concurrent_tasks.append(m.run(self.server)) + if self.server: + concurrent_tasks.append(self.server.wait_for_termination()) + await asyncio.gather(*concurrent_tasks) + + if self.http_server: + await self.http_server.cleanup() diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/http_server_agent.py b/vllm/lib/python3.10/site-packages/ray/dashboard/http_server_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..fe4c88ed1992e02c2833e1bbbd146a96c3ac8905 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/http_server_agent.py @@ -0,0 +1,83 @@ +import logging + +from packaging.version import Version + +import ray.dashboard.optional_utils as dashboard_optional_utils +from ray._private.utils import get_or_create_event_loop +from ray.dashboard.optional_deps import aiohttp, aiohttp_cors, hdrs + +logger = logging.getLogger(__name__) +routes = dashboard_optional_utils.DashboardAgentRouteTable + + +class HttpServerAgent: + def __init__(self, ip, listen_port): + self.ip = ip + self.listen_port = listen_port + self.http_host = None + self.http_port = None + self.http_session = None + self.runner = None + + async def start(self, modules): + # Create a http session for all modules. + # aiohttp<4.0.0 uses a 'loop' variable, aiohttp>=4.0.0 doesn't anymore + if Version(aiohttp.__version__) < Version("4.0.0"): + self.http_session = aiohttp.ClientSession(loop=get_or_create_event_loop()) + else: + self.http_session = aiohttp.ClientSession() + + # Bind routes for every module so that each module + # can use decorator-style routes. + for c in modules: + dashboard_optional_utils.DashboardAgentRouteTable.bind(c) + + app = aiohttp.web.Application() + app.add_routes(routes=routes.bound_routes()) + + # Enable CORS on all routes. + cors = aiohttp_cors.setup( + app, + defaults={ + "*": aiohttp_cors.ResourceOptions( + allow_credentials=True, + expose_headers="*", + allow_methods="*", + allow_headers=("Content-Type", "X-Header"), + ) + }, + ) + for route in list(app.router.routes()): + cors.add(route) + + self.runner = aiohttp.web.AppRunner(app) + await self.runner.setup() + try: + site = aiohttp.web.TCPSite( + self.runner, + "127.0.0.1" if self.ip == "127.0.0.1" else "0.0.0.0", + self.listen_port, + ) + await site.start() + except OSError as e: + logger.error( + f"Agent port #{self.listen_port} already in use. " + "Failed to start agent. " + f"Ensure port #{self.listen_port} is available, and then try again." + ) + raise e + self.http_host, self.http_port, *_ = site._server.sockets[0].getsockname() + logger.info( + "Dashboard agent http address: %s:%s", self.http_host, self.http_port + ) + + # Dump registered http routes. + dump_routes = [r for r in app.router.routes() if r.method != hdrs.METH_HEAD] + for r in dump_routes: + logger.info(r) + logger.info("Registered %s routes.", len(dump_routes)) + + async def cleanup(self): + # Wait for finish signal. + await self.runner.cleanup() + await self.http_session.close() diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/http_server_head.py b/vllm/lib/python3.10/site-packages/ray/dashboard/http_server_head.py new file mode 100644 index 0000000000000000000000000000000000000000..078d4a97dd38d21a7b675653882779f4b8b55a8e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/http_server_head.py @@ -0,0 +1,289 @@ +import asyncio +import errno +import ipaddress +import logging +import os +import pathlib +import sys +import time +from math import floor + +from packaging.version import Version + +import ray +import ray.dashboard.optional_utils as dashboard_optional_utils +import ray.dashboard.timezone_utils as timezone_utils +import ray.dashboard.utils as dashboard_utils +from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag +from ray._private.utils import get_or_create_event_loop +from ray.dashboard.dashboard_metrics import DashboardPrometheusMetrics + +# All third-party dependencies that are not included in the minimal Ray +# installation must be included in this file. This allows us to determine if +# the agent has the necessary dependencies to be started. +from ray.dashboard.optional_deps import aiohttp, hdrs + +# Logger for this module. It should be configured at the entry point +# into the program using Ray. Ray provides a default configuration at +# entry/init points. +logger = logging.getLogger(__name__) +routes = dashboard_optional_utils.DashboardHeadRouteTable + +# Env var that enables follow_symlinks for serving UI static files. +# This is an advanced setting that should only be used with special Ray installations +# where the dashboard build files are symlinked to a different directory. +# This is not recommended for most users and can pose a security risk. +# Please reference the aiohttp docs here: +# https://docs.aiohttp.org/en/stable/web_reference.html#aiohttp.web.UrlDispatcher.add_static +ENV_VAR_FOLLOW_SYMLINKS = "RAY_DASHBOARD_BUILD_FOLLOW_SYMLINKS" +FOLLOW_SYMLINKS_ENABLED = os.environ.get(ENV_VAR_FOLLOW_SYMLINKS) == "1" +if FOLLOW_SYMLINKS_ENABLED: + logger.warning( + "Enabling RAY_DASHBOARD_BUILD_FOLLOW_SYMLINKS is not recommended as it " + "allows symlinks to directories outside the dashboard build folder. " + "You may accidentally expose files on your system outside of the " + "build directory." + ) + + +def setup_static_dir(): + build_dir = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "client", "build" + ) + module_name = os.path.basename(os.path.dirname(__file__)) + if not os.path.isdir(build_dir): + raise dashboard_utils.FrontendNotFoundError( + errno.ENOENT, + "Dashboard build directory not found. If installing " + "from source, please follow the additional steps " + "required to build the dashboard" + f"(cd python/ray/{module_name}/client " + "&& npm ci " + "&& npm run build)", + build_dir, + ) + + static_dir = os.path.join(build_dir, "static") + routes.static("/static", static_dir, follow_symlinks=FOLLOW_SYMLINKS_ENABLED) + return build_dir + + +class HttpServerDashboardHead: + def __init__( + self, + ip: str, + http_host: str, + http_port: int, + http_port_retries: int, + gcs_address: str, + session_name: str, + metrics: DashboardPrometheusMetrics, + ): + self.ip = ip + self.http_host = http_host + self.http_port = http_port + self.http_port_retries = http_port_retries + self.head_node_ip = gcs_address.split(":")[0] + self.metrics = metrics + self._session_name = session_name + + # Below attirubtes are filled after `run` API is invoked. + self.runner = None + + # Setup Dashboard Routes + try: + build_dir = setup_static_dir() + logger.info("Setup static dir for dashboard: %s", build_dir) + except dashboard_utils.FrontendNotFoundError as ex: + # Not to raise FrontendNotFoundError due to NPM incompatibilities + # with Windows. + # Please refer to ci.sh::build_dashboard_front_end() + if sys.platform in ["win32", "cygwin"]: + logger.warning(ex) + else: + raise ex + dashboard_optional_utils.DashboardHeadRouteTable.bind(self) + + # Create a http session for all modules. + # aiohttp<4.0.0 uses a 'loop' variable, aiohttp>=4.0.0 doesn't anymore + if Version(aiohttp.__version__) < Version("4.0.0"): + self.http_session = aiohttp.ClientSession(loop=get_or_create_event_loop()) + else: + self.http_session = aiohttp.ClientSession() + + @routes.get("/") + async def get_index(self, req) -> aiohttp.web.FileResponse: + try: + # This API will be no-op after the first report. + # Note: We always record the usage, but it is not reported + # if the usage stats is disabled. + record_extra_usage_tag(TagKey.DASHBOARD_USED, "True") + except Exception as e: + logger.warning( + "Failed to record the dashboard usage. " + "This error message is harmless and can be ignored. " + f"Error: {e}" + ) + resp = aiohttp.web.FileResponse( + os.path.join( + os.path.dirname(os.path.abspath(__file__)), "client/build/index.html" + ) + ) + resp.headers["Cache-Control"] = "no-cache" + return resp + + @routes.get("/favicon.ico") + async def get_favicon(self, req) -> aiohttp.web.FileResponse: + return aiohttp.web.FileResponse( + os.path.join( + os.path.dirname(os.path.abspath(__file__)), "client/build/favicon.ico" + ) + ) + + @routes.get("/timezone") + async def get_timezone(self, req) -> aiohttp.web.Response: + try: + current_timezone = timezone_utils.get_current_timezone_info() + return aiohttp.web.json_response(current_timezone) + + except Exception as e: + logger.error(f"Error getting timezone: {e}") + return aiohttp.web.Response( + status=500, text="Internal Server Error:" + str(e) + ) + + def get_address(self): + assert self.http_host and self.http_port + return self.http_host, self.http_port + + @aiohttp.web.middleware + async def path_clean_middleware(self, request, handler): + if request.path.startswith("/static") or request.path.startswith("/logs"): + parent = pathlib.PurePosixPath( + "/logs" if request.path.startswith("/logs") else "/static" + ) + + # If the destination is not relative to the expected directory, + # then the user is attempting path traversal, so deny the request. + request_path = pathlib.PurePosixPath( + pathlib.posixpath.realpath(request.path) + ) + if request_path != parent and parent not in request_path.parents: + logger.info( + f"Rejecting {request_path=} because it is not relative to {parent=}" + ) + raise aiohttp.web.HTTPForbidden() + return await handler(request) + + @aiohttp.web.middleware + async def browsers_no_post_put_middleware(self, request, handler): + if ( + # A best effort test for browser traffic. All common browsers + # start with Mozilla at the time of writing. + request.headers["User-Agent"].startswith("Mozilla") + and request.method in [hdrs.METH_POST, hdrs.METH_PUT] + ): + return aiohttp.web.Response( + status=405, text="Method Not Allowed for browser traffic." + ) + + return await handler(request) + + @aiohttp.web.middleware + async def metrics_middleware(self, request, handler): + start_time = time.monotonic() + + try: + response = await handler(request) + status_tag = f"{floor(response.status / 100)}xx" + return response + except (Exception, asyncio.CancelledError): + status_tag = "5xx" + raise + finally: + resp_time = time.monotonic() - start_time + try: + self.metrics.metrics_request_duration.labels( + endpoint=handler.__name__, + http_status=status_tag, + Version=ray.__version__, + SessionName=self._session_name, + Component="dashboard", + ).observe(resp_time) + self.metrics.metrics_request_count.labels( + method=request.method, + endpoint=handler.__name__, + http_status=status_tag, + Version=ray.__version__, + SessionName=self._session_name, + Component="dashboard", + ).inc() + except Exception as e: + logger.exception(f"Error emitting api metrics: {e}") + + @aiohttp.web.middleware + async def cache_control_static_middleware(self, request, handler): + if request.path.startswith("/static"): + response = await handler(request) + response.headers["Cache-Control"] = "max-age=31536000" + return response + return await handler(request) + + async def run(self, modules): + # Bind http routes of each module. + for c in modules: + dashboard_optional_utils.DashboardHeadRouteTable.bind(c) + + # Http server should be initialized after all modules loaded. + # working_dir uploads for job submission can be up to 100MiB. + app = aiohttp.web.Application( + client_max_size=100 * 1024**2, + middlewares=[ + self.metrics_middleware, + self.path_clean_middleware, + self.browsers_no_post_put_middleware, + self.cache_control_static_middleware, + ], + ) + app.add_routes(routes=routes.bound_routes()) + + self.runner = aiohttp.web.AppRunner( + app, + access_log_format=( + "%a %t '%r' %s %b bytes %D us " "'%{Referer}i' '%{User-Agent}i'" + ), + ) + await self.runner.setup() + last_ex = None + for i in range(1 + self.http_port_retries): + try: + site = aiohttp.web.TCPSite(self.runner, self.http_host, self.http_port) + await site.start() + break + except OSError as e: + last_ex = e + self.http_port += 1 + logger.warning("Try to use port %s: %s", self.http_port, e) + else: + raise Exception( + f"Failed to find a valid port for dashboard after " + f"{self.http_port_retries} retries: {last_ex}" + ) + self.http_host, self.http_port, *_ = site._server.sockets[0].getsockname() + self.http_host = ( + self.ip + if ipaddress.ip_address(self.http_host).is_unspecified + else self.http_host + ) + logger.info( + "Dashboard head http address: %s:%s", self.http_host, self.http_port + ) + # Dump registered http routes. + dump_routes = [r for r in app.router.routes() if r.method != hdrs.METH_HEAD] + for r in dump_routes: + logger.info(r) + logger.info("Registered %s routes.", len(dump_routes)) + + async def cleanup(self): + # Wait for finish signal. + await self.runner.cleanup() diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/k8s_utils.py b/vllm/lib/python3.10/site-packages/ray/dashboard/k8s_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c5da030f4417ffde81b176a2b73a9296a6d442 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/k8s_utils.py @@ -0,0 +1,111 @@ +import logging + +from ray._private.utils import get_num_cpus + +logger = logging.getLogger(__name__) + +CPU_USAGE_PATH = "/sys/fs/cgroup/cpuacct/cpuacct.usage" +CPU_USAGE_PATH_V2 = "/sys/fs/cgroup/cpu.stat" +PROC_STAT_PATH = "/proc/stat" + +container_num_cpus = None +host_num_cpus = None + +last_cpu_usage = None +last_system_usage = None + + +def cpu_percent(): + """Estimate CPU usage percent for Ray pod managed by Kubernetes + Operator. + + Computed by the following steps + (1) Replicate the logic used by 'docker stats' cli command. + See https://github.com/docker/cli/blob/c0a6b1c7b30203fbc28cd619acb901a95a80e30e/cli/command/container/stats_helpers.go#L166. + (2) Divide by the number of CPUs available to the container, so that + e.g. full capacity use of 2 CPUs will read as 100%, + rather than 200%. + + Step (1) above works by + dividing delta in cpu usage by + delta in total host cpu usage, averaged over host's cpus. + + Since deltas are not initially available, return 0.0 on first call. + """ # noqa + global last_system_usage + global last_cpu_usage + try: + cpu_usage = _cpu_usage() + system_usage = _system_usage() + # Return 0.0 on first call. + if last_system_usage is None: + cpu_percent = 0.0 + else: + cpu_delta = cpu_usage - last_cpu_usage + # "System time passed." (Typically close to clock time.) + system_delta = (system_usage - last_system_usage) / _host_num_cpus() + + quotient = cpu_delta / system_delta + cpu_percent = round(quotient * 100 / get_num_cpus(), 1) + last_system_usage = system_usage + last_cpu_usage = cpu_usage + # Computed percentage might be slightly above 100%. + return min(cpu_percent, 100.0) + except Exception: + logger.exception("Error computing CPU usage of Ray Kubernetes pod.") + return 0.0 + + +def _cpu_usage(): + """Compute total cpu usage of the container in nanoseconds + by reading from cpuacct in cgroups v1 or cpu.stat in cgroups v2.""" + try: + # cgroups v1 + return int(open(CPU_USAGE_PATH).read()) + except FileNotFoundError: + # cgroups v2 + cpu_stat_text = open(CPU_USAGE_PATH_V2).read() + # e.g. "usage_usec 16089294616" + cpu_stat_first_line = cpu_stat_text.split("\n")[0] + # get the second word of the first line, cast as an integer + # this is the CPU usage is microseconds + cpu_usec = int(cpu_stat_first_line.split()[1]) + # Convert to nanoseconds and return. + return cpu_usec * 1000 + + +def _system_usage(): + """ + Computes total CPU usage of the host in nanoseconds. + + Logic taken from here: + https://github.com/moby/moby/blob/b42ac8d370a8ef8ec720dff0ca9dfb3530ac0a6a/daemon/stats/collector_unix.go#L31 + + See also the /proc/stat entry here: + https://man7.org/linux/man-pages/man5/proc.5.html + """ # noqa + cpu_summary_str = open(PROC_STAT_PATH).read().split("\n")[0] + parts = cpu_summary_str.split() + assert parts[0] == "cpu" + usage_data = parts[1:8] + total_clock_ticks = sum(int(entry) for entry in usage_data) + # 100 clock ticks per second, 10^9 ns per second + usage_ns = total_clock_ticks * 10**7 + return usage_ns + + +def _host_num_cpus(): + """Number of physical CPUs, obtained by parsing /proc/stat.""" + global host_num_cpus + if host_num_cpus is None: + proc_stat_lines = open(PROC_STAT_PATH).read().split("\n") + split_proc_stat_lines = [line.split() for line in proc_stat_lines] + cpu_lines = [ + split_line + for split_line in split_proc_stat_lines + if len(split_line) > 0 and "cpu" in split_line[0] + ] + # Number of lines starting with a word including 'cpu', subtracting + # 1 for the first summary line. + host_num_cpus = len(cpu_lines) - 1 + return host_num_cpus diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/memory_utils.py b/vllm/lib/python3.10/site-packages/ray/dashboard/memory_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..83b22631418cd5442279883a0d1e0a386dbd59ce --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/memory_utils.py @@ -0,0 +1,524 @@ +import base64 +import logging +from collections import defaultdict +from enum import Enum +from typing import List + +import ray +from ray._private.internal_api import node_stats +from ray._raylet import ActorID, JobID, TaskID + +logger = logging.getLogger(__name__) + +# These values are used to calculate if objectRefs are actor handles. +TASKID_BYTES_SIZE = TaskID.size() +ACTORID_BYTES_SIZE = ActorID.size() +JOBID_BYTES_SIZE = JobID.size() + + +def decode_object_ref_if_needed(object_ref: str) -> bytes: + """Decode objectRef bytes string. + + gRPC reply contains an objectRef that is encodded by Base64. + This function is used to decode the objectRef. + Note that there are times that objectRef is already decoded as + a hex string. In this case, just convert it to a binary number. + """ + if object_ref.endswith("="): + # If the object ref ends with =, that means it is base64 encoded. + # Object refs will always have = as a padding + # when it is base64 encoded because objectRef is always 20B. + return base64.standard_b64decode(object_ref) + else: + return ray._private.utils.hex_to_binary(object_ref) + + +class SortingType(Enum): + PID = 1 + OBJECT_SIZE = 3 + REFERENCE_TYPE = 4 + + +class GroupByType(Enum): + NODE_ADDRESS = "node" + STACK_TRACE = "stack_trace" + + +class ReferenceType(Enum): + # We don't use enum because enum is not json serializable. + ACTOR_HANDLE = "ACTOR_HANDLE" + PINNED_IN_MEMORY = "PINNED_IN_MEMORY" + LOCAL_REFERENCE = "LOCAL_REFERENCE" + USED_BY_PENDING_TASK = "USED_BY_PENDING_TASK" + CAPTURED_IN_OBJECT = "CAPTURED_IN_OBJECT" + UNKNOWN_STATUS = "UNKNOWN_STATUS" + + +def get_sorting_type(sort_by: str): + """Translate string input into SortingType instance""" + sort_by = sort_by.upper() + if sort_by == "PID": + return SortingType.PID + elif sort_by == "OBJECT_SIZE": + return SortingType.OBJECT_SIZE + elif sort_by == "REFERENCE_TYPE": + return SortingType.REFERENCE_TYPE + else: + raise Exception( + "The sort-by input provided is not one of\ + PID, OBJECT_SIZE, or REFERENCE_TYPE." + ) + + +def get_group_by_type(group_by: str): + """Translate string input into GroupByType instance""" + group_by = group_by.upper() + if group_by == "NODE_ADDRESS": + return GroupByType.NODE_ADDRESS + elif group_by == "STACK_TRACE": + return GroupByType.STACK_TRACE + else: + raise Exception( + "The group-by input provided is not one of\ + NODE_ADDRESS or STACK_TRACE." + ) + + +class MemoryTableEntry: + def __init__( + self, *, object_ref: dict, node_address: str, is_driver: bool, pid: int + ): + # worker info + self.is_driver = is_driver + self.pid = pid + self.node_address = node_address + + # object info + self.task_status = object_ref.get("taskStatus", "?") + if self.task_status == "NIL": + self.task_status = "-" + self.attempt_number = int(object_ref.get("attemptNumber", 0)) + 1 + self.object_size = int(object_ref.get("objectSize", -1)) + self.call_site = object_ref.get("callSite", "") + if len(self.call_site) == 0: + self.call_site = "disabled" + self.object_ref = ray.ObjectRef( + decode_object_ref_if_needed(object_ref["objectId"]) + ) + + # reference info + self.local_ref_count = int(object_ref.get("localRefCount", 0)) + self.pinned_in_memory = bool(object_ref.get("pinnedInMemory", False)) + self.submitted_task_ref_count = int(object_ref.get("submittedTaskRefCount", 0)) + self.contained_in_owned = [ + ray.ObjectRef(decode_object_ref_if_needed(object_ref)) + for object_ref in object_ref.get("containedInOwned", []) + ] + self.reference_type = self._get_reference_type() + + def is_valid(self) -> bool: + # If the entry doesn't have a reference type or some invalid state, + # (e.g., no object ref presented), it is considered invalid. + if ( + not self.pinned_in_memory + and self.local_ref_count == 0 + and self.submitted_task_ref_count == 0 + and len(self.contained_in_owned) == 0 + ): + return False + elif self.object_ref.is_nil(): + return False + else: + return True + + def group_key(self, group_by_type: GroupByType) -> str: + if group_by_type == GroupByType.NODE_ADDRESS: + return self.node_address + elif group_by_type == GroupByType.STACK_TRACE: + return self.call_site + else: + raise ValueError(f"group by type {group_by_type} is invalid.") + + def _get_reference_type(self) -> str: + if self._is_object_ref_actor_handle(): + return ReferenceType.ACTOR_HANDLE.value + if self.pinned_in_memory: + return ReferenceType.PINNED_IN_MEMORY.value + elif self.submitted_task_ref_count > 0: + return ReferenceType.USED_BY_PENDING_TASK.value + elif self.local_ref_count > 0: + return ReferenceType.LOCAL_REFERENCE.value + elif len(self.contained_in_owned) > 0: + return ReferenceType.CAPTURED_IN_OBJECT.value + else: + return ReferenceType.UNKNOWN_STATUS.value + + def _is_object_ref_actor_handle(self) -> bool: + object_ref_hex = self.object_ref.hex() + + # We need to multiply 2 because we need bits size instead of bytes size. + taskid_random_bits_size = (TASKID_BYTES_SIZE - ACTORID_BYTES_SIZE) * 2 + actorid_random_bits_size = (ACTORID_BYTES_SIZE - JOBID_BYTES_SIZE) * 2 + + # random (8B) | ActorID(6B) | flag (2B) | index (6B) + # ActorID(6B) == ActorRandomByte(4B) + JobID(2B) + # If random bytes are all 'f', but ActorRandomBytes + # are not all 'f', that means it is an actor creation + # task, which is an actor handle. + random_bits = object_ref_hex[:taskid_random_bits_size] + actor_random_bits = object_ref_hex[ + taskid_random_bits_size : taskid_random_bits_size + actorid_random_bits_size + ] + if random_bits == "f" * 16 and not actor_random_bits == "f" * 24: + return True + else: + return False + + def as_dict(self): + return { + "object_ref": self.object_ref.hex(), + "pid": self.pid, + "node_ip_address": self.node_address, + "object_size": self.object_size, + "reference_type": self.reference_type, + "call_site": self.call_site, + "task_status": self.task_status, + "attempt_number": self.attempt_number, + "local_ref_count": self.local_ref_count, + "pinned_in_memory": self.pinned_in_memory, + "submitted_task_ref_count": self.submitted_task_ref_count, + "contained_in_owned": [ + object_ref.hex() for object_ref in self.contained_in_owned + ], + "type": "Driver" if self.is_driver else "Worker", + } + + def __str__(self): + return self.__repr__() + + def __repr__(self): + return str(self.as_dict()) + + +class MemoryTable: + def __init__( + self, + entries: List[MemoryTableEntry], + group_by_type: GroupByType = GroupByType.NODE_ADDRESS, + sort_by_type: SortingType = SortingType.PID, + ): + self.table = entries + # Group is a list of memory tables grouped by a group key. + self.group = {} + self.summary = defaultdict(int) + # NOTE YOU MUST SORT TABLE BEFORE GROUPING. + # self._group_by(..)._sort_by(..) != self._sort_by(..)._group_by(..) + if group_by_type and sort_by_type: + self.setup(group_by_type, sort_by_type) + elif group_by_type: + self._group_by(group_by_type) + elif sort_by_type: + self._sort_by(sort_by_type) + + def setup(self, group_by_type: GroupByType, sort_by_type: SortingType): + """Setup memory table. + + This will sort entries first and group them after. + Sort order will be still kept. + """ + self._sort_by(sort_by_type)._group_by(group_by_type) + for group_memory_table in self.group.values(): + group_memory_table.summarize() + self.summarize() + return self + + def insert_entry(self, entry: MemoryTableEntry): + self.table.append(entry) + + def summarize(self): + # Reset summary. + total_object_size = 0 + total_local_ref_count = 0 + total_pinned_in_memory = 0 + total_used_by_pending_task = 0 + total_captured_in_objects = 0 + total_actor_handles = 0 + + for entry in self.table: + if entry.object_size > 0: + total_object_size += entry.object_size + if entry.reference_type == ReferenceType.LOCAL_REFERENCE.value: + total_local_ref_count += 1 + elif entry.reference_type == ReferenceType.PINNED_IN_MEMORY.value: + total_pinned_in_memory += 1 + elif entry.reference_type == ReferenceType.USED_BY_PENDING_TASK.value: + total_used_by_pending_task += 1 + elif entry.reference_type == ReferenceType.CAPTURED_IN_OBJECT.value: + total_captured_in_objects += 1 + elif entry.reference_type == ReferenceType.ACTOR_HANDLE.value: + total_actor_handles += 1 + + self.summary = { + "total_object_size": total_object_size, + "total_local_ref_count": total_local_ref_count, + "total_pinned_in_memory": total_pinned_in_memory, + "total_used_by_pending_task": total_used_by_pending_task, + "total_captured_in_objects": total_captured_in_objects, + "total_actor_handles": total_actor_handles, + } + return self + + def _sort_by(self, sorting_type: SortingType): + if sorting_type == SortingType.PID: + self.table.sort(key=lambda entry: entry.pid) + elif sorting_type == SortingType.OBJECT_SIZE: + self.table.sort(key=lambda entry: entry.object_size) + elif sorting_type == SortingType.REFERENCE_TYPE: + self.table.sort(key=lambda entry: entry.reference_type) + else: + raise ValueError(f"Give sorting type: {sorting_type} is invalid.") + return self + + def _group_by(self, group_by_type: GroupByType): + """Group entries and summarize the result. + + NOTE: Each group is another MemoryTable. + """ + # Reset group + self.group = {} + + # Build entries per group. + group = defaultdict(list) + for entry in self.table: + group[entry.group_key(group_by_type)].append(entry) + + # Build a group table. + for group_key, entries in group.items(): + self.group[group_key] = MemoryTable( + entries, group_by_type=None, sort_by_type=None + ) + for group_key, group_memory_table in self.group.items(): + group_memory_table.summarize() + return self + + def as_dict(self): + return { + "summary": self.summary, + "group": { + group_key: { + "entries": group_memory_table.get_entries(), + "summary": group_memory_table.summary, + } + for group_key, group_memory_table in self.group.items() + }, + } + + def get_entries(self) -> List[dict]: + return [entry.as_dict() for entry in self.table] + + def __repr__(self): + return str(self.as_dict()) + + def __str__(self): + return self.__repr__() + + +def construct_memory_table( + workers_stats: List, + group_by: GroupByType = GroupByType.NODE_ADDRESS, + sort_by=SortingType.OBJECT_SIZE, +) -> MemoryTable: + memory_table_entries = [] + for core_worker_stats in workers_stats: + pid = core_worker_stats["pid"] + is_driver = core_worker_stats.get("workerType") == "DRIVER" + node_address = core_worker_stats["ipAddress"] + object_refs = core_worker_stats.get("objectRefs", []) + + for object_ref in object_refs: + memory_table_entry = MemoryTableEntry( + object_ref=object_ref, + node_address=node_address, + is_driver=is_driver, + pid=pid, + ) + if memory_table_entry.is_valid(): + memory_table_entries.append(memory_table_entry) + memory_table = MemoryTable( + memory_table_entries, group_by_type=group_by, sort_by_type=sort_by + ) + return memory_table + + +def track_reference_size(group): + """Returns dictionary mapping reference type + to memory usage for a given memory table group.""" + d = defaultdict(int) + table_name = { + "LOCAL_REFERENCE": "total_local_ref_count", + "PINNED_IN_MEMORY": "total_pinned_in_memory", + "USED_BY_PENDING_TASK": "total_used_by_pending_task", + "CAPTURED_IN_OBJECT": "total_captured_in_objects", + "ACTOR_HANDLE": "total_actor_handles", + } + for entry in group["entries"]: + size = entry["object_size"] + if size == -1: + # size not recorded + size = 0 + d[table_name[entry["reference_type"]]] += size + return d + + +def memory_summary( + state, + group_by="NODE_ADDRESS", + sort_by="OBJECT_SIZE", + line_wrap=True, + unit="B", + num_entries=None, +) -> str: + # Get terminal size + import shutil + + from ray.dashboard.modules.node.node_head import node_stats_to_dict + + size = shutil.get_terminal_size((80, 20)).columns + line_wrap_threshold = 137 + + # Unit conversions + units = {"B": 10**0, "KB": 10**3, "MB": 10**6, "GB": 10**9} + + # Fetch core memory worker stats, store as a dictionary + core_worker_stats = [] + for raylet in state.node_table(): + if not raylet["Alive"]: + continue + try: + stats = node_stats_to_dict( + node_stats(raylet["NodeManagerAddress"], raylet["NodeManagerPort"]) + ) + except RuntimeError: + continue + core_worker_stats.extend(stats["coreWorkersStats"]) + assert type(stats) is dict and "coreWorkersStats" in stats + + # Build memory table with "group_by" and "sort_by" parameters + group_by, sort_by = get_group_by_type(group_by), get_sorting_type(sort_by) + memory_table = construct_memory_table( + core_worker_stats, group_by, sort_by + ).as_dict() + assert "summary" in memory_table and "group" in memory_table + + # Build memory summary + mem = "" + group_by, sort_by = group_by.name.lower().replace( + "_", " " + ), sort_by.name.lower().replace("_", " ") + summary_labels = [ + "Mem Used by Objects", + "Local References", + "Pinned", + "Used by task", + "Captured in Objects", + "Actor Handles", + ] + summary_string = "{:<19} {:<16} {:<12} {:<13} {:<19} {:<13}\n" + + object_ref_labels = [ + "IP Address", + "PID", + "Type", + "Call Site", + "Status", + "Attampt", + "Size", + "Reference Type", + "Object Ref", + ] + object_ref_string = "{:<13} | {:<8} | {:<7} | {:<9} \ +| {:<9} | {:<8} | {:<8} | {:<14} | {:<10}\n" + + if size > line_wrap_threshold and line_wrap: + object_ref_string = "{:<15} {:<5} {:<6} {:<22} {:<14} {:<8} {:<6} \ +{:<18} {:<56}\n" + + mem += f"Grouping by {group_by}...\ + Sorting by {sort_by}...\ + Display {num_entries if num_entries is not None else 'all'}\ +entries per group...\n\n\n" + + for key, group in memory_table["group"].items(): + # Group summary + summary = group["summary"] + ref_size = track_reference_size(group) + for k, v in summary.items(): + if k == "total_object_size": + summary[k] = str(v / units[unit]) + f" {unit}" + else: + summary[k] = str(v) + f", ({ref_size[k] / units[unit]} {unit})" + mem += f"--- Summary for {group_by}: {key} ---\n" + mem += summary_string.format(*summary_labels) + mem += summary_string.format(*summary.values()) + "\n" + + # Memory table per group + mem += f"--- Object references for {group_by}: {key} ---\n" + mem += object_ref_string.format(*object_ref_labels) + n = 1 # Counter for num entries per group + for entry in group["entries"]: + if num_entries is not None and n > num_entries: + break + entry["object_size"] = ( + str(entry["object_size"] / units[unit]) + f" {unit}" + if entry["object_size"] > -1 + else "?" + ) + num_lines = 1 + if size > line_wrap_threshold and line_wrap: + call_site_length = 22 + if len(entry["call_site"]) == 0: + entry["call_site"] = ["disabled"] + else: + entry["call_site"] = [ + entry["call_site"][i : i + call_site_length] + for i in range(0, len(entry["call_site"]), call_site_length) + ] + + task_status_length = 12 + entry["task_status"] = [ + entry["task_status"][i : i + task_status_length] + for i in range(0, len(entry["task_status"]), task_status_length) + ] + num_lines = max(len(entry["call_site"]), len(entry["task_status"])) + + else: + mem += "\n" + object_ref_values = [ + entry["node_ip_address"], + entry["pid"], + entry["type"], + entry["call_site"], + entry["task_status"], + entry["attempt_number"], + entry["object_size"], + entry["reference_type"], + entry["object_ref"], + ] + for i in range(len(object_ref_values)): + if not isinstance(object_ref_values[i], list): + object_ref_values[i] = [object_ref_values[i]] + object_ref_values[i].extend( + ["" for x in range(num_lines - len(object_ref_values[i]))] + ) + for i in range(num_lines): + row = [elem[i] for elem in object_ref_values] + mem += object_ref_string.format(*row) + mem += "\n" + n += 1 + + mem += ( + "To record callsite information for each ObjectRef created, set " + "env variable RAY_record_ref_creation_sites=1\n\n" + ) + + return mem diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/__init__.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__init__.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b64254709d13db130b878c912e709e1ee56f1078 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/actor_consts.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/actor_consts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fb9509ce657dfe77cb42dfb989bca252acbbd98 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/actor_consts.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/actor_head.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/actor_head.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f100b674eced28c0359fc5f8dab2f149905fe3d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/actor_head.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/actor_consts.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/actor_consts.py new file mode 100644 index 0000000000000000000000000000000000000000..ffb3b98d575eb13b2ed062f8d9a1a9b26f3cdd6d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/actor_consts.py @@ -0,0 +1,5 @@ +import ray + +ACTOR_CHANNEL = "ACTOR" +NIL_NODE_ID = ray.NodeID.nil().hex() +RETRY_GET_ALL_ACTOR_INFO_INTERVAL_SECONDS = 1 diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/actor_head.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/actor_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2489eefc251894c1bcdb2ed6bda8399735dcd831 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/actor_head.py @@ -0,0 +1,356 @@ +import abc +import asyncio +import logging +import os +from collections import defaultdict, deque +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Dict, Optional + +import aiohttp.web + +import ray +import ray.dashboard.optional_utils as dashboard_optional_utils +import ray.dashboard.utils as dashboard_utils +from ray import ActorID +from ray._private.gcs_pubsub import GcsAioActorSubscriber +from ray._private.utils import get_or_create_event_loop +from ray.core.generated import gcs_pb2, gcs_service_pb2, gcs_service_pb2_grpc +from ray.dashboard.consts import GCS_RPC_TIMEOUT_SECONDS +from ray.dashboard.datacenter import DataOrganizer, DataSource +from ray.dashboard.modules.actor import actor_consts + +logger = logging.getLogger(__name__) +routes = dashboard_optional_utils.DashboardHeadRouteTable + +MAX_DESTROYED_ACTORS_TO_CACHE = max( + 0, ray._config.maximum_gcs_destroyed_actor_cached_count() +) + +ACTOR_CLEANUP_FREQUENCY = 1 # seconds + + +ACTOR_TABLE_STATE_COLUMNS = ( + "state", + "address", + "numRestarts", + "timestamp", + "pid", + "exitDetail", + "startTime", + "endTime", + "reprName", +) + + +def actor_table_data_to_dict(message): + orig_message = dashboard_utils.message_to_dict( + message, + { + "actorId", + "parentId", + "jobId", + "workerId", + "rayletId", + "callerId", + "taskId", + "parentTaskId", + "sourceActorId", + "placementGroupId", + }, + always_print_fields_with_no_presence=True, + ) + # The complete schema for actor table is here: + # src/ray/protobuf/gcs.proto + # It is super big and for dashboard, we don't need that much information. + # Only preserve the necessary ones here for memory usage. + fields = { + "actorId", + "jobId", + "pid", + "address", + "state", + "name", + "numRestarts", + "timestamp", + "className", + "startTime", + "endTime", + "reprName", + "placementGroupId", + } + light_message = {k: v for (k, v) in orig_message.items() if k in fields} + light_message["actorClass"] = orig_message["className"] + exit_detail = "-" + if "deathCause" in orig_message: + context = orig_message["deathCause"] + if "actorDiedErrorContext" in context: + exit_detail = context["actorDiedErrorContext"]["errorMessage"] # noqa + elif "runtimeEnvFailedContext" in context: + exit_detail = context["runtimeEnvFailedContext"]["errorMessage"] # noqa + elif "actorUnschedulableContext" in context: + exit_detail = context["actorUnschedulableContext"]["errorMessage"] # noqa + elif "creationTaskFailureContext" in context: + exit_detail = context["creationTaskFailureContext"][ + "formattedExceptionString" + ] # noqa + light_message["exitDetail"] = exit_detail + light_message["startTime"] = int(light_message["startTime"]) + light_message["endTime"] = int(light_message["endTime"]) + light_message["requiredResources"] = dict(message.required_resources) + + return light_message + + +class GetAllActorInfoClient(abc.ABC): + """ + Gets all actor info from GCS via gRPC ActorInfoGcsService.GetAllActorInfo. + It makes the call via GcsAioClient or a direct gRPC stub, depends on the env var + RAY_USE_OLD_GCS_CLIENT. + """ + + @classmethod + def create(cls, *args, **kwargs): + use_old_client = os.getenv("RAY_USE_OLD_GCS_CLIENT") == "1" + if use_old_client: + return GetAllActorInfoFromGrpc(*args, **kwargs) + else: + return GetAllActorInfoFromNewGcsClient(*args, **kwargs) + + @abc.abstractmethod + def __call__(self, *, timeout_s: int, state: Optional[str] = None): + pass + + +class GetAllActorInfoFromNewGcsClient(GetAllActorInfoClient): + def __init__(self, dashboard_head): + self.gcs_aio_client = dashboard_head.gcs_aio_client + + async def __call__( + self, *, timeout, state: Optional[str] = None + ) -> Dict[ActorID, gcs_pb2.ActorTableData]: + return await self.gcs_aio_client.get_all_actor_info( + timeout=timeout, actor_state_name=state + ) + + +class GetAllActorInfoFromGrpc(GetAllActorInfoClient): + def __init__(self, dashboard_head): + gcs_channel = dashboard_head.aiogrpc_gcs_channel + self._gcs_actor_info_stub = gcs_service_pb2_grpc.ActorInfoGcsServiceStub( + gcs_channel + ) + + async def __call__( + self, *, timeout, state: Optional[str] = None + ) -> Dict[ActorID, gcs_pb2.ActorTableData]: + request = gcs_service_pb2.GetAllActorInfoRequest() + + reply = await self._gcs_actor_info_stub.GetAllActorInfo( + request, + timeout=timeout, + filters=gcs_service_pb2.GetAllActorInfoRequest.Filters(state=state) + if state + else None, + ) + + if reply.status.code != 0: + raise Exception(f"Failed to GetAllActorInfo: {reply.status.message}") + + return { + ActorID(message.actor_id): message for message in reply.actor_table_data + } + + +class ActorHead(dashboard_utils.DashboardHeadModule): + def __init__(self, dashboard_head): + super().__init__(dashboard_head) + + self._gcs_actor_channel_subscriber = None + self.get_all_actor_info_client = None + # A queue of dead actors in order of when they died + self.destroyed_actors_queue = deque() + + # -- Internal state -- + self._loop = get_or_create_event_loop() + # NOTE: This executor is intentionally constrained to just 1 thread to + # limit its concurrency, therefore reducing potential for GIL contention + self._executor = ThreadPoolExecutor( + max_workers=1, thread_name_prefix="actor_head_executor" + ) + + async def _update_actors(self): + """ + Processes actor info. First gets all actors from GCS, then subscribes to + actor updates. For each actor update, updates DataSource.node_actors and + DataSource.actors. + """ + + # To prevent Time-of-check to time-of-use issue [1], the get-all-actor-info + # happens after the subscription. That is, an update between get-all-actor-info + # and the subscription is not missed. + # + # [1] https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use + gcs_addr = self._dashboard_head.gcs_address + actor_channel_subscriber = GcsAioActorSubscriber(address=gcs_addr) + await actor_channel_subscriber.subscribe() + + # Get all actor info. + while True: + try: + logger.info("Getting all actor info from GCS.") + + actor_dicts = await self._get_all_actors() + # Update actors + DataSource.actors.reset(actor_dicts) + + # Update node actors and job actors. + node_actors = defaultdict(dict) + for actor_id_bytes, updated_actor_table in actor_dicts.items(): + node_id = updated_actor_table["address"]["rayletId"] + # Update only when node_id is not Nil. + if node_id != actor_consts.NIL_NODE_ID: + node_actors[node_id][actor_id_bytes] = updated_actor_table + + # Update node's actor info + DataSource.node_actors.reset(node_actors) + + logger.info("Received %d actor info from GCS.", len(actor_dicts)) + + # Break, once all initial actors are successfully fetched + break + except Exception as e: + logger.exception("Error Getting all actor info from GCS", exc_info=e) + await asyncio.sleep( + actor_consts.RETRY_GET_ALL_ACTOR_INFO_INTERVAL_SECONDS + ) + + # Pull incremental updates from the GCS channel + while True: + try: + updated_actor_table_entries = await self._poll_updated_actor_table_data( + actor_channel_subscriber + ) + + for ( + actor_id, + updated_actor_table, + ) in updated_actor_table_entries.items(): + self._process_updated_actor_table(actor_id, updated_actor_table) + + # TODO emit metrics + logger.debug( + f"Total events processed: {len(updated_actor_table_entries)}, " + f"queue size: {actor_channel_subscriber.queue_size}" + ) + + except Exception as e: + logger.exception("Error processing actor info from GCS.", exc_info=e) + + async def _poll_updated_actor_table_data( + self, actor_channel_subscriber: GcsAioActorSubscriber + ) -> Dict[str, Dict[str, Any]]: + # TODO make batch size configurable + batch = await actor_channel_subscriber.poll(batch_size=200) + + # NOTE: We're offloading conversion to a TPE to make sure we're not + # blocking the event-loop for prolonged period of time irrespective + # of the batch size + def _convert_to_dict(): + return { + actor_id_bytes.hex(): actor_table_data_to_dict(actor_table_data_message) + for actor_id_bytes, actor_table_data_message in batch + if actor_id_bytes is not None + } + + return await self._loop.run_in_executor(self._executor, _convert_to_dict) + + def _process_updated_actor_table( + self, actor_id: str, actor_table_data: Dict[str, Any] + ): + """NOTE: This method has to be executed on the event-loop, provided that it accesses + DataSource data structures (to follow its thread-safety model)""" + + # If actor is not new registered but updated, we only update + # states related fields. + actor = DataSource.actors.get(actor_id) + + if actor and actor_table_data["state"] != "DEPENDENCIES_UNREADY": + for k in ACTOR_TABLE_STATE_COLUMNS: + if k in actor_table_data: + actor[k] = actor_table_data[k] + actor_table_data = actor + + actor_id = actor_table_data["actorId"] + node_id = actor_table_data["address"]["rayletId"] + + if actor_table_data["state"] == "DEAD": + self.destroyed_actors_queue.append(actor_id) + + # Update actors. + DataSource.actors[actor_id] = actor_table_data + # Update node actors (only when node_id is not Nil). + if node_id != actor_consts.NIL_NODE_ID: + node_actors = DataSource.node_actors.get(node_id, {}) + node_actors[actor_id] = actor_table_data + DataSource.node_actors[node_id] = node_actors + + async def _get_all_actors(self) -> Dict[str, dict]: + actors = await self.get_all_actor_info_client(timeout=GCS_RPC_TIMEOUT_SECONDS) + + # NOTE: We're offloading conversion to a TPE to make sure we're not + # blocking the event-loop for prolonged period of time for large clusters + def _convert_to_dict(): + return { + actor_id.hex(): actor_table_data_to_dict(actor_table_data) + for actor_id, actor_table_data in actors.items() + } + + return await self._loop.run_in_executor(self._executor, _convert_to_dict) + + async def _cleanup_actors(self): + while True: + try: + while len(self.destroyed_actors_queue) > MAX_DESTROYED_ACTORS_TO_CACHE: + actor_id = self.destroyed_actors_queue.popleft() + if actor_id in DataSource.actors: + actor = DataSource.actors.pop(actor_id) + node_id = actor["address"].get("rayletId") + if node_id and node_id != actor_consts.NIL_NODE_ID: + del DataSource.node_actors[node_id][actor_id] + await asyncio.sleep(ACTOR_CLEANUP_FREQUENCY) + except Exception: + logger.exception("Error cleaning up actor info from GCS.") + + @routes.get("/logical/actors") + @dashboard_optional_utils.aiohttp_cache + async def get_all_actors(self, req) -> aiohttp.web.Response: + actors = await DataOrganizer.get_actor_infos() + return dashboard_optional_utils.rest_response( + success=True, + message="All actors fetched.", + actors=actors, + # False to avoid converting Ray resource name to google style. + # It's not necessary here because the fields are already + # google formatted when protobuf was converted into dict. + convert_google_style=False, + ) + + @routes.get("/logical/actors/{actor_id}") + @dashboard_optional_utils.aiohttp_cache + async def get_actor(self, req) -> aiohttp.web.Response: + actor_id = req.match_info.get("actor_id") + actors = await DataOrganizer.get_actor_infos(actor_ids=[actor_id]) + return dashboard_optional_utils.rest_response( + success=True, message="Actor details fetched.", detail=actors[actor_id] + ) + + async def run(self, server): + self.get_all_actor_info_client = GetAllActorInfoClient.create( + self._dashboard_head + ) + + await asyncio.gather(self._update_actors(), self._cleanup_actors()) + + @staticmethod + def is_minimal_module(): + return False diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/dashboard_sdk.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/dashboard_sdk.py new file mode 100644 index 0000000000000000000000000000000000000000..6b0dfdaadab7b27f2780deb10064bc4fb2485768 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/dashboard_sdk.py @@ -0,0 +1,418 @@ +import dataclasses +import importlib +import json +import logging +import os +import ssl +import tempfile +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +import packaging.version +import yaml + +import ray +from ray._private.runtime_env.packaging import ( + create_package, + get_uri_for_directory, + get_uri_for_package, +) +from ray._private.runtime_env.py_modules import upload_py_modules_if_needed +from ray._private.runtime_env.working_dir import upload_working_dir_if_needed +from ray._private.utils import split_address +from ray.autoscaler._private.cli_logger import cli_logger +from ray.dashboard.modules.job.common import uri_to_http_components +from ray.util.annotations import DeveloperAPI, PublicAPI + +try: + import requests +except ImportError: + requests = None + + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +# By default, connect to local cluster. +DEFAULT_DASHBOARD_ADDRESS = "http://localhost:8265" + + +def parse_runtime_env_args( + runtime_env: Optional[str] = None, + runtime_env_json: Optional[str] = None, + working_dir: Optional[str] = None, +): + """ + Generates a runtime_env dictionary using `runtime_env`, `runtime_env_json`, + and `working_dir` CLI options. Only one of `runtime_env` or + `runtime_env_json` may be defined. `working_dir` overwrites the + `working_dir` from any other option. + """ + + final_runtime_env = {} + if runtime_env is not None: + if runtime_env_json is not None: + raise ValueError( + "Only one of --runtime_env and --runtime-env-json can be provided." + ) + with open(runtime_env, "r") as f: + final_runtime_env = yaml.safe_load(f) + + elif runtime_env_json is not None: + final_runtime_env = json.loads(runtime_env_json) + + if working_dir is not None: + if "working_dir" in final_runtime_env: + cli_logger.warning( + "Overriding runtime_env working_dir with --working-dir option" + ) + + final_runtime_env["working_dir"] = working_dir + + return final_runtime_env + + +@dataclasses.dataclass +class ClusterInfo: + address: str + cookies: Optional[Dict[str, Any]] = None + metadata: Optional[Dict[str, Any]] = None + headers: Optional[Dict[str, Any]] = None + + +# TODO (shrekris-anyscale): renaming breaks compatibility, do NOT rename +def get_job_submission_client_cluster_info( + address: str, + # For backwards compatibility + *, + # only used in importlib case in parse_cluster_info, but needed + # in function signature. + create_cluster_if_needed: Optional[bool] = False, + cookies: Optional[Dict[str, Any]] = None, + metadata: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, Any]] = None, + _use_tls: Optional[bool] = False, +) -> ClusterInfo: + """Get address, cookies, and metadata used for SubmissionClient. + + If no port is specified in `address`, the Ray dashboard default will be + inserted. + + Args: + address: Address without the module prefix that is passed + to SubmissionClient. + create_cluster_if_needed: Indicates whether the cluster + of the address returned needs to be running. Ray doesn't + start a cluster before interacting with jobs, but other + implementations may do so. + + Returns: + ClusterInfo object consisting of address, cookies, and metadata + for SubmissionClient to use. + """ + + scheme = "https" if _use_tls else "http" + return ClusterInfo( + address=f"{scheme}://{address}", + cookies=cookies, + metadata=metadata, + headers=headers, + ) + + +def parse_cluster_info( + address: Optional[str] = None, + create_cluster_if_needed: bool = False, + cookies: Optional[Dict[str, Any]] = None, + metadata: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, Any]] = None, +) -> ClusterInfo: + """Create a cluster if needed and return its address, cookies, and metadata.""" + if address is None: + if ( + ray.is_initialized() + and ray._private.worker.global_worker.node.address_info["webui_url"] + is not None + ): + address = ( + "http://" + f"{ray._private.worker.global_worker.node.address_info['webui_url']}" + ) + logger.info( + f"No address provided but Ray is running; using address {address}." + ) + else: + logger.info( + f"No address provided, defaulting to {DEFAULT_DASHBOARD_ADDRESS}." + ) + address = DEFAULT_DASHBOARD_ADDRESS + + if address == "auto": + raise ValueError("Internal error: unexpected address 'auto'.") + + if "://" not in address: + # Default to HTTP. + logger.info( + "No scheme (e.g. 'http://') or module string (e.g. 'ray://') " + f"provided in address {address}, defaulting to HTTP." + ) + address = f"http://{address}" + + module_string, inner_address = split_address(address) + + if module_string == "ray": + raise ValueError(f"Internal error: unexpected Ray Client address {address}.") + # If user passes http(s)://, go through normal parsing. + if module_string in {"http", "https"}: + return get_job_submission_client_cluster_info( + inner_address, + create_cluster_if_needed=create_cluster_if_needed, + cookies=cookies, + metadata=metadata, + headers=headers, + _use_tls=(module_string == "https"), + ) + # Try to dynamically import the function to get cluster info. + else: + try: + module = importlib.import_module(module_string) + except Exception: + raise RuntimeError( + f"Module: {module_string} does not exist.\n" + f"This module was parsed from address: {address}" + ) from None + assert "get_job_submission_client_cluster_info" in dir(module), ( + f"Module: {module_string} does " + "not have `get_job_submission_client_cluster_info`.\n" + f"This module was parsed from address: {address}" + ) + + return module.get_job_submission_client_cluster_info( + inner_address, + create_cluster_if_needed=create_cluster_if_needed, + cookies=cookies, + metadata=metadata, + headers=headers, + ) + + +class SubmissionClient: + def __init__( + self, + address: Optional[str] = None, + create_cluster_if_needed: bool = False, + cookies: Optional[Dict[str, Any]] = None, + metadata: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, Any]] = None, + verify: Optional[Union[str, bool]] = True, + ): + # Remove any trailing slashes + if address is not None and address.endswith("/"): + address = address.rstrip("/") + logger.debug( + "The submission address cannot contain trailing slashes. Removing " + f'them from the requested submission address of "{address}".' + ) + + cluster_info = parse_cluster_info( + address, create_cluster_if_needed, cookies, metadata, headers + ) + self._address = cluster_info.address + self._cookies = cluster_info.cookies + self._default_metadata = cluster_info.metadata or {} + # Headers used for all requests sent to job server, optional and only + # needed for cases like authentication to remote cluster. + self._headers = cluster_info.headers + # Set SSL verify parameter for the requests library and create an ssl_context + # object when needed for the aiohttp library. + self._verify = verify + if isinstance(self._verify, str): + if os.path.isdir(self._verify): + cafile, capath = None, self._verify + elif os.path.isfile(self._verify): + cafile, capath = self._verify, None + else: + raise FileNotFoundError( + f"Path to CA certificates: '{self._verify}', does not exist." + ) + self._ssl_context = ssl.create_default_context(cafile=cafile, capath=capath) + else: + if self._verify is False: + self._ssl_context = False + else: + self._ssl_context = None + + def _check_connection_and_version( + self, min_version: str = "1.9", version_error_message: str = None + ): + self._check_connection_and_version_with_url(min_version, version_error_message) + + def _check_connection_and_version_with_url( + self, + min_version: str = "1.9", + version_error_message: str = None, + url: str = "/api/version", + ): + if version_error_message is None: + version_error_message = ( + f"Please ensure the cluster is running Ray {min_version} or higher." + ) + + try: + r = self._do_request("GET", url) + if r.status_code == 404: + raise RuntimeError( + "Version check returned 404. " + version_error_message + ) + r.raise_for_status() + + running_ray_version = r.json()["ray_version"] + if packaging.version.parse(running_ray_version) < packaging.version.parse( + min_version + ): + raise RuntimeError( + f"Ray version {running_ray_version} is running on the cluster. " + + version_error_message + ) + except requests.exceptions.ConnectionError: + raise ConnectionError( + f"Failed to connect to Ray at address: {self._address}." + ) + + def _raise_error(self, r: "requests.Response"): + raise RuntimeError( + f"Request failed with status code {r.status_code}: {r.text}." + ) + + def _do_request( + self, + method: str, + endpoint: str, + *, + data: Optional[bytes] = None, + json_data: Optional[dict] = None, + **kwargs, + ) -> "requests.Response": + """Perform the actual HTTP request + + Keyword arguments other than "cookies", "headers" are forwarded to the + `requests.request()`. + """ + url = self._address + endpoint + logger.debug(f"Sending request to {url} with json data: {json_data or {}}.") + return requests.request( + method, + url, + cookies=self._cookies, + data=data, + json=json_data, + headers=self._headers, + verify=self._verify, + **kwargs, + ) + + def _package_exists( + self, + package_uri: str, + ) -> bool: + protocol, package_name = uri_to_http_components(package_uri) + r = self._do_request("GET", f"/api/packages/{protocol}/{package_name}") + + if r.status_code == 200: + logger.debug(f"Package {package_uri} already exists.") + return True + elif r.status_code == 404: + logger.debug(f"Package {package_uri} does not exist.") + return False + else: + self._raise_error(r) + + def _upload_package( + self, + package_uri: str, + package_path: str, + include_parent_dir: Optional[bool] = False, + excludes: Optional[List[str]] = None, + is_file: bool = False, + ) -> bool: + logger.info(f"Uploading package {package_uri}.") + with tempfile.TemporaryDirectory() as tmp_dir: + protocol, package_name = uri_to_http_components(package_uri) + if is_file: + package_file = Path(package_path) + else: + package_file = Path(tmp_dir) / package_name + create_package( + package_path, + package_file, + include_parent_dir=include_parent_dir, + excludes=excludes, + ) + try: + r = self._do_request( + "PUT", + f"/api/packages/{protocol}/{package_name}", + data=package_file.read_bytes(), + ) + if r.status_code != 200: + self._raise_error(r) + finally: + # If the package is a user's existing file, don't delete it. + if not is_file: + package_file.unlink() + + def _upload_package_if_needed( + self, + package_path: str, + include_parent_dir: bool = False, + excludes: Optional[List[str]] = None, + is_file: bool = False, + ) -> str: + if is_file: + package_uri = get_uri_for_package(Path(package_path)) + else: + package_uri = get_uri_for_directory(package_path, excludes=excludes) + + if not self._package_exists(package_uri): + self._upload_package( + package_uri, + package_path, + include_parent_dir=include_parent_dir, + excludes=excludes, + is_file=is_file, + ) + else: + logger.info(f"Package {package_uri} already exists, skipping upload.") + + return package_uri + + def _upload_working_dir_if_needed(self, runtime_env: Dict[str, Any]): + def _upload_fn(working_dir, excludes, is_file=False): + self._upload_package_if_needed( + working_dir, + include_parent_dir=False, + excludes=excludes, + is_file=is_file, + ) + + upload_working_dir_if_needed(runtime_env, upload_fn=_upload_fn) + + def _upload_py_modules_if_needed(self, runtime_env: Dict[str, Any]): + def _upload_fn(module_path, excludes, is_file=False): + self._upload_package_if_needed( + module_path, include_parent_dir=True, excludes=excludes, is_file=is_file + ) + + upload_py_modules_if_needed(runtime_env, upload_fn=_upload_fn) + + @PublicAPI(stability="beta") + def get_version(self) -> str: + r = self._do_request("GET", "/api/version") + if r.status_code == 200: + return r.json().get("version") + else: + self._raise_error(r) + + @DeveloperAPI + def get_address(self) -> str: + return self._address diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fe8c0ca7927cf5b536d2b819975132d4f6768c4 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/healthz_agent.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/healthz_agent.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..547554939fe7a829722892d10eab161f68c7512d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/healthz_agent.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/healthz_head.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/healthz_head.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c041a4b5bc0c0b992e754e683437f6b2d044e4a8 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/healthz_head.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/healthz_agent.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/healthz_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..f9483f14aea64ae998d4bbfa98cfbb879145afd0 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/healthz_agent.py @@ -0,0 +1,54 @@ +from aiohttp.web import Request, Response + +import ray.dashboard.optional_utils as optional_utils +import ray.dashboard.utils as dashboard_utils +import ray.exceptions +from ray.dashboard.modules.healthz.utils import HealthChecker + +routes = optional_utils.DashboardAgentRouteTable + + +class HealthzAgent(dashboard_utils.DashboardAgentModule): + """Health check in the agent. + + This module adds health check related endpoint to the agent to check + local components' health. + """ + + def __init__(self, dashboard_agent): + super().__init__(dashboard_agent) + self._health_checker = HealthChecker( + dashboard_agent.gcs_aio_client, + f"{dashboard_agent.ip}:{dashboard_agent.node_manager_port}", + ) + + @routes.get("/api/local_raylet_healthz") + async def health_check(self, req: Request) -> Response: + try: + alive = await self._health_checker.check_local_raylet_liveness() + if alive is False: + return Response(status=503, text="Local Raylet failed") + except ray.exceptions.RpcError as e: + # We only consider the error other than GCS unreachable as raylet failure + # to avoid false positive. + # In case of GCS failed, Raylet will crash eventually if GCS is not back + # within a given time and the check will fail since agent can't live + # without a local raylet. + if e.rpc_code not in ( + ray._raylet.GRPC_STATUS_CODE_UNAVAILABLE, + ray._raylet.GRPC_STATUS_CODE_UNKNOWN, + ray._raylet.GRPC_STATUS_CODE_DEADLINE_EXCEEDED, + ): + return Response(status=503, text=f"Health check failed due to: {e}") + + return Response( + text="success", + content_type="application/text", + ) + + async def run(self, server): + pass + + @staticmethod + def is_minimal_module(): + return False diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/healthz_head.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/healthz_head.py new file mode 100644 index 0000000000000000000000000000000000000000..9e2ea23094bddde72b4941fe62a154e8a14789c2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/healthz_head.py @@ -0,0 +1,41 @@ +from aiohttp.web import HTTPServiceUnavailable, Request, Response + +import ray.dashboard.optional_utils as optional_utils +import ray.dashboard.utils as dashboard_utils +from ray.dashboard.modules.healthz.utils import HealthChecker + +routes = optional_utils.DashboardHeadRouteTable + + +class HealthzHead(dashboard_utils.DashboardHeadModule): + """Health check in the head. + + This module adds health check related endpoint to the head to check + GCS's heath. + """ + + def __init__(self, dashboard_head): + super().__init__(dashboard_head) + self._health_checker = HealthChecker(dashboard_head.gcs_aio_client) + + @routes.get("/api/gcs_healthz") + async def health_check(self, req: Request) -> Response: + alive = False + try: + alive = await self._health_checker.check_gcs_liveness() + if alive is True: + return Response( + text="success", + content_type="application/text", + ) + except Exception as e: + return HTTPServiceUnavailable(reason=f"Health check failed: {e}") + + return HTTPServiceUnavailable(reason="Health check failed") + + async def run(self, server): + pass + + @staticmethod + def is_minimal_module(): + return True diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/utils.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4941c22e6e714d2086d1238070b17636688e39df --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/utils.py @@ -0,0 +1,24 @@ +from typing import Optional + +from ray._private.gcs_utils import GcsAioClient + + +class HealthChecker: + def __init__( + self, gcs_aio_client: GcsAioClient, local_node_address: Optional[str] = None + ): + self._gcs_aio_client = gcs_aio_client + self._local_node_address = local_node_address + + async def check_local_raylet_liveness(self) -> bool: + if self._local_node_address is None: + return False + + liveness = await self._gcs_aio_client.check_alive( + [self._local_node_address.encode()], 0.1 + ) + return liveness[0] + + async def check_gcs_liveness(self) -> bool: + await self._gcs_aio_client.check_alive([], 0.1) + return True diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/job/__init__.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/job/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/node/__init__.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/node/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__init__.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/profile_manager.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/profile_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c54c8a1291f428386411a39cdc6a6a7c026c252 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/profile_manager.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_agent.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_agent.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb24910af3b3e8b4690752ca69d717607bab6cfe Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_agent.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_consts.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_consts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83e5ae2aace86fe1c96f9c21d20f829dabe4ec21 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_consts.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_head.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_head.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80f1690280ccb7a31af18b69c112194cd422b2f7 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_head.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_agent.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..af5362885b242c8acfd32f61326a91b987cbf113 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_agent.py @@ -0,0 +1,1305 @@ +import asyncio +import datetime +import json +import logging +import os +import socket +import sys +import traceback +from collections import defaultdict +from concurrent.futures import ThreadPoolExecutor +from typing import List, Optional, Tuple, TypedDict, Union + +from opencensus.stats import stats as stats_module +from prometheus_client.core import REGISTRY + +import ray +import ray._private.prometheus_exporter as prometheus_exporter +import ray._private.services +import ray._private.utils +import ray.dashboard.modules.reporter.reporter_consts as reporter_consts +import ray.dashboard.utils as dashboard_utils +from ray._private import utils +from ray._private.metrics_agent import Gauge, MetricsAgent, Record +from ray._private.ray_constants import DEBUG_AUTOSCALING_STATUS, env_integer +from ray._raylet import WorkerID +from ray.core.generated import reporter_pb2, reporter_pb2_grpc +from ray.dashboard import k8s_utils +from ray.dashboard.consts import ( + CLUSTER_TAG_KEYS, + COMPONENT_METRICS_TAG_KEYS, + GCS_RPC_TIMEOUT_SECONDS, + GPU_TAG_KEYS, + NODE_TAG_KEYS, +) +from ray.dashboard.modules.reporter.profile_manager import ( + CpuProfilingManager, + MemoryProfilingManager, +) + +import psutil + +logger = logging.getLogger(__name__) + +enable_gpu_usage_check = True + +# Are we in a K8s pod? +IN_KUBERNETES_POD = "KUBERNETES_SERVICE_HOST" in os.environ +# Flag to enable showing disk usage when running in a K8s pod, +# disk usage defined as the result of running psutil.disk_usage("/") +# in the Ray container. +ENABLE_K8S_DISK_USAGE = os.environ.get("RAY_DASHBOARD_ENABLE_K8S_DISK_USAGE") == "1" +# Try to determine if we're in a container. +IN_CONTAINER = os.path.exists("/sys/fs/cgroup") +# Using existence of /sys/fs/cgroup as the criterion is consistent with +# Ray's existing resource logic, see e.g. ray._private.utils.get_num_cpus(). + +# NOTE: Executor in this head is intentionally constrained to just 1 thread by +# default to limit its concurrency, therefore reducing potential for +# GIL contention +RAY_DASHBOARD_REPORTER_AGENT_TPE_MAX_WORKERS = env_integer( + "RAY_DASHBOARD_REPORTER_AGENT_TPE_MAX_WORKERS", 1 +) + + +def recursive_asdict(o): + if isinstance(o, tuple) and hasattr(o, "_asdict"): + return recursive_asdict(o._asdict()) + + if isinstance(o, (tuple, list)): + L = [] + for k in o: + L.append(recursive_asdict(k)) + return L + + if isinstance(o, dict): + D = {k: recursive_asdict(v) for k, v in o.items()} + return D + + return o + + +def jsonify_asdict(o) -> str: + return json.dumps(dashboard_utils.to_google_style(recursive_asdict(o))) + + +# A list of gauges to record and export metrics. +METRICS_GAUGES = { + # CPU metrics + "node_cpu_utilization": Gauge( + "node_cpu_utilization", + "Total CPU usage on a ray node", + "percentage", + NODE_TAG_KEYS, + ), + "node_cpu_count": Gauge( + "node_cpu_count", + "Total CPUs available on a ray node", + "cores", + NODE_TAG_KEYS, + ), + # Memory metrics + "node_mem_used": Gauge( + "node_mem_used", + "Memory usage on a ray node", + "bytes", + NODE_TAG_KEYS, + ), + "node_mem_available": Gauge( + "node_mem_available", + "Memory available on a ray node", + "bytes", + NODE_TAG_KEYS, + ), + "node_mem_total": Gauge( + "node_mem_total", + "Total memory on a ray node", + "bytes", + NODE_TAG_KEYS, + ), + "node_mem_shared_bytes": Gauge( + "node_mem_shared_bytes", + "Total shared memory usage on a ray node", + "bytes", + NODE_TAG_KEYS, + ), + # GPU metrics + "node_gpus_available": Gauge( + "node_gpus_available", + "Total GPUs available on a ray node", + "percentage", + GPU_TAG_KEYS, + ), + "node_gpus_utilization": Gauge( + "node_gpus_utilization", + "Total GPUs usage on a ray node", + "percentage", + GPU_TAG_KEYS, + ), + "node_gram_used": Gauge( + "node_gram_used", + "Total GPU RAM usage on a ray node", + "bytes", + GPU_TAG_KEYS, + ), + "node_gram_available": Gauge( + "node_gram_available", + "Total GPU RAM available on a ray node", + "bytes", + GPU_TAG_KEYS, + ), + # Disk I/O metrics + "node_disk_io_read": Gauge( + "node_disk_io_read", + "Total read from disk", + "bytes", + NODE_TAG_KEYS, + ), + "node_disk_io_write": Gauge( + "node_disk_io_write", + "Total written to disk", + "bytes", + NODE_TAG_KEYS, + ), + "node_disk_io_read_count": Gauge( + "node_disk_io_read_count", + "Total read ops from disk", + "io", + NODE_TAG_KEYS, + ), + "node_disk_io_write_count": Gauge( + "node_disk_io_write_count", + "Total write ops to disk", + "io", + NODE_TAG_KEYS, + ), + "node_disk_io_read_speed": Gauge( + "node_disk_io_read_speed", + "Disk read speed", + "bytes/sec", + NODE_TAG_KEYS, + ), + "node_disk_io_write_speed": Gauge( + "node_disk_io_write_speed", + "Disk write speed", + "bytes/sec", + NODE_TAG_KEYS, + ), + "node_disk_read_iops": Gauge( + "node_disk_read_iops", + "Disk read iops", + "iops", + NODE_TAG_KEYS, + ), + "node_disk_write_iops": Gauge( + "node_disk_write_iops", + "Disk write iops", + "iops", + NODE_TAG_KEYS, + ), + # Disk usage metrics + "node_disk_usage": Gauge( + "node_disk_usage", + "Total disk usage (bytes) on a ray node", + "bytes", + NODE_TAG_KEYS, + ), + "node_disk_free": Gauge( + "node_disk_free", + "Total disk free (bytes) on a ray node", + "bytes", + NODE_TAG_KEYS, + ), + "node_disk_utilization_percentage": Gauge( + "node_disk_utilization_percentage", + "Total disk utilization (percentage) on a ray node", + "percentage", + NODE_TAG_KEYS, + ), + # Network metrics + "node_network_sent": Gauge( + "node_network_sent", + "Total network sent", + "bytes", + NODE_TAG_KEYS, + ), + "node_network_received": Gauge( + "node_network_received", + "Total network received", + "bytes", + NODE_TAG_KEYS, + ), + "node_network_send_speed": Gauge( + "node_network_send_speed", + "Network send speed", + "bytes/sec", + NODE_TAG_KEYS, + ), + "node_network_receive_speed": Gauge( + "node_network_receive_speed", + "Network receive speed", + "bytes/sec", + NODE_TAG_KEYS, + ), + # Component metrics + "component_cpu_percentage": Gauge( + "component_cpu_percentage", + "Total CPU usage of the components on a node.", + "percentage", + COMPONENT_METRICS_TAG_KEYS, + ), + "component_mem_shared_bytes": Gauge( + "component_mem_shared_bytes", + "SHM usage of all components of the node. " + "It is equivalent to the top command's SHR column.", + "bytes", + COMPONENT_METRICS_TAG_KEYS, + ), + "component_rss_mb": Gauge( + "component_rss_mb", + "RSS usage of all components on the node.", + "MB", + COMPONENT_METRICS_TAG_KEYS, + ), + "component_uss_mb": Gauge( + "component_uss_mb", + "USS usage of all components on the node.", + "MB", + COMPONENT_METRICS_TAG_KEYS, + ), + "component_num_fds": Gauge( + "component_num_fds", + "Number of open fds of all components on the node (Not available on Windows).", + "count", + COMPONENT_METRICS_TAG_KEYS, + ), + # Cluster metrics + "cluster_active_nodes": Gauge( + "cluster_active_nodes", + "Active nodes on the cluster", + "count", + CLUSTER_TAG_KEYS, + ), + "cluster_failed_nodes": Gauge( + "cluster_failed_nodes", + "Failed nodes on the cluster", + "count", + CLUSTER_TAG_KEYS, + ), + "cluster_pending_nodes": Gauge( + "cluster_pending_nodes", + "Pending nodes on the cluster", + "count", + CLUSTER_TAG_KEYS, + ), +} + +PSUTIL_PROCESS_ATTRS = ( + [ + "pid", + "create_time", + "cpu_percent", + "cpu_times", + "cmdline", + "memory_info", + "memory_full_info", + ] + + ["num_fds"] + if sys.platform != "win32" + else [] +) + +MB = 1024 * 1024 + +# Types +Percentage = int +Megabytes = int + + +# gpu utilization for nvidia gpu from a single process +class ProcessGPUInfo(TypedDict): + pid: int + gpu_memory_usage: Megabytes + + +# gpu utilization for nvidia gpu +class GpuUtilizationInfo(TypedDict): + index: int + name: str + uuid: str + utilization_gpu: Optional[Percentage] + memory_used: Megabytes + memory_total: Megabytes + processes_pids: Optional[List[ProcessGPUInfo]] + + +class ReporterAgent( + dashboard_utils.DashboardAgentModule, reporter_pb2_grpc.ReporterServiceServicer +): + """A monitor process for monitoring Ray nodes. + + Attributes: + dashboard_agent: The DashboardAgent object contains global config + """ + + def __init__(self, dashboard_agent): + """Initialize the reporter object.""" + super().__init__(dashboard_agent) + + if IN_KUBERNETES_POD or IN_CONTAINER: + # psutil does not give a meaningful logical cpu count when in a K8s pod, or + # in a container in general. + # Use ray._private.utils for this instead. + logical_cpu_count = ray._private.utils.get_num_cpus( + override_docker_cpu_warning=True + ) + # (Override the docker warning to avoid dashboard log spam.) + + # The dashboard expects a physical CPU count as well. + # This is not always meaningful in a container, but we will go ahead + # and give the dashboard what it wants using psutil. + physical_cpu_count = psutil.cpu_count(logical=False) + else: + logical_cpu_count = psutil.cpu_count() + physical_cpu_count = psutil.cpu_count(logical=False) + self._cpu_counts = (logical_cpu_count, physical_cpu_count) + self._gcs_aio_client = dashboard_agent.gcs_aio_client + self._ip = dashboard_agent.ip + self._log_dir = dashboard_agent.log_dir + self._is_head_node = self._ip == dashboard_agent.gcs_address.split(":")[0] + self._hostname = socket.gethostname() + # (pid, created_time) -> psutil.Process + self._workers = {} + # psutil.Process of the parent. + self._raylet_proc = None + # psutil.Process of the current process. + self._agent_proc = None + # The last reported worker proc names (e.g., ray::*). + self._latest_worker_proc_names = set() + self._network_stats_hist = [(0, (0.0, 0.0))] # time, (sent, recv) + self._disk_io_stats_hist = [ + (0, (0.0, 0.0, 0, 0)) + ] # time, (bytes read, bytes written, read ops, write ops) + self._metrics_collection_disabled = dashboard_agent.metrics_collection_disabled + self._metrics_agent = None + self._session_name = dashboard_agent.session_name + if not self._metrics_collection_disabled: + try: + stats_exporter = prometheus_exporter.new_stats_exporter( + prometheus_exporter.Options( + namespace="ray", + port=dashboard_agent.metrics_export_port, + address="127.0.0.1" if self._ip == "127.0.0.1" else "", + ) + ) + except Exception: + # TODO(SongGuyang): Catch the exception here because there is + # port conflict issue which brought from static port. We should + # remove this after we find better port resolution. + logger.exception( + "Failed to start prometheus stats exporter. Agent will stay " + "alive but disable the stats." + ) + stats_exporter = None + + self._metrics_agent = MetricsAgent( + stats_module.stats.view_manager, + stats_module.stats.stats_recorder, + stats_exporter, + ) + if self._metrics_agent.proxy_exporter_collector: + # proxy_exporter_collector is None + # if Prometheus server is not started. + REGISTRY.register(self._metrics_agent.proxy_exporter_collector) + self._key = ( + f"{reporter_consts.REPORTER_PREFIX}" f"{self._dashboard_agent.node_id}" + ) + + self._executor = ThreadPoolExecutor( + max_workers=RAY_DASHBOARD_REPORTER_AGENT_TPE_MAX_WORKERS, + thread_name_prefix="reporter_agent_executor", + ) + + async def GetTraceback(self, request, context): + pid = request.pid + native = request.native + p = CpuProfilingManager(self._log_dir) + success, output = await p.trace_dump(pid, native=native) + return reporter_pb2.GetTracebackReply(output=output, success=success) + + async def CpuProfiling(self, request, context): + pid = request.pid + duration = request.duration + format = request.format + native = request.native + p = CpuProfilingManager(self._log_dir) + success, output = await p.cpu_profile( + pid, format=format, duration=duration, native=native + ) + return reporter_pb2.CpuProfilingReply(output=output, success=success) + + async def MemoryProfiling(self, request, context): + pid = request.pid + format = request.format + leaks = request.leaks + duration = request.duration + native = request.native + trace_python_allocators = request.trace_python_allocators + p = MemoryProfilingManager(self._log_dir) + success, profiler_filename, output = await p.attach_profiler( + pid, native=native, trace_python_allocators=trace_python_allocators + ) + if not success: + return reporter_pb2.MemoryProfilingReply(output=output, success=success) + + # add 1 second sleep for memray overhead + await asyncio.sleep(duration + 1) + success, output = await p.detach_profiler(pid) + warning = None if success else output + success, output = await p.get_profile_result( + pid, profiler_filename=profiler_filename, format=format, leaks=leaks + ) + return reporter_pb2.MemoryProfilingReply( + output=output, success=success, warning=warning + ) + + async def ReportOCMetrics(self, request, context): + # Do nothing if metrics collection is disabled. + if self._metrics_collection_disabled: + return reporter_pb2.ReportOCMetricsReply() + + # This function receives a GRPC containing OpenCensus (OC) metrics + # from a Ray process, then exposes those metrics to Prometheus. + try: + worker_id = WorkerID(request.worker_id) + worker_id = None if worker_id.is_nil() else worker_id.hex() + self._metrics_agent.proxy_export_metrics(request.metrics, worker_id) + except Exception: + logger.error(traceback.format_exc()) + return reporter_pb2.ReportOCMetricsReply() + + @staticmethod + def _get_cpu_percent(in_k8s: bool): + if in_k8s: + return k8s_utils.cpu_percent() + else: + return psutil.cpu_percent() + + @staticmethod + def _get_gpu_usage(): + import ray._private.thirdparty.pynvml as pynvml + + global enable_gpu_usage_check + if not enable_gpu_usage_check: + return [] + gpu_utilizations = [] + + def decode(b: Union[str, bytes]) -> str: + if isinstance(b, bytes): + return b.decode("utf-8") # for python3, to unicode + return b + + try: + pynvml.nvmlInit() + except Exception as e: + logger.debug(f"pynvml failed to retrieve GPU information: {e}") + + # On machines without GPUs, pynvml.nvmlInit() can run subprocesses that + # spew to stderr. Then with log_to_driver=True, we get log spew from every + # single raylet. To avoid this, disable the GPU usage check on + # certain errors. + # https://github.com/ray-project/ray/issues/14305 + # https://github.com/ray-project/ray/pull/21686 + if type(e).__name__ == "NVMLError_DriverNotLoaded": + enable_gpu_usage_check = False + return gpu_utilizations + + num_gpus = pynvml.nvmlDeviceGetCount() + for i in range(num_gpus): + gpu_handle = pynvml.nvmlDeviceGetHandleByIndex(i) + memory_info = pynvml.nvmlDeviceGetMemoryInfo(gpu_handle) + utilization = None + try: + utilization_info = pynvml.nvmlDeviceGetUtilizationRates(gpu_handle) + utilization = int(utilization_info.gpu) + except pynvml.NVMLError as e: + logger.debug(f"pynvml failed to retrieve GPU utilization: {e}") + + # processes pids + processes_pids = None + try: + nv_comp_processes = pynvml.nvmlDeviceGetComputeRunningProcesses( + gpu_handle + ) + nv_graphics_processes = pynvml.nvmlDeviceGetGraphicsRunningProcesses( + gpu_handle + ) + processes_pids = [ + ProcessGPUInfo( + pid=int(nv_process.pid), + gpu_memory_usage=int(nv_process.usedGpuMemory) // MB + if nv_process.usedGpuMemory + else 0, + ) + for nv_process in (nv_comp_processes + nv_graphics_processes) + ] + except pynvml.NVMLError as e: + logger.debug(f"pynvml failed to retrieve GPU processes: {e}") + + info = GpuUtilizationInfo( + index=i, + name=decode(pynvml.nvmlDeviceGetName(gpu_handle)), + uuid=decode(pynvml.nvmlDeviceGetUUID(gpu_handle)), + utilization_gpu=utilization, + memory_used=int(memory_info.used) // MB, + memory_total=int(memory_info.total) // MB, + processes_pids=processes_pids, + ) + gpu_utilizations.append(info) + pynvml.nvmlShutdown() + + return gpu_utilizations + + @staticmethod + def _get_boot_time(): + if IN_KUBERNETES_POD: + # Return start time of container entrypoint + return psutil.Process(pid=1).create_time() + else: + return psutil.boot_time() + + @staticmethod + def _get_network_stats(): + ifaces = [ + v for k, v in psutil.net_io_counters(pernic=True).items() if k[0] == "e" + ] + + sent = sum((iface.bytes_sent for iface in ifaces)) + recv = sum((iface.bytes_recv for iface in ifaces)) + return sent, recv + + @staticmethod + def _get_mem_usage(): + total = ray._private.utils.get_system_memory() + used = ray._private.utils.get_used_memory() + available = total - used + percent = round(used / total, 3) * 100 + return total, available, percent, used + + @staticmethod + def _get_disk_usage(): + if IN_KUBERNETES_POD and not ENABLE_K8S_DISK_USAGE: + # If in a K8s pod, disable disk display by passing in dummy values. + return { + "/": psutil._common.sdiskusage(total=1, used=0, free=1, percent=0.0) + } + if sys.platform == "win32": + root = psutil.disk_partitions()[0].mountpoint + else: + root = os.sep + tmp = ray._private.utils.get_user_temp_dir() + return { + "/": psutil.disk_usage(root), + tmp: psutil.disk_usage(tmp), + } + + @staticmethod + def _get_disk_io_stats(): + stats = psutil.disk_io_counters() + # stats can be None or {} if the machine is diskless. + # https://psutil.readthedocs.io/en/latest/#psutil.disk_io_counters + if not stats: + return (0, 0, 0, 0) + else: + return ( + stats.read_bytes, + stats.write_bytes, + stats.read_count, + stats.write_count, + ) + + def _get_agent_proc(self) -> psutil.Process: + # Agent is the current process. + # This method is not necessary, but we have it for mock testing. + return psutil.Process() + + def _generate_worker_key(self, proc: psutil.Process) -> Tuple[int, float]: + return (proc.pid, proc.create_time()) + + def _get_workers(self): + raylet_proc = self._get_raylet_proc() + + if raylet_proc is None: + return [] + else: + workers = {} + if sys.platform == "win32": + # windows, get the child process not the runner + for child in raylet_proc.children(): + if child.children(): + child = child.children()[0] + workers[self._generate_worker_key(child)] = child + else: + workers = { + self._generate_worker_key(proc): proc + for proc in raylet_proc.children() + } + + # We should keep `raylet_proc.children()` in `self` because + # when `cpu_percent` is first called, it returns the meaningless 0. + # See more: https://github.com/ray-project/ray/issues/29848 + keys_to_pop = [] + # Add all new workers. + for key, worker in workers.items(): + if key not in self._workers: + self._workers[key] = worker + + # Pop out stale workers. + for key in self._workers: + if key not in workers: + keys_to_pop.append(key) + for k in keys_to_pop: + self._workers.pop(k) + + # Remove the current process (reporter agent), which is also a child of + # the Raylet. + self._workers.pop(self._generate_worker_key(self._get_agent_proc())) + + result = [] + for w in self._workers.values(): + try: + if w.status() == psutil.STATUS_ZOMBIE: + continue + except psutil.NoSuchProcess: + # the process may have terminated due to race condition. + continue + + result.append(w.as_dict(attrs=PSUTIL_PROCESS_ATTRS)) + return result + + def _get_raylet_proc(self): + try: + if not self._raylet_proc: + curr_proc = psutil.Process() + # The dashboard agent is a child of the raylet process. + # It is not necessarily the direct child (python-windows + # typically uses a py.exe runner to run python), so search + # up for a process named 'raylet' + candidate = curr_proc.parent() + while candidate: + if "raylet" in candidate.name(): + break + candidate = candidate.parent() + self._raylet_proc = candidate + + if self._raylet_proc is not None: + if self._raylet_proc.pid == 1: + return None + if self._raylet_proc.status() == psutil.STATUS_ZOMBIE: + return None + return self._raylet_proc + except (psutil.AccessDenied, ProcessLookupError): + pass + return None + + def _get_raylet(self): + raylet_proc = self._get_raylet_proc() + if raylet_proc is None: + return {} + else: + return raylet_proc.as_dict(attrs=PSUTIL_PROCESS_ATTRS) + + def _get_agent(self): + # Current proc == agent proc + if not self._agent_proc: + self._agent_proc = psutil.Process() + return self._agent_proc.as_dict(attrs=PSUTIL_PROCESS_ATTRS) + + def _get_load_avg(self): + if sys.platform == "win32": + cpu_percent = psutil.cpu_percent() + load = (cpu_percent, cpu_percent, cpu_percent) + else: + load = os.getloadavg() + if self._cpu_counts[0] > 0: + per_cpu_load = tuple((round(x / self._cpu_counts[0], 2) for x in load)) + else: + per_cpu_load = None + return load, per_cpu_load + + @staticmethod + def _compute_speed_from_hist(hist): + while len(hist) > 7: + hist.pop(0) + then, prev_stats = hist[0] + now, now_stats = hist[-1] + time_delta = now - then + return tuple((y - x) / time_delta for x, y in zip(prev_stats, now_stats)) + + def _get_shm_usage(self): + """Return the shm usage. + + If shm doesn't exist (e.g., MacOS), it returns None. + """ + mem = psutil.virtual_memory() + if not hasattr(mem, "shared"): + return None + return mem.shared + + def _collect_stats(self): + now = dashboard_utils.to_posix_time(datetime.datetime.utcnow()) + network_stats = self._get_network_stats() + self._network_stats_hist.append((now, network_stats)) + network_speed_stats = self._compute_speed_from_hist(self._network_stats_hist) + + disk_stats = self._get_disk_io_stats() + self._disk_io_stats_hist.append((now, disk_stats)) + disk_speed_stats = self._compute_speed_from_hist(self._disk_io_stats_hist) + + return { + "now": now, + "hostname": self._hostname, + "ip": self._ip, + "cpu": self._get_cpu_percent(IN_KUBERNETES_POD), + "cpus": self._cpu_counts, + "mem": self._get_mem_usage(), + # Unit is in bytes. None if + "shm": self._get_shm_usage(), + "workers": self._get_workers(), + "raylet": self._get_raylet(), + "agent": self._get_agent(), + "bootTime": self._get_boot_time(), + "loadAvg": self._get_load_avg(), + "disk": self._get_disk_usage(), + "disk_io": disk_stats, + "disk_io_speed": disk_speed_stats, + "gpus": self._get_gpu_usage(), + "network": network_stats, + "network_speed": network_speed_stats, + # Deprecated field, should be removed with frontend. + "cmdline": self._get_raylet().get("cmdline", []), + } + + def _generate_reseted_stats_record(self, component_name: str) -> List[Record]: + """Return a list of Record that will reset + the system metrics of a given component name. + + Args: + component_name: a component name for a given stats. + + Returns: + a list of Record instances of all values 0. + """ + tags = {"ip": self._ip, "Component": component_name} + + records = [] + records.append( + Record( + gauge=METRICS_GAUGES["component_cpu_percentage"], + value=0.0, + tags=tags, + ) + ) + records.append( + Record( + gauge=METRICS_GAUGES["component_mem_shared_bytes"], + value=0.0, + tags=tags, + ) + ) + records.append( + Record( + gauge=METRICS_GAUGES["component_rss_mb"], + value=0.0, + tags=tags, + ) + ) + records.append( + Record( + gauge=METRICS_GAUGES["component_uss_mb"], + value=0.0, + tags=tags, + ) + ) + records.append( + Record( + gauge=METRICS_GAUGES["component_num_fds"], + value=0, + tags=tags, + ) + ) + return records + + def _generate_system_stats_record( + self, stats: List[dict], component_name: str, pid: Optional[str] = None + ) -> List[Record]: + """Generate a list of Record class from a given component names. + + Args: + stats: a list of stats dict generated by `psutil.as_dict`. + If empty, it will create the metrics of a given "component_name" + which has all 0 values. + component_name: a component name for a given stats. + pid: optionally provided pids. + + Returns: + a list of Record class that will be exposed to Prometheus. + """ + total_cpu_percentage = 0.0 + total_rss = 0.0 + total_uss = 0.0 + total_shm = 0.0 + total_num_fds = 0 + + for stat in stats: + total_cpu_percentage += float(stat.get("cpu_percent", 0.0)) # noqa + memory_info = stat.get("memory_info") + if memory_info: + mem = stat["memory_info"] + total_rss += float(mem.rss) / 1.0e6 + if hasattr(mem, "shared"): + total_shm += float(mem.shared) + mem_full_info = stat.get("memory_full_info") + if mem_full_info is not None: + total_uss += float(mem_full_info.uss) / 1.0e6 + total_num_fds += int(stat.get("num_fds", 0)) + + tags = {"ip": self._ip, "Component": component_name} + if pid: + tags["pid"] = pid + + records = [] + records.append( + Record( + gauge=METRICS_GAUGES["component_cpu_percentage"], + value=total_cpu_percentage, + tags=tags, + ) + ) + records.append( + Record( + gauge=METRICS_GAUGES["component_mem_shared_bytes"], + value=total_shm, + tags=tags, + ) + ) + records.append( + Record( + gauge=METRICS_GAUGES["component_rss_mb"], + value=total_rss, + tags=tags, + ) + ) + if total_uss > 0.0: + records.append( + Record( + gauge=METRICS_GAUGES["component_uss_mb"], + value=total_uss, + tags=tags, + ) + ) + records.append( + Record( + gauge=METRICS_GAUGES["component_num_fds"], + value=total_num_fds, + tags=tags, + ) + ) + + return records + + def generate_worker_stats_record(self, worker_stats: List[dict]) -> List[Record]: + """Generate a list of Record class for worker proceses. + + This API automatically sets the component_name of record as + the name of worker processes. I.e., ray::* so that we can report + per task/actor (grouped by a func/class name) resource usages. + + Args: + stats: a list of stats dict generated by `psutil.as_dict` + for worker processes. + """ + # worekr cmd name (ray::*) -> stats dict. + proc_name_to_stats = defaultdict(list) + for stat in worker_stats: + cmdline = stat.get("cmdline") + # All ray processes start with ray:: + if cmdline and len(cmdline) > 0 and cmdline[0].startswith("ray::"): + proc_name = cmdline[0] + proc_name_to_stats[proc_name].append(stat) + # We will lose worker stats that don't follow the ray worker proc + # naming convention. Theoretically, there should be no data loss here + # because all worker processes are renamed to ray::. + + records = [] + for proc_name, stats in proc_name_to_stats.items(): + records.extend(self._generate_system_stats_record(stats, proc_name)) + + # Reset worker metrics that are from finished processes. + new_proc_names = set(proc_name_to_stats.keys()) + stale_procs = self._latest_worker_proc_names - new_proc_names + self._latest_worker_proc_names = new_proc_names + + for stale_proc_name in stale_procs: + records.extend(self._generate_reseted_stats_record(stale_proc_name)) + + return records + + def _to_records(self, stats, cluster_stats) -> List[Record]: + records_reported = [] + ip = stats["ip"] + is_head_node = str(self._is_head_node).lower() + + # Common tags for node-level metrics + node_tags = {"ip": ip, "IsHeadNode": is_head_node} + + # -- Instance count of cluster -- + # Only report cluster stats on head node + if "autoscaler_report" in cluster_stats and self._is_head_node: + active_nodes = cluster_stats["autoscaler_report"]["active_nodes"] + for node_type, active_node_count in active_nodes.items(): + records_reported.append( + Record( + gauge=METRICS_GAUGES["cluster_active_nodes"], + value=active_node_count, + tags={"node_type": node_type}, + ) + ) + + failed_nodes = cluster_stats["autoscaler_report"]["failed_nodes"] + failed_nodes_dict = {} + for node_ip, node_type in failed_nodes: + if node_type in failed_nodes_dict: + failed_nodes_dict[node_type] += 1 + else: + failed_nodes_dict[node_type] = 1 + + for node_type, failed_node_count in failed_nodes_dict.items(): + records_reported.append( + Record( + gauge=METRICS_GAUGES["cluster_failed_nodes"], + value=failed_node_count, + tags={"node_type": node_type}, + ) + ) + + pending_nodes = cluster_stats["autoscaler_report"]["pending_nodes"] + pending_nodes_dict = {} + for node_ip, node_type, status_message in pending_nodes: + if node_type in pending_nodes_dict: + pending_nodes_dict[node_type] += 1 + else: + pending_nodes_dict[node_type] = 1 + + for node_type, pending_node_count in pending_nodes_dict.items(): + records_reported.append( + Record( + gauge=METRICS_GAUGES["cluster_pending_nodes"], + value=pending_node_count, + tags={"node_type": node_type}, + ) + ) + + # -- CPU per node -- + cpu_usage = float(stats["cpu"]) + cpu_record = Record( + gauge=METRICS_GAUGES["node_cpu_utilization"], + value=cpu_usage, + tags=node_tags, + ) + + cpu_count, _ = stats["cpus"] + cpu_count_record = Record( + gauge=METRICS_GAUGES["node_cpu_count"], value=cpu_count, tags=node_tags + ) + + # -- Mem per node -- + mem_total, mem_available, _, mem_used = stats["mem"] + mem_used_record = Record( + gauge=METRICS_GAUGES["node_mem_used"], value=mem_used, tags=node_tags + ) + mem_available_record = Record( + gauge=METRICS_GAUGES["node_mem_available"], + value=mem_available, + tags=node_tags, + ) + mem_total_record = Record( + gauge=METRICS_GAUGES["node_mem_total"], value=mem_total, tags=node_tags + ) + + shm_used = stats["shm"] + if shm_used: + node_mem_shared = Record( + gauge=METRICS_GAUGES["node_mem_shared_bytes"], + value=shm_used, + tags=node_tags, + ) + records_reported.append(node_mem_shared) + + # The output example of GpuUtilizationInfo. + """ + {'index': 0, + 'uuid': 'GPU-36e1567d-37ed-051e-f8ff-df807517b396', + 'name': 'NVIDIA A10G', + 'utilization_gpu': 1, + 'memory_used': 0, + 'memory_total': 22731} + """ + # -- GPU per node -- + gpus = stats["gpus"] + gpus_available = len(gpus) + + if gpus_available: + for gpu in gpus: + gpus_utilization, gram_used, gram_total = 0, 0, 0 + # Consume GPU may not report its utilization. + if gpu["utilization_gpu"] is not None: + gpus_utilization += gpu["utilization_gpu"] + gram_used += gpu["memory_used"] + gram_total += gpu["memory_total"] + gpu_index = gpu.get("index") + gpu_name = gpu.get("name") + + gram_available = gram_total - gram_used + + if gpu_index is not None: + gpu_tags = {**node_tags, "GpuIndex": str(gpu_index)} + if gpu_name: + gpu_tags["GpuDeviceName"] = gpu_name + + # There's only 1 GPU per each index, so we record 1 here. + gpus_available_record = Record( + gauge=METRICS_GAUGES["node_gpus_available"], + value=1, + tags=gpu_tags, + ) + gpus_utilization_record = Record( + gauge=METRICS_GAUGES["node_gpus_utilization"], + value=gpus_utilization, + tags=gpu_tags, + ) + gram_used_record = Record( + gauge=METRICS_GAUGES["node_gram_used"], + value=gram_used, + tags=gpu_tags, + ) + gram_available_record = Record( + gauge=METRICS_GAUGES["node_gram_available"], + value=gram_available, + tags=gpu_tags, + ) + records_reported.extend( + [ + gpus_available_record, + gpus_utilization_record, + gram_used_record, + gram_available_record, + ] + ) + + # -- Disk per node -- + disk_io_stats = stats["disk_io"] + disk_read_record = Record( + gauge=METRICS_GAUGES["node_disk_io_read"], + value=disk_io_stats[0], + tags=node_tags, + ) + disk_write_record = Record( + gauge=METRICS_GAUGES["node_disk_io_write"], + value=disk_io_stats[1], + tags=node_tags, + ) + disk_read_count_record = Record( + gauge=METRICS_GAUGES["node_disk_io_read_count"], + value=disk_io_stats[2], + tags=node_tags, + ) + disk_write_count_record = Record( + gauge=METRICS_GAUGES["node_disk_io_write_count"], + value=disk_io_stats[3], + tags=node_tags, + ) + disk_io_speed_stats = stats["disk_io_speed"] + disk_read_speed_record = Record( + gauge=METRICS_GAUGES["node_disk_io_read_speed"], + value=disk_io_speed_stats[0], + tags=node_tags, + ) + disk_write_speed_record = Record( + gauge=METRICS_GAUGES["node_disk_io_write_speed"], + value=disk_io_speed_stats[1], + tags=node_tags, + ) + disk_read_iops_record = Record( + gauge=METRICS_GAUGES["node_disk_read_iops"], + value=disk_io_speed_stats[2], + tags=node_tags, + ) + disk_write_iops_record = Record( + gauge=METRICS_GAUGES["node_disk_write_iops"], + value=disk_io_speed_stats[3], + tags=node_tags, + ) + used = stats["disk"]["/"].used + free = stats["disk"]["/"].free + disk_utilization = float(used / (used + free)) * 100 + disk_usage_record = Record( + gauge=METRICS_GAUGES["node_disk_usage"], value=used, tags=node_tags + ) + disk_free_record = Record( + gauge=METRICS_GAUGES["node_disk_free"], value=free, tags=node_tags + ) + disk_utilization_percentage_record = Record( + gauge=METRICS_GAUGES["node_disk_utilization_percentage"], + value=disk_utilization, + tags=node_tags, + ) + + # -- Network speed (send/receive) stats per node -- + network_stats = stats["network"] + network_sent_record = Record( + gauge=METRICS_GAUGES["node_network_sent"], + value=network_stats[0], + tags=node_tags, + ) + network_received_record = Record( + gauge=METRICS_GAUGES["node_network_received"], + value=network_stats[1], + tags=node_tags, + ) + + # -- Network speed (send/receive) per node -- + network_speed_stats = stats["network_speed"] + network_send_speed_record = Record( + gauge=METRICS_GAUGES["node_network_send_speed"], + value=network_speed_stats[0], + tags=node_tags, + ) + network_receive_speed_record = Record( + gauge=METRICS_GAUGES["node_network_receive_speed"], + value=network_speed_stats[1], + tags=node_tags, + ) + + """ + Record system stats. + """ + + # Record component metrics. + raylet_stats = stats["raylet"] + if raylet_stats: + raylet_pid = str(raylet_stats["pid"]) + records_reported.extend( + self._generate_system_stats_record( + [raylet_stats], "raylet", pid=raylet_pid + ) + ) + workers_stats = stats["workers"] + records_reported.extend(self.generate_worker_stats_record(workers_stats)) + agent_stats = stats["agent"] + if agent_stats: + agent_pid = str(agent_stats["pid"]) + records_reported.extend( + self._generate_system_stats_record( + [agent_stats], "agent", pid=agent_pid + ) + ) + + # TODO(sang): Record GCS metrics. + # NOTE: Dashboard metrics is recorded within the dashboard because + # it can be deployed as a standalone instance. It shouldn't + # depend on the agent. + + records_reported.extend( + [ + cpu_record, + cpu_count_record, + mem_used_record, + mem_available_record, + mem_total_record, + disk_read_record, + disk_write_record, + disk_read_count_record, + disk_write_count_record, + disk_read_speed_record, + disk_write_speed_record, + disk_read_iops_record, + disk_write_iops_record, + disk_usage_record, + disk_free_record, + disk_utilization_percentage_record, + network_sent_record, + network_received_record, + network_send_speed_record, + network_receive_speed_record, + ] + ) + + return records_reported + + async def _run_loop(self, publisher): + """Get any changes to the log files and push updates to kv.""" + loop = utils.get_or_create_event_loop() + + while True: + try: + # Fetch autoscaler debug status + autoscaler_status_json_bytes: Optional[ + bytes + ] = await self._gcs_aio_client.internal_kv_get( + DEBUG_AUTOSCALING_STATUS.encode(), + None, + timeout=GCS_RPC_TIMEOUT_SECONDS, + ) + + # NOTE: Stats collection is executed inside the thread-pool + # executor (TPE) to avoid blocking the Agent's event-loop + json_payload = await loop.run_in_executor( + self._executor, + self._compose_stats_payload, + autoscaler_status_json_bytes, + ) + + await publisher.publish_resource_usage(self._key, json_payload) + + except Exception: + logger.exception("Error publishing node physical stats.") + + await asyncio.sleep(reporter_consts.REPORTER_UPDATE_INTERVAL_MS / 1000) + + def _compose_stats_payload( + self, cluster_autoscaling_stats_json: Optional[bytes] + ) -> str: + stats = self._collect_stats() + + # Report stats only when metrics collection is enabled. + if not self._metrics_collection_disabled: + cluster_stats = ( + json.loads(cluster_autoscaling_stats_json.decode()) + if cluster_autoscaling_stats_json + else {} + ) + + records = self._to_records(stats, cluster_stats) + + self._metrics_agent.record_and_export( + records, + global_tags={ + "Version": ray.__version__, + "SessionName": self._session_name, + }, + ) + + self._metrics_agent.clean_all_dead_worker_metrics() + + return jsonify_asdict(stats) + + async def run(self, server): + if server: + reporter_pb2_grpc.add_ReporterServiceServicer_to_server(self, server) + + await self._run_loop(self._dashboard_agent.publisher) + + @staticmethod + def is_minimal_module(): + return False diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_consts.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_consts.py new file mode 100644 index 0000000000000000000000000000000000000000..b3254fd3e51e5c7aa4454033af1802d9f89a1217 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_consts.py @@ -0,0 +1,7 @@ +import ray._private.ray_constants as ray_constants + +REPORTER_PREFIX = "RAY_REPORTER:" +# The reporter will report its statistics this often (milliseconds). +REPORTER_UPDATE_INTERVAL_MS = ray_constants.env_integer( + "REPORTER_UPDATE_INTERVAL_MS", 5000 +) diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_head.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6553f561ea503334018bb4991d32f2a67ab896f9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_head.py @@ -0,0 +1,669 @@ +import asyncio +import json +import logging +from concurrent.futures import ThreadPoolExecutor +from typing import List, Optional, Tuple + +import aiohttp.web + +import ray.dashboard.optional_utils as dashboard_optional_utils +import ray.dashboard.utils as dashboard_utils +from ray._private.gcs_pubsub import GcsAioResourceUsageSubscriber +from ray._private.metrics_agent import PrometheusServiceDiscoveryWriter +from ray._private.ray_constants import ( + DEBUG_AUTOSCALING_ERROR, + DEBUG_AUTOSCALING_STATUS, + DEBUG_AUTOSCALING_STATUS_LEGACY, + GLOBAL_GRPC_OPTIONS, + KV_NAMESPACE_CLUSTER, + env_integer, +) +from ray._private.usage.usage_constants import CLUSTER_METADATA_KEY +from ray._private.utils import get_or_create_event_loop, init_grpc_channel +from ray.autoscaler._private.commands import debug_status +from ray.core.generated import reporter_pb2, reporter_pb2_grpc +from ray.dashboard.consts import GCS_RPC_TIMEOUT_SECONDS +from ray.dashboard.datacenter import DataSource +from ray.dashboard.state_aggregator import StateAPIManager +from ray.util.state.common import ListApiOptions +from ray.util.state.state_manager import StateDataSourceClient + +logger = logging.getLogger(__name__) +routes = dashboard_optional_utils.DashboardHeadRouteTable + +EMOJI_WARNING = "⚠️" +WARNING_FOR_MULTI_TASK_IN_A_WORKER = ( + "Warning: This task is running in a worker process that is running multiple tasks. " + "This can happen if you are profiling a task right as it finishes or if you" + "are using the Async Actor or Threaded Actors pattern. " + "The information that follows may come from any of these tasks:" +) +SVG_STYLE = """\n""" + +# NOTE: Executor in this head is intentionally constrained to just 1 thread by +# default to limit its concurrency, therefore reducing potential for +# GIL contention +RAY_DASHBOARD_REPORTER_HEAD_TPE_MAX_WORKERS = env_integer( + "RAY_DASHBOARD_REPORTER_HEAD_TPE_MAX_WORKERS", 1 +) + + +class ReportHead(dashboard_utils.DashboardHeadModule): + def __init__(self, dashboard_head): + super().__init__(dashboard_head) + self._stubs = {} + self._ray_config = None + DataSource.agents.signal.append(self._update_stubs) + # TODO(fyrestone): Avoid using ray.state in dashboard, it's not + # asynchronous and will lead to low performance. ray disconnect() + # will be hang when the ray.state is connected and the GCS is exit. + # Please refer to: https://github.com/ray-project/ray/issues/16328 + assert dashboard_head.gcs_address or dashboard_head.redis_address + self._gcs_address = dashboard_head.gcs_address + temp_dir = dashboard_head.temp_dir + self.service_discovery = PrometheusServiceDiscoveryWriter( + self._gcs_address, temp_dir + ) + self._gcs_aio_client = dashboard_head.gcs_aio_client + self._state_api = None + + self._executor = ThreadPoolExecutor( + max_workers=RAY_DASHBOARD_REPORTER_HEAD_TPE_MAX_WORKERS, + thread_name_prefix="reporter_head_executor", + ) + + async def _update_stubs(self, change): + if change.old: + node_id, port = change.old + ip = DataSource.nodes[node_id]["nodeManagerAddress"] + self._stubs.pop(ip, None) + if change.new: + node_id, ports = change.new + ip = DataSource.nodes[node_id]["nodeManagerAddress"] + options = GLOBAL_GRPC_OPTIONS + channel = init_grpc_channel( + f"{ip}:{ports[1]}", options=options, asynchronous=True + ) + stub = reporter_pb2_grpc.ReporterServiceStub(channel) + self._stubs[ip] = stub + + @routes.get("/api/v0/cluster_metadata") + async def get_cluster_metadata(self, req): + return dashboard_optional_utils.rest_response( + success=True, message="", **self.cluster_metadata + ) + + @routes.get("/api/cluster_status") + async def get_cluster_status(self, req): + """Returns status information about the cluster. + + Currently contains two fields: + autoscaling_status (str)-- a status message from the autoscaler. + autoscaling_error (str)-- an error message from the autoscaler if + anything has gone wrong during autoscaling. + + These fields are both read from the GCS, it's expected that the + autoscaler writes them there. + """ + # TODO(rickyx): We should be able to get the cluster status from the + # autoscaler directly with V2. And we should be able to return structured data + # rather than a string. + + return_formatted_output = req.query.get("format", "0") == "1" + + (legacy_status, formatted_status_string, error) = await asyncio.gather( + *[ + self._gcs_aio_client.internal_kv_get( + key.encode(), namespace=None, timeout=GCS_RPC_TIMEOUT_SECONDS + ) + for key in [ + DEBUG_AUTOSCALING_STATUS_LEGACY, + DEBUG_AUTOSCALING_STATUS, + DEBUG_AUTOSCALING_ERROR, + ] + ] + ) + + formatted_status = ( + json.loads(formatted_status_string.decode()) + if formatted_status_string + else {} + ) + + if not return_formatted_output: + return dashboard_optional_utils.rest_response( + success=True, + message="Got cluster status.", + autoscaling_status=legacy_status.decode() if legacy_status else None, + autoscaling_error=error.decode() if error else None, + cluster_status=formatted_status if formatted_status else None, + ) + else: + return dashboard_optional_utils.rest_response( + success=True, + message="Got formatted cluster status.", + cluster_status=debug_status( + formatted_status_string, error, address=self._gcs_address + ), + ) + + async def get_task_ids_running_in_a_worker(self, worker_id: str) -> List[str]: + """ + Retrieves the task IDs of running tasks associated with a specific worker. + + Args: + worker_id: The ID of the worker. + + Returns: + List[str]: A list containing the task IDs + of all the running tasks associated with the worker. + """ + option = ListApiOptions( + filters=[("worker_id", "=", worker_id), ("state", "=", "RUNNING")], + detail=True, + timeout=10, + ) + # Call the state API to get all tasks in a worker + tasks_in_a_worker_result = await self._state_api.list_tasks(option=option) + tasks_in_a_worker = tasks_in_a_worker_result.result + + # Get task_id from each task in a worker + task_ids_in_a_worker = [ + task.get("task_id") + for task in tasks_in_a_worker + if task and "task_id" in task + ] + return task_ids_in_a_worker + + async def get_worker_details_for_running_task( + self, task_id: str, attempt_number: int + ) -> Tuple[Optional[int], Optional[str]]: + """ + Retrieves worker details for a specific task and attempt number. + + Args: + task_id: The ID of the task. + attempt_number: The attempt number of the task. + + Returns: + Tuple[Optional[int], Optional[str]]: A tuple + containing the worker's PID (process ID), + and worker's ID. + + Raises: + ValueError: If the task attempt is not running or + the state APi is not initialized. + """ + if self._state_api is None: + raise ValueError("The state API is not initialized yet. Please retry.") + option = ListApiOptions( + filters=[ + ("task_id", "=", task_id), + ("attempt_number", "=", attempt_number), + ], + detail=True, + timeout=10, + ) + + result = await self._state_api.list_tasks(option=option) + tasks = result.result + if not tasks: + return None, None + + pid = tasks[0]["worker_pid"] + worker_id = tasks[0]["worker_id"] + + state = tasks[0]["state"] + if state != "RUNNING": + raise ValueError( + f"The task attempt is not running: the current state is {state}." + ) + + return pid, worker_id + + @routes.get("/task/traceback") + async def get_task_traceback(self, req) -> aiohttp.web.Response: + """ + Retrieves the traceback information for a specific task. + Note that one worker process works on one task at a time + or one worker works on multiple async tasks. + + Args: + req (aiohttp.web.Request): The HTTP request object. + + Returns: + aiohttp.web.Response: The HTTP response containing + the traceback information. + + Raises: + ValueError: If the "task_id" parameter + is missing in the request query. + ValueError: If the "attempt_number" parameter + is missing in the request query. + ValueError: If the worker begins working on + another task during the traceback retrieval. + aiohttp.web.HTTPInternalServerError: If there is + an internal server error during the traceback retrieval. + """ + + if "task_id" not in req.query: + raise ValueError("task_id is required") + if "attempt_number" not in req.query: + raise ValueError("task's attempt number is required") + if "node_id" not in req.query: + raise ValueError("node_id is required") + + task_id = req.query.get("task_id") + attempt_number = req.query.get("attempt_number") + node_id = req.query.get("node_id") + + ip = DataSource.nodes[node_id]["nodeManagerAddress"] + + reporter_stub = self._stubs[ip] + + # Default not using `--native` for profiling + native = req.query.get("native", False) == "1" + + try: + (pid, _) = await self.get_worker_details_for_running_task( + task_id, attempt_number + ) + except ValueError as e: + raise aiohttp.web.HTTPInternalServerError(text=str(e)) + + logger.info( + "Sending stack trace request to {}:{} with native={}".format( + ip, pid, native + ) + ) + reply = await reporter_stub.GetTraceback( + reporter_pb2.GetTracebackRequest(pid=pid, native=native) + ) + + """ + In order to truly confirm whether there are any other tasks + running during the profiling, we need to retrieve all tasks + that are currently running or have finished, and then parse + the task events (i.e., their start and finish times) to check + for any potential overlap. However, this process can be + quite extensive, so here we will make our best efforts + to check for any overlapping tasks. + Therefore, we will check if the task is still running + """ + try: + (_, worker_id) = await self.get_worker_details_for_running_task( + task_id, attempt_number + ) + + except ValueError as e: + raise aiohttp.web.HTTPInternalServerError(text=str(e)) + if not reply.success: + return aiohttp.web.HTTPInternalServerError(text=reply.output) + + logger.info("Returning stack trace, size {}".format(len(reply.output))) + + task_ids_in_a_worker = await self.get_task_ids_running_in_a_worker(worker_id) + return aiohttp.web.Response( + text=WARNING_FOR_MULTI_TASK_IN_A_WORKER + + str(task_ids_in_a_worker) + + "\n" + + reply.output + if len(task_ids_in_a_worker) > 1 + else reply.output + ) + + @routes.get("/task/cpu_profile") + async def get_task_cpu_profile(self, req) -> aiohttp.web.Response: + """ + Retrieves the CPU profile for a specific task. + Note that one worker process works on one task at a time + or one worker works on multiple async tasks. + + Args: + req (aiohttp.web.Request): The HTTP request object. + + Returns: + aiohttp.web.Response: The HTTP response containing the CPU profile data. + + Raises: + ValueError: If the "task_id" parameter is + missing in the request query. + ValueError: If the "attempt_number" parameter is + missing in the request query. + ValueError: If the maximum duration allowed is exceeded. + ValueError: If the worker begins working on + another task during the profile retrieval. + aiohttp.web.HTTPInternalServerError: If there is + an internal server error during the profile retrieval. + aiohttp.web.HTTPInternalServerError: If the CPU Flame + Graph information for the task is not found. + """ + if "task_id" not in req.query: + raise ValueError("task_id is required") + if "attempt_number" not in req.query: + raise ValueError("task's attempt number is required") + if "node_id" not in req.query: + raise ValueError("node_id is required") + + task_id = req.query.get("task_id") + attempt_number = req.query.get("attempt_number") + node_id = req.query.get("node_id") + + ip = DataSource.nodes[node_id]["nodeManagerAddress"] + + duration_s = int(req.query.get("duration", 5)) + if duration_s > 60: + raise ValueError(f"The max duration allowed is 60 seconds: {duration_s}.") + format = req.query.get("format", "flamegraph") + + # Default not using `--native` for profiling + native = req.query.get("native", False) == "1" + reporter_stub = self._stubs[ip] + + try: + (pid, _) = await self.get_worker_details_for_running_task( + task_id, attempt_number + ) + except ValueError as e: + raise aiohttp.web.HTTPInternalServerError(text=str(e)) + + logger.info( + "Sending CPU profiling request to {}:{} for {} with native={}".format( + ip, pid, task_id, native + ) + ) + + reply = await reporter_stub.CpuProfiling( + reporter_pb2.CpuProfilingRequest( + pid=pid, duration=duration_s, format=format, native=native + ) + ) + + """ + In order to truly confirm whether there are any other tasks + running during the profiling, we need to retrieve all tasks + that are currently running or have finished, and then parse + the task events (i.e., their start and finish times) to check + for any potential overlap. However, this process can be quite + extensive, so here we will make our best efforts to check + for any overlapping tasks. Therefore, we will check if + the task is still running + """ + try: + (_, worker_id) = await self.get_worker_details_for_running_task( + task_id, attempt_number + ) + except ValueError as e: + raise aiohttp.web.HTTPInternalServerError(text=str(e)) + + if not reply.success: + return aiohttp.web.HTTPInternalServerError(text=reply.output) + logger.info("Returning profiling response, size {}".format(len(reply.output))) + + task_ids_in_a_worker = await self.get_task_ids_running_in_a_worker(worker_id) + return aiohttp.web.Response( + body='

{} {}


'.format( + EMOJI_WARNING, + WARNING_FOR_MULTI_TASK_IN_A_WORKER + str(task_ids_in_a_worker), + ) + + SVG_STYLE + + (reply.output) + if len(task_ids_in_a_worker) > 1 + else SVG_STYLE + reply.output, + headers={"Content-Type": "text/html"}, + ) + + @routes.get("/worker/traceback") + async def get_traceback(self, req) -> aiohttp.web.Response: + if "ip" in req.query and req.query["ip"] in self._stubs: + reporter_stub = self._stubs[req.query["ip"]] + else: + reporter_stub = list(self._stubs.values())[0] + pid = int(req.query["pid"]) + # Default not using `--native` for profiling + native = req.query.get("native", False) == "1" + logger.info( + "Sending stack trace request to {}:{} with native={}".format( + req.query.get("ip"), pid, native + ) + ) + reply = await reporter_stub.GetTraceback( + reporter_pb2.GetTracebackRequest(pid=pid, native=native) + ) + if reply.success: + logger.info("Returning stack trace, size {}".format(len(reply.output))) + return aiohttp.web.Response(text=reply.output) + else: + return aiohttp.web.HTTPInternalServerError(text=reply.output) + + @routes.get("/worker/cpu_profile") + async def cpu_profile(self, req) -> aiohttp.web.Response: + if "ip" in req.query and req.query["ip"] in self._stubs: + reporter_stub = self._stubs[req.query["ip"]] + else: + reporter_stub = list(self._stubs.values())[0] + pid = int(req.query["pid"]) + duration_s = int(req.query.get("duration", 5)) + if duration_s > 60: + raise ValueError(f"The max duration allowed is 60 seconds: {duration_s}.") + format = req.query.get("format", "flamegraph") + + # Default not using `--native` for profiling + native = req.query.get("native", False) == "1" + logger.info( + "Sending CPU profiling request to {}:{} with native={}".format( + req.query.get("ip"), pid, native + ) + ) + reply = await reporter_stub.CpuProfiling( + reporter_pb2.CpuProfilingRequest( + pid=pid, duration=duration_s, format=format, native=native + ) + ) + if reply.success: + logger.info( + "Returning profiling response, size {}".format(len(reply.output)) + ) + return aiohttp.web.Response( + body=reply.output, + headers={ + "Content-Type": "image/svg+xml" + if format == "flamegraph" + else "text/plain" + }, + ) + else: + return aiohttp.web.HTTPInternalServerError(text=reply.output) + + @routes.get("/memory_profile") + async def memory_profile(self, req) -> aiohttp.web.Response: + """ + Retrieves the memory profile for a specific worker or task. + Note that for tasks, one worker process works on one task at a time + or one worker works on multiple async tasks. + + Args: + req (aiohttp.web.Request): The HTTP request object. + + Returns: + aiohttp.web.Response: The HTTP response containing the memory profile data. + + Raises: + aiohttp.web.HTTPInternalServerError: If no stub + found from the given IP value + aiohttp.web.HTTPInternalServerError: If the + "task_id" parameter exists but either "attempt_number" + or "node id" is missing in the request query. + aiohttp.web.HTTPInternalServerError: If the maximum + duration allowed is exceeded. + aiohttp.web.HTTPInternalServerError If requesting task + profiling for the worker begins working on another task + during the profile retrieval. + aiohttp.web.HTTPInternalServerError: If there is + an internal server error during the profile retrieval. + """ + is_task = "task_id" in req.query + + if is_task: + if "attempt_number" not in req.query: + return aiohttp.web.HTTPInternalServerError( + text=( + "Failed to execute task profiling: " + "task's attempt number is required" + ) + ) + if "node_id" not in req.query: + return aiohttp.web.HTTPInternalServerError( + text=( + "Failed to execute task profiling: " + "task's node id is required" + ) + ) + + task_id = req.query.get("task_id") + attempt_number = req.query.get("attempt_number") + node_id = req.query.get("node_id") + ip = DataSource.nodes[node_id]["nodeManagerAddress"] + try: + (pid, _) = await self.get_worker_details_for_running_task( + task_id, attempt_number + ) + except ValueError as e: + raise aiohttp.web.HTTPInternalServerError(text=str(e)) + else: + pid = int(req.query["pid"]) + ip = req.query.get("ip") or None + + duration_s = int(req.query.get("duration", 10)) + + # Default not using `--native`, `--leaks` and `--format` for profiling + format = req.query.get("format", "flamegraph") + native = req.query.get("native", False) == "1" + leaks = req.query.get("leaks", False) == "1" + trace_python_allocators = req.query.get("trace_python_allocators", False) == "1" + + if ip: + if ip not in self._stubs: + return aiohttp.web.HTTPInternalServerError( + text="Failed to execute: No stub with given ip value" + ) + reporter_stub = self._stubs[ip] + else: + reporter_stub = list(self._stubs.values())[0] + + logger.info( + "Retrieving memory profiling request to {}:{}{}".format( + ip, pid, (f" for {task_id}" if is_task else "") + ) + ) + + reply = await reporter_stub.MemoryProfiling( + reporter_pb2.MemoryProfilingRequest( + pid=pid, + format=format, + leaks=leaks, + duration=duration_s, + native=native, + trace_python_allocators=trace_python_allocators, + ) + ) + + task_ids_in_a_worker = None + warning = reply.warning if reply.warning else "" + if is_task: + """ + In order to truly confirm whether there are any other tasks + running during the profiling, Ray needs to retrieve all tasks + that are currently running or have finished, and then parse + the task events (i.e., their start and finish times) to check + for any potential overlap. However, this process can be quite + extensive, so Ray makes our best efforts to check + for any overlapping tasks. Therefore, Ray checks if + the task is still running. + """ + try: + (_, worker_id) = await self.get_worker_details_for_running_task( + task_id, attempt_number + ) + except ValueError as e: + raise aiohttp.web.HTTPInternalServerError(text=str(e)) + + task_ids_in_a_worker = await self.get_task_ids_running_in_a_worker( + worker_id + ) + if len(task_ids_in_a_worker) > 1: + warning += ( + "\n" + + WARNING_FOR_MULTI_TASK_IN_A_WORKER + + str(task_ids_in_a_worker) + ) + + if not reply.success: + return aiohttp.web.HTTPInternalServerError(text=reply.output) + logger.info("Returning profiling response, size {}".format(len(reply.output))) + + return aiohttp.web.Response( + body='

{} {}


'.format( + EMOJI_WARNING, warning + ) + + (reply.output) + if warning != "" + else reply.output, + headers={"Content-Type": "text/html"}, + ) + + async def run(self, server): + gcs_channel = self._dashboard_head.aiogrpc_gcs_channel + self._state_api_data_source_client = StateDataSourceClient( + gcs_channel, self._dashboard_head.gcs_aio_client + ) + # Set up the state API in order to fetch task information. + # TODO(ryw): unify the StateAPIManager in reporter_head and state_head. + self._state_api = StateAPIManager( + self._state_api_data_source_client, + self._executor, + ) + + # Need daemon True to avoid dashboard hangs at exit. + self.service_discovery.daemon = True + self.service_discovery.start() + gcs_addr = self._dashboard_head.gcs_address + subscriber = GcsAioResourceUsageSubscriber(address=gcs_addr) + await subscriber.subscribe() + cluster_metadata = await self._dashboard_head.gcs_aio_client.internal_kv_get( + CLUSTER_METADATA_KEY, + namespace=KV_NAMESPACE_CLUSTER, + ) + self.cluster_metadata = json.loads(cluster_metadata.decode("utf-8")) + + loop = get_or_create_event_loop() + + while True: + try: + # The key is b'RAY_REPORTER:{node id hex}', + # e.g. b'RAY_REPORTER:2b4fbd...' + key, data = await subscriber.poll() + if key is None: + continue + + # NOTE: Every iteration is executed inside the thread-pool executor + # (TPE) to avoid blocking the Dashboard's event-loop + parsed_data = await loop.run_in_executor( + self._executor, json.loads, data + ) + + node_id = key.split(":")[-1] + DataSource.node_physical_stats[node_id] = parsed_data + except Exception: + logger.exception( + "Error receiving node physical stats from reporter agent." + ) + + @staticmethod + def is_minimal_module(): + return False diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__init__.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b837487d25e3cfdd2c9e8cad558deb883866255 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/sdk.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/sdk.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eed4a3bbf48d969d3941f588710dc4c0f9563b32 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/sdk.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_agent.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_agent.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..718e18fe1c580937225c6871b9eb339d40ba4c87 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_agent.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_head.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_head.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f78c9e337b9436e0250ba2cc34d6ba799d52ecbe Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_head.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_rest_api_impl.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_rest_api_impl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ba1b7760256690fcca36476beafdf64a15dfe9e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_rest_api_impl.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/sdk.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/sdk.py new file mode 100644 index 0000000000000000000000000000000000000000..338b051cbd62e85c05ffb0998eb287deb7ae9665 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/sdk.py @@ -0,0 +1,85 @@ +from typing import Any, Dict, Optional + +from ray._private.utils import split_address +from ray.dashboard.modules.dashboard_sdk import SubmissionClient + +try: + import aiohttp + import requests +except ImportError: + aiohttp = None + requests = None + + +DEPLOY_PATH = "/api/serve/applications/" +DELETE_PATH = "/api/serve/applications/" +STATUS_PATH = "/api/serve/applications/" + + +class ServeSubmissionClient(SubmissionClient): + def __init__( + self, + dashboard_head_address: str, + create_cluster_if_needed=False, + cookies: Optional[Dict[str, Any]] = None, + metadata: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, Any]] = None, + ): + if requests is None: + raise RuntimeError( + "The Serve CLI requires the ray[default] " + 'installation: `pip install "ray[default]"`' + ) + + invalid_address_message = ( + "Got an unexpected address" + f'"{dashboard_head_address}" while trying ' + "to connect to the Ray dashboard. The Serve SDK/CLI requires the " + "Ray dashboard's HTTP(S) address (which should start with " + '"http://" or "https://". If this address ' + "wasn't passed explicitly, it may be set in the " + "RAY_DASHBOARD_ADDRESS environment variable." + ) + + if "://" not in dashboard_head_address: + raise ValueError(invalid_address_message) + + module_string, _ = split_address(dashboard_head_address) + + # If user passes in ray://, raise error. Serve submission should + # not use a Ray client address. + if module_string not in ["http", "https"]: + raise ValueError(invalid_address_message) + + super().__init__( + address=dashboard_head_address, + create_cluster_if_needed=create_cluster_if_needed, + cookies=cookies, + metadata=metadata, + headers=headers, + ) + self._check_connection_and_version_with_url( + min_version="1.12", + version_error_message="Serve CLI is not supported on the Ray " + "cluster. Please ensure the cluster is " + "running Ray 1.12 or higher.", + url="/api/ray/version", + ) + + def get_serve_details(self) -> Dict: + response = self._do_request("GET", STATUS_PATH) + if response.status_code != 200: + self._raise_error(response) + + return response.json() + + def deploy_applications(self, config: Dict): + """Deploy multiple applications.""" + response = self._do_request("PUT", DEPLOY_PATH, json_data=config) + if response.status_code != 200: + self._raise_error(response) + + def delete_applications(self): + response = self._do_request("DELETE", DELETE_PATH) + if response.status_code != 200: + self._raise_error(response) diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_agent.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..47fe122840229e0e7e62d6f001044f3fb57ac177 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_agent.py @@ -0,0 +1,11 @@ +import ray.dashboard.optional_utils as optional_utils +import ray.dashboard.utils as dashboard_utils +from ray.dashboard.modules.serve.serve_rest_api_impl import create_serve_rest_api + +dashboard_agent_route_table = optional_utils.DashboardAgentRouteTable + +ServeAgent = create_serve_rest_api( + dashboard_module_superclass=dashboard_utils.DashboardAgentModule, + dashboard_route_table=dashboard_agent_route_table, + log_deprecation_warning=True, +) diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_head.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b3598bc67c6198ed7ef373d18ada7c1d00f56940 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_head.py @@ -0,0 +1,10 @@ +import ray.dashboard.optional_utils as optional_utils +import ray.dashboard.utils as dashboard_utils +from ray.dashboard.modules.serve.serve_rest_api_impl import create_serve_rest_api + +dashboard_head_route_table = optional_utils.DashboardHeadRouteTable + +ServeHead = create_serve_rest_api( + dashboard_module_superclass=dashboard_utils.DashboardHeadModule, + dashboard_route_table=dashboard_head_route_table, +) diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_rest_api_impl.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_rest_api_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..73c0f82c79ece1520961840767e89bd8a6a917a7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_rest_api_impl.py @@ -0,0 +1,260 @@ +"""This file contains the implementation for the Serve REST API. + +This implementation is in a class generated by a factory method. serve_head.py +and serve_agent.py run the factory method to generate versions of the class +that inherit from the DashboardHeadModule and DashboardAgentModule classes, +respectively. + +This means the API will be accessible on both the dashboard head and the +dashboard agent. Any changes here will affect both the head and the agent. +""" + +import asyncio +import dataclasses +import json +import logging +from functools import wraps +from typing import Union + +import aiohttp +from aiohttp.web import Request, Response + +import ray +import ray.dashboard.optional_utils as optional_utils +import ray.dashboard.optional_utils as dashboard_optional_utils +import ray.dashboard.utils as dashboard_utils +from ray._private.pydantic_compat import ValidationError +from ray.dashboard.modules.version import CURRENT_VERSION, VersionResponse +from ray.exceptions import RayTaskError + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +def validate_endpoint(log_deprecation_warning: bool): + def decorator(func): + @wraps(func) + async def check(self, *args, **kwargs): + try: + from ray import serve # noqa: F401 + + if log_deprecation_warning: + logger.info( + "The Serve REST API on the dashboard agent is deprecated. " + "Send requests to the Serve REST API directly to the " + "dashboard instead. If you're using default ports, this " + "means you should send the request to the same route on " + "port 8265 instead of 52365." + ) + except ImportError: + return Response( + status=501, + text=( + "Serve dependencies are not installed. Please run `pip " + 'install "ray[serve]"`.' + ), + ) + return await func(self, *args, **kwargs) + + return check + + return decorator + + +def create_serve_rest_api( + dashboard_module_superclass: Union[ + dashboard_utils.DashboardHeadModule, dashboard_utils.DashboardAgentModule + ], + dashboard_route_table: Union[ + dashboard_optional_utils.DashboardHeadRouteTable, + dashboard_optional_utils.DashboardAgentRouteTable, + ], + log_deprecation_warning: bool = False, +): + # NOTE (shrekris-anyscale): This class uses delayed imports for all + # Ray Serve-related modules. That way, users can use the Ray dashboard agent for + # non-Serve purposes without downloading Serve dependencies. + class ServeRestApiImpl(dashboard_module_superclass): + def __init__(self, dashboard_head_or_agent): + super().__init__(dashboard_head_or_agent) + self._controller = None + self._controller_lock = asyncio.Lock() + + # serve_start_async is not thread-safe call. This lock + # will make sure there is only one call that starts the serve instance. + # If the lock is already acquired by another async task, the async task + # will asynchronously wait for the lock. + self._controller_start_lock = asyncio.Lock() + self._session_name = dashboard_head_or_agent.session_name + + # TODO: It's better to use `/api/version`. + # It requires a refactor of ClassMethodRouteTable to differentiate the server. + @dashboard_route_table.get("/api/ray/version") + async def get_version(self, req: Request) -> Response: + # NOTE(edoakes): CURRENT_VERSION should be bumped and checked on the + # client when we have backwards-incompatible changes. + resp = VersionResponse( + version=CURRENT_VERSION, + ray_version=ray.__version__, + ray_commit=ray.__commit__, + session_name=self._session_name, + ) + return Response( + text=json.dumps(dataclasses.asdict(resp)), + content_type="application/json", + status=aiohttp.web.HTTPOk.status_code, + ) + + @dashboard_route_table.get("/api/serve/applications/") + @optional_utils.init_ray_and_catch_exceptions() + @validate_endpoint(log_deprecation_warning=log_deprecation_warning) + async def get_serve_instance_details(self, req: Request) -> Response: + from ray.serve.schema import ServeInstanceDetails + + controller = await self.get_serve_controller() + + if controller is None: + # If no serve instance is running, return a dict that represents that. + details = ServeInstanceDetails.get_empty_schema_dict() + else: + try: + details = await controller.get_serve_instance_details.remote() + except ray.exceptions.RayTaskError as e: + # Task failure sometimes are due to GCS + # failure. When GCS failed, we expect a longer time + # to recover. + return Response( + status=503, + text=( + "Failed to get a response from the controller. " + f"The GCS may be down, please retry later: {e}" + ), + ) + + return Response( + text=json.dumps(details), + content_type="application/json", + ) + + @dashboard_route_table.delete("/api/serve/applications/") + @optional_utils.init_ray_and_catch_exceptions() + async def delete_serve_applications(self, req: Request) -> Response: + from ray import serve + + if await self.get_serve_controller() is not None: + serve.shutdown() + + return Response() + + @dashboard_route_table.put("/api/serve/applications/") + @optional_utils.init_ray_and_catch_exceptions() + @validate_endpoint(log_deprecation_warning=log_deprecation_warning) + async def put_all_applications(self, req: Request) -> Response: + from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag + from ray.serve._private.api import serve_start_async + from ray.serve.config import ProxyLocation + from ray.serve.schema import ServeDeploySchema + + try: + config: ServeDeploySchema = ServeDeploySchema.parse_obj( + await req.json() + ) + except ValidationError as e: + return Response( + status=400, + text=repr(e), + ) + + config_http_options = config.http_options.dict() + location = ProxyLocation._to_deployment_mode(config.proxy_location) + full_http_options = dict({"location": location}, **config_http_options) + grpc_options = config.grpc_options.dict() + + async with self._controller_start_lock: + client = await serve_start_async( + http_options=full_http_options, + grpc_options=grpc_options, + global_logging_config=config.logging_config, + ) + + # Serve ignores HTTP options if it was already running when + # serve_start_async() is called. Therefore we validate that no + # existing HTTP options are updated and print warning in case they are + self.validate_http_options(client, full_http_options) + + try: + if config.logging_config: + client.update_global_logging_config(config.logging_config) + client.deploy_apps(config) + record_extra_usage_tag(TagKey.SERVE_REST_API_VERSION, "v2") + except RayTaskError as e: + return Response( + status=400, + text=str(e), + ) + else: + return Response() + + def validate_http_options(self, client, http_options): + divergent_http_options = [] + + for option, new_value in http_options.items(): + prev_value = getattr(client.http_config, option) + if prev_value != new_value: + divergent_http_options.append(option) + + if divergent_http_options: + logger.warning( + "Serve is already running on this Ray cluster and " + "it's not possible to update its HTTP options without " + "restarting it. Following options are attempted to be " + f"updated: {divergent_http_options}." + ) + + async def get_serve_controller(self): + """Gets the ServeController to the this cluster's Serve app. + + return: If Serve is running on this Ray cluster, returns a client to + the Serve controller. If Serve is not running, returns None. + """ + async with self._controller_lock: + if self._controller is not None: + try: + await self._controller.check_alive.remote() + return self._controller + except ray.exceptions.RayActorError: + logger.info("Controller is dead") + self._controller = None + + # Try to connect to serve even when we detect the actor is dead + # because the user might have started a new + # serve cluter. + from ray.serve._private.constants import ( + SERVE_CONTROLLER_NAME, + SERVE_NAMESPACE, + ) + + try: + # get_actor is a sync call but it'll timeout after + # ray.dashboard.consts.GCS_RPC_TIMEOUT_SECONDS + self._controller = ray.get_actor( + SERVE_CONTROLLER_NAME, namespace=SERVE_NAMESPACE + ) + except Exception as e: + logger.debug( + "There is no " + "instance running on this Ray cluster. Please " + "call `serve.start(detached=True) to start " + f"one: {e}" + ) + + return self._controller + + async def run(self, server): + pass + + @staticmethod + def is_minimal_module(): + return False + + return ServeRestApiImpl diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/snapshot/__init__.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/snapshot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/snapshot/__pycache__/snapshot_head.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/snapshot/__pycache__/snapshot_head.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31e51c3c9b19b323762a275909a84c628dc42ae4 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/snapshot/__pycache__/snapshot_head.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/train/__init__.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/train/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/modules/version.py b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/version.py new file mode 100644 index 0000000000000000000000000000000000000000..f0d186029932a11aa4e5b2c19da6597a835c1a91 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/modules/version.py @@ -0,0 +1,18 @@ +from dataclasses import dataclass + +# Version 0 -> 1: Added log streaming and changed behavior of job logs cli. +# Version 1 -> 2: - Renamed job_id to submission_id. +# - Changed list_jobs sdk/cli/api to return a list +# instead of a dictionary. +# Version 2 -> 3: - Added optional fields entrypoint_num_cpus, entrypoint_num_gpus +# and entrypoint_resources to submit_job sdk/cli/api. +# Version 3 -> 4: - Added DELETE endpoint for deleting jobs. +CURRENT_VERSION = "4" + + +@dataclass +class VersionResponse: + version: str + ray_version: str + ray_commit: str + session_name: str diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/optional_deps.py b/vllm/lib/python3.10/site-packages/ray/dashboard/optional_deps.py new file mode 100644 index 0000000000000000000000000000000000000000..a7ef2965292b0cf3a902431013409217c8cb4b94 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/optional_deps.py @@ -0,0 +1,21 @@ +# These imports determine whether or not a user has the required dependencies +# to launch the optional dashboard API server. +# If any of these imports fail, the dashboard API server will not be launched. +# Please add important dashboard-api dependencies to this list. + +import aiohttp # noqa: F401 +import aiohttp.web # noqa: F401 +import aiohttp_cors # noqa: F401 +import grpc # noqa: F401 + +# These checks have to come first because aiohttp looks +# for opencensus, too, and raises a different error otherwise. +import opencensus # noqa: F401 +import prometheus_client # noqa: F401 +import pydantic # noqa: F401 +from aiohttp import hdrs # noqa: F401 +from aiohttp.typedefs import PathLike # noqa: F401 +from aiohttp.web import RouteDef # noqa: F401 + +# Adding new modules should also be reflected in the +# python/ray/tests/test_minimal_install.py diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/optional_utils.py b/vllm/lib/python3.10/site-packages/ray/dashboard/optional_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4f5d067664656ff51557b7f60b0b514ded3f8ff2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/optional_utils.py @@ -0,0 +1,300 @@ +""" +Optional utils module contains utility methods +that require optional dependencies. +""" +import asyncio +import collections +import functools +import inspect +import json +import logging +import os +import time +import traceback +from collections import namedtuple +from typing import Any, Callable + +from aiohttp.web import Response + +import ray +import ray.dashboard.consts as dashboard_consts +from ray._private.ray_constants import RAY_INTERNAL_DASHBOARD_NAMESPACE, env_bool + +# All third-party dependencies that are not included in the minimal Ray +# installation must be included in this file. This allows us to determine if +# the agent has the necessary dependencies to be started. +from ray.dashboard.optional_deps import PathLike, RouteDef, aiohttp, hdrs +from ray.dashboard.utils import CustomEncoder, to_google_style + +try: + create_task = asyncio.create_task +except AttributeError: + create_task = asyncio.ensure_future + + +logger = logging.getLogger(__name__) + + +def method_route_table_factory(): + class MethodRouteTable: + """A helper class to bind http route to class method.""" + + _bind_map = collections.defaultdict(dict) + _routes = aiohttp.web.RouteTableDef() + + class _BindInfo: + def __init__(self, filename, lineno, instance): + self.filename = filename + self.lineno = lineno + self.instance = instance + + @classmethod + def routes(cls): + return cls._routes + + @classmethod + def bound_routes(cls): + bound_items = [] + for r in cls._routes._items: + if isinstance(r, RouteDef): + route_method = getattr(r.handler, "__route_method__") + route_path = getattr(r.handler, "__route_path__") + instance = cls._bind_map[route_method][route_path].instance + if instance is not None: + bound_items.append(r) + else: + bound_items.append(r) + routes = aiohttp.web.RouteTableDef() + routes._items = bound_items + return routes + + @classmethod + def _register_route(cls, method, path, **kwargs): + def _wrapper(handler): + if path in cls._bind_map[method]: + bind_info = cls._bind_map[method][path] + raise Exception( + f"Duplicated route path: {path}, " + f"previous one registered at " + f"{bind_info.filename}:{bind_info.lineno}" + ) + + bind_info = cls._BindInfo( + handler.__code__.co_filename, handler.__code__.co_firstlineno, None + ) + + @functools.wraps(handler) + async def _handler_route(*args) -> aiohttp.web.Response: + try: + # Make the route handler as a bound method. + # The args may be: + # * (Request, ) + # * (self, Request) + req = args[-1] + return await handler(bind_info.instance, req) + except Exception: + logger.exception("Handle %s %s failed.", method, path) + return rest_response( + success=False, message=traceback.format_exc() + ) + + cls._bind_map[method][path] = bind_info + _handler_route.__route_method__ = method + _handler_route.__route_path__ = path + return cls._routes.route(method, path, **kwargs)(_handler_route) + + return _wrapper + + @classmethod + def head(cls, path, **kwargs): + return cls._register_route(hdrs.METH_HEAD, path, **kwargs) + + @classmethod + def get(cls, path, **kwargs): + return cls._register_route(hdrs.METH_GET, path, **kwargs) + + @classmethod + def post(cls, path, **kwargs): + return cls._register_route(hdrs.METH_POST, path, **kwargs) + + @classmethod + def put(cls, path, **kwargs): + return cls._register_route(hdrs.METH_PUT, path, **kwargs) + + @classmethod + def patch(cls, path, **kwargs): + return cls._register_route(hdrs.METH_PATCH, path, **kwargs) + + @classmethod + def delete(cls, path, **kwargs): + return cls._register_route(hdrs.METH_DELETE, path, **kwargs) + + @classmethod + def view(cls, path, **kwargs): + return cls._register_route(hdrs.METH_ANY, path, **kwargs) + + @classmethod + def static(cls, prefix: str, path: PathLike, **kwargs: Any) -> None: + cls._routes.static(prefix, path, **kwargs) + + @classmethod + def bind(cls, instance): + def predicate(o): + if inspect.ismethod(o): + return hasattr(o, "__route_method__") and hasattr( + o, "__route_path__" + ) + return False + + handler_routes = inspect.getmembers(instance, predicate) + for _, h in handler_routes: + cls._bind_map[h.__func__.__route_method__][ + h.__func__.__route_path__ + ].instance = instance + + return MethodRouteTable + + +DashboardHeadRouteTable = method_route_table_factory() +DashboardAgentRouteTable = method_route_table_factory() + + +def rest_response( + success, message, convert_google_style=True, **kwargs +) -> aiohttp.web.Response: + # In the dev context we allow a dev server running on a + # different port to consume the API, meaning we need to allow + # cross-origin access + if os.environ.get("RAY_DASHBOARD_DEV") == "1": + headers = {"Access-Control-Allow-Origin": "*"} + else: + headers = {} + return aiohttp.web.json_response( + { + "result": success, + "msg": message, + "data": to_google_style(kwargs) if convert_google_style else kwargs, + }, + dumps=functools.partial(json.dumps, cls=CustomEncoder), + headers=headers, + status=200 if success else 500, + ) + + +# The cache value type used by aiohttp_cache. +_AiohttpCacheValue = namedtuple("AiohttpCacheValue", ["data", "expiration", "task"]) +# The methods with no request body used by aiohttp_cache. +_AIOHTTP_CACHE_NOBODY_METHODS = {hdrs.METH_GET, hdrs.METH_DELETE} + + +def aiohttp_cache( + ttl_seconds=dashboard_consts.AIOHTTP_CACHE_TTL_SECONDS, + maxsize=dashboard_consts.AIOHTTP_CACHE_MAX_SIZE, + enable=not env_bool(dashboard_consts.AIOHTTP_CACHE_DISABLE_ENVIRONMENT_KEY, False), +): + assert maxsize > 0 + cache = collections.OrderedDict() + + def _wrapper(handler): + if enable: + + @functools.wraps(handler) + async def _cache_handler(*args) -> aiohttp.web.Response: + # Make the route handler as a bound method. + # The args may be: + # * (Request, ) + # * (self, Request) + req = args[-1] + # Make key. + if req.method in _AIOHTTP_CACHE_NOBODY_METHODS: + key = req.path_qs + else: + key = (req.path_qs, await req.read()) + # Query cache. + value = cache.get(key) + if value is not None: + cache.move_to_end(key) + if not value.task.done() or value.expiration >= time.time(): + # Update task not done or the data is not expired. + return aiohttp.web.Response(**value.data) + + def _update_cache(task): + try: + response = task.result() + except Exception: + response = rest_response( + success=False, message=traceback.format_exc() + ) + data = { + "status": response.status, + "headers": dict(response.headers), + "body": response.body, + } + cache[key] = _AiohttpCacheValue( + data, time.time() + ttl_seconds, task + ) + cache.move_to_end(key) + if len(cache) > maxsize: + cache.popitem(last=False) + return response + + task = create_task(handler(*args)) + task.add_done_callback(_update_cache) + if value is None: + return await task + else: + return aiohttp.web.Response(**value.data) + + suffix = f"[cache ttl={ttl_seconds}, max_size={maxsize}]" + _cache_handler.__name__ += suffix + _cache_handler.__qualname__ += suffix + return _cache_handler + else: + return handler + + if inspect.iscoroutinefunction(ttl_seconds): + target_func = ttl_seconds + ttl_seconds = dashboard_consts.AIOHTTP_CACHE_TTL_SECONDS + return _wrapper(target_func) + else: + return _wrapper + + +def init_ray_and_catch_exceptions() -> Callable: + """Decorator to be used on methods that require being connected to Ray.""" + + def decorator_factory(f: Callable) -> Callable: + @functools.wraps(f) + async def decorator(self, *args, **kwargs): + try: + if not ray.is_initialized(): + try: + address = self.get_gcs_address() + logger.info(f"Connecting to ray with address={address}") + # Set the gcs rpc timeout to shorter + os.environ["RAY_gcs_server_request_timeout_seconds"] = str( + dashboard_consts.GCS_RPC_TIMEOUT_SECONDS + ) + # Init ray without logging to driver + # to avoid infinite logging issue. + ray.init( + address=address, + log_to_driver=False, + configure_logging=False, + namespace=RAY_INTERNAL_DASHBOARD_NAMESPACE, + _skip_env_hook=True, + ) + except Exception as e: + ray.shutdown() + raise e from None + return await f(self, *args, **kwargs) + except Exception as e: + logger.exception(f"Unexpected error in handler: {e}") + return Response( + text=traceback.format_exc(), + status=aiohttp.web.HTTPInternalServerError.status_code, + ) + + return decorator + + return decorator_factory diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/state_aggregator.py b/vllm/lib/python3.10/site-packages/ray/dashboard/state_aggregator.py new file mode 100644 index 0000000000000000000000000000000000000000..b934f4c5c9e68d5d068c5ef78e1ea5b306076b61 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/state_aggregator.py @@ -0,0 +1,822 @@ +import asyncio +import dataclasses +import logging +from concurrent.futures import ThreadPoolExecutor +from dataclasses import fields +from datetime import datetime +from itertools import islice +from typing import List, Optional, Tuple + +import ray.dashboard.memory_utils as memory_utils +from ray._private.profiling import chrome_tracing_dump +from ray._private.ray_constants import env_integer +from ray._private.utils import get_or_create_event_loop +from ray.dashboard.utils import compose_state_message +from ray.runtime_env import RuntimeEnv +from ray.util.state.common import ( + RAY_MAX_LIMIT_FROM_API_SERVER, + ActorState, + ActorSummaries, + ClusterEventState, + JobState, + ListApiOptions, + ListApiResponse, + NodeState, + ObjectState, + ObjectSummaries, + PlacementGroupState, + PredicateType, + RuntimeEnvState, + StateSchema, + StateSummary, + SummaryApiOptions, + SummaryApiResponse, + SupportedFilterType, + TaskState, + TaskSummaries, + WorkerState, + filter_fields, + protobuf_message_to_dict, + protobuf_to_task_state_dict, +) +from ray.util.state.state_manager import DataSourceUnavailable, StateDataSourceClient +from ray.util.state.util import convert_string_to_type + +logger = logging.getLogger(__name__) + +GCS_QUERY_FAILURE_WARNING = ( + "Failed to query data from GCS. It is due to " + "(1) GCS is unexpectedly failed. " + "(2) GCS is overloaded. " + "(3) There's an unexpected network issue. " + "Please check the gcs_server.out log to find the root cause." +) +NODE_QUERY_FAILURE_WARNING = ( + "Failed to query data from {type}. " + "Queried {total} {type} " + "and {network_failures} {type} failed to reply. It is due to " + "(1) {type} is unexpectedly failed. " + "(2) {type} is overloaded. " + "(3) There's an unexpected network issue. Please check the " + "{log_command} to find the root cause." +) + + +def _convert_filters_type( + filter: List[Tuple[str, PredicateType, SupportedFilterType]], + schema: StateSchema, +) -> List[Tuple[str, PredicateType, SupportedFilterType]]: + """Convert the given filter's type to SupportedFilterType. + + This method is necessary because click can only accept a single type + for its tuple (which is string in this case). + + Args: + filter: A list of filter which is a tuple of (key, val). + schema: The state schema. It is used to infer the type of the column for filter. + + Returns: + A new list of filters with correct types that match the schema. + """ + new_filter = [] + if dataclasses.is_dataclass(schema): + schema = {field.name: field.type for field in fields(schema)} + else: + schema = schema.schema_dict() + + for col, predicate, val in filter: + if col in schema: + column_type = schema[col] + try: + isinstance(val, column_type) + except TypeError: + # Calling `isinstance` to the Literal type raises a TypeError. + # Ignore this case. + pass + else: + if isinstance(val, column_type): + # Do nothing. + pass + elif column_type is int or column_type == "integer": + try: + val = convert_string_to_type(val, int) + except ValueError: + raise ValueError( + f"Invalid filter `--filter {col} {val}` for a int type " + "column. Please provide an integer filter " + f"`--filter {col} [int]`" + ) + elif column_type is float or column_type == "number": + try: + val = convert_string_to_type( + val, + float, + ) + except ValueError: + raise ValueError( + f"Invalid filter `--filter {col} {val}` for a float " + "type column. Please provide an integer filter " + f"`--filter {col} [float]`" + ) + elif column_type is bool or column_type == "boolean": + try: + val = convert_string_to_type(val, bool) + except ValueError: + raise ValueError( + f"Invalid filter `--filter {col} {val}` for a boolean " + "type column. Please provide " + f"`--filter {col} [True|true|1]` for True or " + f"`--filter {col} [False|false|0]` for False." + ) + new_filter.append((col, predicate, val)) + return new_filter + + +# TODO(sang): Move the class to state/state_manager.py. +# TODO(sang): Remove *State and replaces with Pydantic or protobuf. +# (depending on API interface standardization). +class StateAPIManager: + """A class to query states from data source, caches, and post-processes + the entries. + """ + + def __init__( + self, + state_data_source_client: StateDataSourceClient, + thread_pool_executor: ThreadPoolExecutor, + ): + self._client = state_data_source_client + self._thread_pool_executor = thread_pool_executor + + @property + def data_source_client(self): + return self._client + + def _filter( + self, + data: List[dict], + filters: List[Tuple[str, PredicateType, SupportedFilterType]], + state_dataclass: StateSchema, + detail: bool, + ) -> List[dict]: + """Return the filtered data given filters. + + Args: + data: A list of state data. + filters: A list of KV tuple to filter data (key, val). The data is filtered + if data[key] != val. + state_dataclass: The state schema. + + Returns: + A list of filtered state data in dictionary. Each state data's + unnecessary columns are filtered by the given state_dataclass schema. + """ + filters = _convert_filters_type(filters, state_dataclass) + result = [] + for datum in data: + match = True + for filter_column, filter_predicate, filter_value in filters: + filterable_columns = state_dataclass.filterable_columns() + filter_column = filter_column.lower() + if filter_column not in filterable_columns: + raise ValueError( + f"The given filter column {filter_column} is not supported. " + "Enter filters with –-filter key=value " + "or –-filter key!=value " + f"Supported filter columns: {filterable_columns}" + ) + + if filter_column not in datum: + match = False + elif filter_predicate == "=": + if isinstance(filter_value, str) and isinstance( + datum[filter_column], str + ): + # Case insensitive match for string filter values. + match = datum[filter_column].lower() == filter_value.lower() + elif isinstance(filter_value, str) and isinstance( + datum[filter_column], bool + ): + match = datum[filter_column] == convert_string_to_type( + filter_value, bool + ) + elif isinstance(filter_value, str) and isinstance( + datum[filter_column], int + ): + match = datum[filter_column] == convert_string_to_type( + filter_value, int + ) + else: + match = datum[filter_column] == filter_value + elif filter_predicate == "!=": + if isinstance(filter_value, str) and isinstance( + datum[filter_column], str + ): + match = datum[filter_column].lower() != filter_value.lower() + else: + match = datum[filter_column] != filter_value + else: + raise ValueError( + f"Unsupported filter predicate {filter_predicate} is given. " + "Available predicates: =, !=." + ) + + if not match: + break + + if match: + result.append(filter_fields(datum, state_dataclass, detail)) + return result + + async def list_actors(self, *, option: ListApiOptions) -> ListApiResponse: + """List all actor information from the cluster. + + Returns: + {actor_id -> actor_data_in_dict} + actor_data_in_dict's schema is in ActorState + + """ + try: + reply = await self._client.get_all_actor_info( + timeout=option.timeout, filters=option.filters + ) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + result = [] + for message in reply.actor_table_data: + data = protobuf_message_to_dict( + message=message, + fields_to_decode=[ + "actor_id", + "owner_id", + "job_id", + "node_id", + "placement_group_id", + ], + ) + result.append(data) + + num_after_truncation = len(result) + reply.num_filtered + result = self._filter(result, option.filters, ActorState, option.detail) + num_filtered = len(result) + + # Sort to make the output deterministic. + result.sort(key=lambda entry: entry["actor_id"]) + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + total=reply.total, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_placement_groups(self, *, option: ListApiOptions) -> ListApiResponse: + """List all placement group information from the cluster. + + Returns: + {pg_id -> pg_data_in_dict} + pg_data_in_dict's schema is in PlacementGroupState + """ + try: + reply = await self._client.get_all_placement_group_info( + timeout=option.timeout + ) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + result = [] + for message in reply.placement_group_table_data: + data = protobuf_message_to_dict( + message=message, + fields_to_decode=[ + "placement_group_id", + "creator_job_id", + "node_id", + ], + ) + result.append(data) + num_after_truncation = len(result) + + result = self._filter( + result, option.filters, PlacementGroupState, option.detail + ) + num_filtered = len(result) + # Sort to make the output deterministic. + result.sort(key=lambda entry: entry["placement_group_id"]) + return ListApiResponse( + result=list(islice(result, option.limit)), + total=reply.total, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_nodes(self, *, option: ListApiOptions) -> ListApiResponse: + """List all node information from the cluster. + + Returns: + {node_id -> node_data_in_dict} + node_data_in_dict's schema is in NodeState + """ + try: + reply = await self._client.get_all_node_info( + timeout=option.timeout, filters=option.filters + ) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + result = [] + for message in reply.node_info_list: + data = protobuf_message_to_dict( + message=message, fields_to_decode=["node_id"] + ) + data["node_ip"] = data["node_manager_address"] + data["start_time_ms"] = int(data["start_time_ms"]) + data["end_time_ms"] = int(data["end_time_ms"]) + death_info = data.get("death_info", {}) + data["state_message"] = compose_state_message( + death_info.get("reason", None), + death_info.get("reason_message", None), + ) + + result.append(data) + + num_after_truncation = len(result) + reply.num_filtered + result = self._filter(result, option.filters, NodeState, option.detail) + num_filtered = len(result) + + # Sort to make the output deterministic. + result.sort(key=lambda entry: entry["node_id"]) + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + total=reply.total, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_workers(self, *, option: ListApiOptions) -> ListApiResponse: + """List all worker information from the cluster. + + Returns: + {worker_id -> worker_data_in_dict} + worker_data_in_dict's schema is in WorkerState + """ + try: + reply = await self._client.get_all_worker_info( + timeout=option.timeout, + filters=option.filters, + ) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + + result = [] + for message in reply.worker_table_data: + data = protobuf_message_to_dict( + message=message, fields_to_decode=["worker_id", "raylet_id"] + ) + data["worker_id"] = data["worker_address"]["worker_id"] + data["node_id"] = data["worker_address"]["raylet_id"] + data["ip"] = data["worker_address"]["ip_address"] + data["start_time_ms"] = int(data["start_time_ms"]) + data["end_time_ms"] = int(data["end_time_ms"]) + data["worker_launch_time_ms"] = int(data["worker_launch_time_ms"]) + data["worker_launched_time_ms"] = int(data["worker_launched_time_ms"]) + result.append(data) + + num_after_truncation = len(result) + reply.num_filtered + result = self._filter(result, option.filters, WorkerState, option.detail) + num_filtered = len(result) + # Sort to make the output deterministic. + result.sort(key=lambda entry: entry["worker_id"]) + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + total=reply.total, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_jobs(self, *, option: ListApiOptions) -> ListApiResponse: + try: + reply = await self._client.get_job_info(timeout=option.timeout) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + result = [job.dict() for job in reply] + total = len(result) + result = self._filter(result, option.filters, JobState, option.detail) + num_filtered = len(result) + result.sort(key=lambda entry: entry["job_id"] or "") + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + total=total, + num_after_truncation=total, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_tasks(self, *, option: ListApiOptions) -> ListApiResponse: + """List all task information from the cluster. + + Returns: + {task_id -> task_data_in_dict} + task_data_in_dict's schema is in TaskState + """ + try: + reply = await self._client.get_all_task_info( + timeout=option.timeout, + filters=option.filters, + exclude_driver=option.exclude_driver, + ) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + """ + Transforms from proto to dict, applies filters, sorts, and truncates. + This function is executed in a separate thread. + """ + result = [ + protobuf_to_task_state_dict(message) for message in reply.events_by_task + ] + + # Num pre-truncation is the number of tasks returned from + # source + num filtered on source + num_after_truncation = len(result) + reply.num_filtered_on_gcs + num_total = reply.num_total_stored + reply.num_status_task_events_dropped + + result = self._filter(result, option.filters, TaskState, option.detail) + num_filtered = len(result) + + result.sort(key=lambda entry: entry["task_id"]) + result = list(islice(result, option.limit)) + + # TODO(rickyx): we could do better with the warning logic. It's messy now. + return ListApiResponse( + result=result, + total=num_total, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_objects(self, *, option: ListApiOptions) -> ListApiResponse: + """List all object information from the cluster. + + Returns: + {object_id -> object_data_in_dict} + object_data_in_dict's schema is in ObjectState + """ + raylet_ids = self._client.get_all_registered_raylet_ids() + replies = await asyncio.gather( + *[ + self._client.get_object_info(node_id, timeout=option.timeout) + for node_id in raylet_ids + ], + return_exceptions=True, + ) + + def transform(replies) -> ListApiResponse: + unresponsive_nodes = 0 + worker_stats = [] + total_objects = 0 + for reply, _ in zip(replies, raylet_ids): + if isinstance(reply, DataSourceUnavailable): + unresponsive_nodes += 1 + continue + elif isinstance(reply, Exception): + raise reply + + total_objects += reply.total + for core_worker_stat in reply.core_workers_stats: + # NOTE: Set preserving_proto_field_name=False here because + # `construct_memory_table` requires a dictionary that has + # modified protobuf name + # (e.g., workerId instead of worker_id) as a key. + worker_stats.append( + protobuf_message_to_dict( + message=core_worker_stat, + fields_to_decode=["object_id"], + preserving_proto_field_name=False, + ) + ) + + partial_failure_warning = None + if len(raylet_ids) > 0 and unresponsive_nodes > 0: + warning_msg = NODE_QUERY_FAILURE_WARNING.format( + type="raylet", + total=len(raylet_ids), + network_failures=unresponsive_nodes, + log_command="raylet.out", + ) + if unresponsive_nodes == len(raylet_ids): + raise DataSourceUnavailable(warning_msg) + partial_failure_warning = ( + f"The returned data may contain incomplete result. {warning_msg}" + ) + + result = [] + memory_table = memory_utils.construct_memory_table(worker_stats) + for entry in memory_table.table: + data = entry.as_dict() + # `construct_memory_table` returns object_ref field which is indeed + # object_id. We do transformation here. + # TODO(sang): Refactor `construct_memory_table`. + data["object_id"] = data["object_ref"] + del data["object_ref"] + data["ip"] = data["node_ip_address"] + del data["node_ip_address"] + data["type"] = data["type"].upper() + data["task_status"] = ( + "NIL" if data["task_status"] == "-" else data["task_status"] + ) + result.append(data) + + # Add callsite warnings if it is not configured. + callsite_warning = [] + callsite_enabled = env_integer("RAY_record_ref_creation_sites", 0) + if not callsite_enabled: + callsite_warning.append( + "Callsite is not being recorded. " + "To record callsite information for each ObjectRef created, set " + "env variable RAY_record_ref_creation_sites=1 during `ray start` " + "and `ray.init`." + ) + + num_after_truncation = len(result) + result = self._filter(result, option.filters, ObjectState, option.detail) + num_filtered = len(result) + # Sort to make the output deterministic. + result.sort(key=lambda entry: entry["object_id"]) + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + partial_failure_warning=partial_failure_warning, + total=total_objects, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + warnings=callsite_warning, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, replies + ) + + async def list_runtime_envs(self, *, option: ListApiOptions) -> ListApiResponse: + """List all runtime env information from the cluster. + + Returns: + A list of runtime env information in the cluster. + The schema of returned "dict" is equivalent to the + `RuntimeEnvState` protobuf message. + We don't have id -> data mapping like other API because runtime env + doesn't have unique ids. + """ + agent_ids = self._client.get_all_registered_runtime_env_agent_ids() + replies = await asyncio.gather( + *[ + self._client.get_runtime_envs_info(node_id, timeout=option.timeout) + for node_id in agent_ids + ], + return_exceptions=True, + ) + + def transform(replies) -> ListApiResponse: + result = [] + unresponsive_nodes = 0 + total_runtime_envs = 0 + for node_id, reply in zip( + self._client.get_all_registered_runtime_env_agent_ids(), replies + ): + if isinstance(reply, DataSourceUnavailable): + unresponsive_nodes += 1 + continue + elif isinstance(reply, Exception): + raise reply + + total_runtime_envs += reply.total + states = reply.runtime_env_states + for state in states: + data = protobuf_message_to_dict(message=state, fields_to_decode=[]) + # Need to deserialize this field. + data["runtime_env"] = RuntimeEnv.deserialize( + data["runtime_env"] + ).to_dict() + data["node_id"] = node_id + result.append(data) + + partial_failure_warning = None + if len(agent_ids) > 0 and unresponsive_nodes > 0: + warning_msg = NODE_QUERY_FAILURE_WARNING.format( + type="agent", + total=len(agent_ids), + network_failures=unresponsive_nodes, + log_command="dashboard_agent.log", + ) + if unresponsive_nodes == len(agent_ids): + raise DataSourceUnavailable(warning_msg) + partial_failure_warning = ( + f"The returned data may contain incomplete result. {warning_msg}" + ) + num_after_truncation = len(result) + result = self._filter( + result, option.filters, RuntimeEnvState, option.detail + ) + num_filtered = len(result) + + # Sort to make the output deterministic. + def sort_func(entry): + # If creation time is not there yet (runtime env is failed + # to be created or not created yet, they are the highest priority. + # Otherwise, "bigger" creation time is coming first. + if "creation_time_ms" not in entry: + return float("inf") + elif entry["creation_time_ms"] is None: + return float("inf") + else: + return float(entry["creation_time_ms"]) + + result.sort(key=sort_func, reverse=True) + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + partial_failure_warning=partial_failure_warning, + total=total_runtime_envs, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, replies + ) + + async def list_cluster_events(self, *, option: ListApiOptions) -> ListApiResponse: + """List all cluster events from the cluster. + + Returns: + A list of cluster events in the cluster. + The schema of returned "dict" is equivalent to the + `ClusterEventState` protobuf message. + """ + reply = await self._client.get_all_cluster_events() + + def transform(reply) -> ListApiResponse: + result = [] + for _, events in reply.items(): + for _, event in events.items(): + event["time"] = str(datetime.fromtimestamp(int(event["timestamp"]))) + result.append(event) + + num_after_truncation = len(result) + result.sort(key=lambda entry: entry["timestamp"]) + total = len(result) + result = self._filter( + result, option.filters, ClusterEventState, option.detail + ) + num_filtered = len(result) + # Sort to make the output deterministic. + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + total=total, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def summarize_tasks(self, option: SummaryApiOptions) -> SummaryApiResponse: + summary_by = option.summary_by or "func_name" + if summary_by not in ["func_name", "lineage"]: + raise ValueError('summary_by must be one of "func_name" or "lineage".') + + # For summary, try getting as many entries as possible to minimze data loss. + result = await self.list_tasks( + option=ListApiOptions( + timeout=option.timeout, + limit=RAY_MAX_LIMIT_FROM_API_SERVER, + filters=option.filters, + detail=summary_by == "lineage", + ) + ) + + if summary_by == "func_name": + summary_results = TaskSummaries.to_summary_by_func_name(tasks=result.result) + else: + # We will need the actors info for actor tasks. + actors = await self.list_actors( + option=ListApiOptions( + timeout=option.timeout, + limit=RAY_MAX_LIMIT_FROM_API_SERVER, + detail=True, + ) + ) + summary_results = TaskSummaries.to_summary_by_lineage( + tasks=result.result, actors=actors.result + ) + summary = StateSummary(node_id_to_summary={"cluster": summary_results}) + warnings = result.warnings + if ( + summary_results.total_actor_scheduled + + summary_results.total_actor_tasks + + summary_results.total_tasks + < result.num_filtered + ): + warnings = warnings or [] + warnings.append( + "There is missing data in this aggregation. " + "Possibly due to task data being evicted to preserve memory." + ) + return SummaryApiResponse( + total=result.total, + result=summary, + partial_failure_warning=result.partial_failure_warning, + warnings=warnings, + num_after_truncation=result.num_after_truncation, + num_filtered=result.num_filtered, + ) + + async def summarize_actors(self, option: SummaryApiOptions) -> SummaryApiResponse: + # For summary, try getting as many entries as possible to minimze data loss. + result = await self.list_actors( + option=ListApiOptions( + timeout=option.timeout, + limit=RAY_MAX_LIMIT_FROM_API_SERVER, + filters=option.filters, + ) + ) + summary = StateSummary( + node_id_to_summary={ + "cluster": ActorSummaries.to_summary(actors=result.result) + } + ) + return SummaryApiResponse( + total=result.total, + result=summary, + partial_failure_warning=result.partial_failure_warning, + warnings=result.warnings, + num_after_truncation=result.num_after_truncation, + num_filtered=result.num_filtered, + ) + + async def summarize_objects(self, option: SummaryApiOptions) -> SummaryApiResponse: + # For summary, try getting as many entries as possible to minimize data loss. + result = await self.list_objects( + option=ListApiOptions( + timeout=option.timeout, + limit=RAY_MAX_LIMIT_FROM_API_SERVER, + filters=option.filters, + ) + ) + summary = StateSummary( + node_id_to_summary={ + "cluster": ObjectSummaries.to_summary(objects=result.result) + } + ) + return SummaryApiResponse( + total=result.total, + result=summary, + partial_failure_warning=result.partial_failure_warning, + warnings=result.warnings, + num_after_truncation=result.num_after_truncation, + num_filtered=result.num_filtered, + ) + + async def generate_task_timeline(self, job_id: Optional[str]) -> List[dict]: + filters = [("job_id", "=", job_id)] if job_id else None + result = await self.list_tasks( + option=ListApiOptions(detail=True, filters=filters, limit=10000) + ) + return chrome_tracing_dump(result.result) diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/timezone_utils.py b/vllm/lib/python3.10/site-packages/ray/dashboard/timezone_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6a0d68b9c1a9989bc62682dd09b7eccaf51fc335 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/timezone_utils.py @@ -0,0 +1,56 @@ +import logging +from datetime import datetime + +logger = logging.getLogger(__name__) + +timezones = [ + {"offset": "-12:00", "value": "Etc/+12"}, + {"offset": "-11:00", "value": "Pacific/Pago_Pago"}, + {"offset": "-10:00", "value": "Pacific/Honolulu"}, + {"offset": "-09:00", "value": "America/Anchorage"}, + {"offset": "-08:00", "value": "America/Los_Angeles"}, + {"offset": "-07:00", "value": "America/Phoenix"}, + {"offset": "-06:00", "value": "America/Guatemala"}, + {"offset": "-05:00", "value": "America/Bogota"}, + {"offset": "-04:00", "value": "America/Halifax"}, + {"offset": "-03:30", "value": "America/St_Johns"}, + {"offset": "-03:00", "value": "America/Sao_Paulo"}, + {"offset": "-02:00", "value": "America/Godthab"}, + {"offset": "-01:00", "value": "Atlantic/Azores"}, + {"offset": "+00:00", "value": "Europe/London"}, + {"offset": "+01:00", "value": "Europe/Amsterdam"}, + {"offset": "+02:00", "value": "Asia/Amman"}, + {"offset": "+03:00", "value": "Asia/Baghdad"}, + {"offset": "+03:30", "value": "Asia/Tehran"}, + {"offset": "+04:00", "value": "Asia/Dubai"}, + {"offset": "+04:30", "value": "Asia/Kabul"}, + {"offset": "+05:00", "value": "Asia/Karachi"}, + {"offset": "+05:30", "value": "Asia/Kolkata"}, + {"offset": "+05:45", "value": "Asia/Kathmandu"}, + {"offset": "+06:00", "value": "Asia/Almaty"}, + {"offset": "+06:30", "value": "Asia/Yangon"}, + {"offset": "+07:00", "value": "Asia/Bangkok"}, + {"offset": "+08:00", "value": "Asia/Shanghai"}, + {"offset": "+09:00", "value": "Asia/Irkutsk"}, + {"offset": "+09:30", "value": "Australia/Adelaide"}, + {"offset": "+10:00", "value": "Australia/Brisbane"}, + {"offset": "+11:00", "value": "Asia/Magadan"}, + {"offset": "+12:00", "value": "Pacific/Auckland"}, + {"offset": "+13:00", "value": "Pacific/Tongatapu"}, +] + + +def get_current_timezone_info(): + current_tz = datetime.now().astimezone().tzinfo + offset = current_tz.utcoffset(None) + hours, remainder = divmod(offset.total_seconds(), 3600) + minutes = remainder // 60 + sign = "+" if hours >= 0 else "-" + current_offset = f"{sign}{abs(int(hours)):02d}:{abs(int(minutes)):02d}" + + current_timezone = next( + (tz for tz in timezones if tz["offset"] == current_offset), + {"offset": None, "value": None}, + ) + + return current_timezone diff --git a/vllm/lib/python3.10/site-packages/ray/dashboard/utils.py b/vllm/lib/python3.10/site-packages/ray/dashboard/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3efd441039bc53236ede002370238240c9ecfe67 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/dashboard/utils.py @@ -0,0 +1,699 @@ +import abc +import asyncio +import datetime +import functools +import importlib +import json +import logging +import os +import pkgutil +from abc import ABCMeta, abstractmethod +from base64 import b64decode +from collections import namedtuple +from collections.abc import Mapping, MutableMapping, Sequence +from typing import Optional + +import aiosignal # noqa: F401 +from frozenlist import FrozenList # noqa: F401 + +import ray +import ray._private.protobuf_compat +import ray._private.ray_constants as ray_constants +import ray._private.services as services +from ray._private.utils import ( + binary_to_hex, + check_dashboard_dependencies_installed, + split_address, +) +from ray._raylet import GcsClient + +try: + create_task = asyncio.create_task +except AttributeError: + create_task = asyncio.ensure_future + +logger = logging.getLogger(__name__) + + +class FrontendNotFoundError(OSError): + pass + + +class DashboardAgentModule(abc.ABC): + def __init__(self, dashboard_agent): + """ + Initialize current module when DashboardAgent loading modules. + :param dashboard_agent: The DashboardAgent instance. + """ + self._dashboard_agent = dashboard_agent + self.session_name = dashboard_agent.session_name + + @abc.abstractmethod + async def run(self, server): + """ + Run the module in an asyncio loop. An agent module can provide + servicers to the server. + :param server: Asyncio GRPC server, or None if ray is minimal. + """ + + @staticmethod + @abc.abstractclassmethod + def is_minimal_module(): + """ + Return True if the module is minimal, meaning it + should work with `pip install ray` that doesn't requires additional + dependencies. + """ + + def get_gcs_address(self): + return self._dashboard_agent.gcs_address + + +class DashboardHeadModule(abc.ABC): + def __init__(self, dashboard_head): + """ + Initialize current module when DashboardHead loading modules. + :param dashboard_head: The DashboardHead instance. + """ + self._dashboard_head = dashboard_head + self.session_name = dashboard_head.session_name + + @property + def http_session(self): + return self._dashboard_head.http_session + + @abc.abstractmethod + async def run(self, server): + """ + Run the module in an asyncio loop. A head module can provide + servicers to the server. + :param server: Asyncio GRPC server, or None if ray is minimal. + """ + + @staticmethod + @abc.abstractclassmethod + def is_minimal_module(): + """ + Return True if the module is minimal, meaning it + should work with `pip install ray` that doesn't requires additional + dependencies. + """ + + def get_gcs_address(self): + return self._dashboard_head.gcs_address + + +def dashboard_module(enable): + """A decorator for dashboard module.""" + + def _cls_wrapper(cls): + cls.__ray_dashboard_module_enable__ = enable + return cls + + return _cls_wrapper + + +def get_all_modules(module_type): + """ + Get all importable modules that are subclass of a given module type. + """ + logger.info(f"Get all modules by type: {module_type.__name__}") + import ray.dashboard.modules + + should_only_load_minimal_modules = not check_dashboard_dependencies_installed() + + for module_loader, name, ispkg in pkgutil.walk_packages( + ray.dashboard.modules.__path__, ray.dashboard.modules.__name__ + "." + ): + try: + importlib.import_module(name) + except ModuleNotFoundError as e: + logger.info( + f"Module {name} cannot be loaded because " + "we cannot import all dependencies. Install this module using " + "`pip install 'ray[default]'` for the full " + f"dashboard functionality. Error: {e}" + ) + if not should_only_load_minimal_modules: + logger.info( + "Although `pip install 'ray[default]'` is downloaded, " + "module couldn't be imported`" + ) + raise e + + imported_modules = [] + # module_type.__subclasses__() should contain modules that + # we could successfully import. + for m in module_type.__subclasses__(): + if not getattr(m, "__ray_dashboard_module_enable__", True): + continue + if should_only_load_minimal_modules and not m.is_minimal_module(): + continue + imported_modules.append(m) + logger.info(f"Available modules: {imported_modules}") + return imported_modules + + +def to_posix_time(dt): + return (dt - datetime.datetime(1970, 1, 1)).total_seconds() + + +def address_tuple(address): + if isinstance(address, tuple): + return address + ip, port = address.split(":") + return ip, int(port) + + +class CustomEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, bytes): + return binary_to_hex(obj) + if isinstance(obj, Immutable): + return obj.mutable() + # Let the base class default method raise the TypeError + return json.JSONEncoder.default(self, obj) + + +def to_camel_case(snake_str): + """Convert a snake str to camel case.""" + components = snake_str.split("_") + # We capitalize the first letter of each component except the first one + # with the 'title' method and join them together. + return components[0] + "".join(x.title() for x in components[1:]) + + +def to_google_style(d): + """Recursive convert all keys in dict to google style.""" + new_dict = {} + + for k, v in d.items(): + if isinstance(v, dict): + new_dict[to_camel_case(k)] = to_google_style(v) + elif isinstance(v, list): + new_list = [] + for i in v: + if isinstance(i, dict): + new_list.append(to_google_style(i)) + else: + new_list.append(i) + new_dict[to_camel_case(k)] = new_list + else: + new_dict[to_camel_case(k)] = v + return new_dict + + +def message_to_dict(message, decode_keys=None, **kwargs): + """Convert protobuf message to Python dict.""" + + def _decode_keys(d): + for k, v in d.items(): + if isinstance(v, dict): + d[k] = _decode_keys(v) + if isinstance(v, list): + new_list = [] + for i in v: + if isinstance(i, dict): + new_list.append(_decode_keys(i)) + else: + new_list.append(i) + d[k] = new_list + else: + if k in decode_keys: + d[k] = binary_to_hex(b64decode(v)) + else: + d[k] = v + return d + + d = ray._private.protobuf_compat.message_to_dict( + message, use_integers_for_enums=False, **kwargs + ) + if decode_keys: + return _decode_keys(d) + else: + return d + + +class SignalManager: + _signals = FrozenList() + + @classmethod + def register(cls, sig): + cls._signals.append(sig) + + @classmethod + def freeze(cls): + cls._signals.freeze() + for sig in cls._signals: + sig.freeze() + + +class Signal(aiosignal.Signal): + __slots__ = () + + def __init__(self, owner): + super().__init__(owner) + SignalManager.register(self) + + +class Bunch(dict): + """A dict with attribute-access.""" + + def __getattr__(self, key): + try: + return self.__getitem__(key) + except KeyError: + raise AttributeError(key) + + def __setattr__(self, key, value): + self.__setitem__(key, value) + + +class Change: + """Notify change object.""" + + def __init__(self, owner=None, old=None, new=None): + self.owner = owner + self.old = old + self.new = new + + def __str__(self): + return ( + f"Change(owner: {type(self.owner)}), " f"old: {self.old}, new: {self.new}" + ) + + +class NotifyQueue: + """Asyncio notify queue for Dict signal.""" + + _queue = asyncio.Queue() + + @classmethod + def put(cls, co): + cls._queue.put_nowait(co) + + @classmethod + async def get(cls): + return await cls._queue.get() + + +""" +https://docs.python.org/3/library/json.html?highlight=json#json.JSONEncoder + +-------------------+---------------+ + | Python | JSON | + +===================+===============+ + | dict | object | + +-------------------+---------------+ + | list, tuple | array | + +-------------------+---------------+ + | str | string | + +-------------------+---------------+ + | int, float | number | + +-------------------+---------------+ + | True | true | + +-------------------+---------------+ + | False | false | + +-------------------+---------------+ + | None | null | + +-------------------+---------------+ +""" +_json_compatible_types = {dict, list, tuple, str, int, float, bool, type(None), bytes} + + +def is_immutable(self): + raise TypeError("%r objects are immutable" % self.__class__.__name__) + + +def make_immutable(value, strict=True): + value_type = type(value) + if value_type is dict: + return ImmutableDict(value) + if value_type is list: + return ImmutableList(value) + if strict: + if value_type not in _json_compatible_types: + raise TypeError("Type {} can't be immutable.".format(value_type)) + return value + + +class Immutable(metaclass=ABCMeta): + @abstractmethod + def mutable(self): + pass + + +class ImmutableList(Immutable, Sequence): + """Makes a :class:`list` immutable.""" + + __slots__ = ("_list", "_proxy") + + def __init__(self, list_value): + if type(list_value) not in (list, ImmutableList): + raise TypeError(f"{type(list_value)} object is not a list.") + if isinstance(list_value, ImmutableList): + list_value = list_value.mutable() + self._list = list_value + self._proxy = [None] * len(list_value) + + def __reduce_ex__(self, protocol): + return type(self), (self._list,) + + def mutable(self): + return self._list + + def __eq__(self, other): + if isinstance(other, ImmutableList): + other = other.mutable() + return list.__eq__(self._list, other) + + def __ne__(self, other): + if isinstance(other, ImmutableList): + other = other.mutable() + return list.__ne__(self._list, other) + + def __contains__(self, item): + if isinstance(item, Immutable): + item = item.mutable() + return list.__contains__(self._list, item) + + def __getitem__(self, item): + proxy = self._proxy[item] + if proxy is None: + proxy = self._proxy[item] = make_immutable(self._list[item]) + return proxy + + def __len__(self): + return len(self._list) + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, list.__repr__(self._list)) + + +class ImmutableDict(Immutable, Mapping): + """Makes a :class:`dict` immutable.""" + + __slots__ = ("_dict", "_proxy") + + def __init__(self, dict_value): + if type(dict_value) not in (dict, ImmutableDict): + raise TypeError(f"{type(dict_value)} object is not a dict.") + if isinstance(dict_value, ImmutableDict): + dict_value = dict_value.mutable() + self._dict = dict_value + self._proxy = {} + + def __reduce_ex__(self, protocol): + return type(self), (self._dict,) + + def mutable(self): + return self._dict + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return make_immutable(default) + + def __eq__(self, other): + if isinstance(other, ImmutableDict): + other = other.mutable() + return dict.__eq__(self._dict, other) + + def __ne__(self, other): + if isinstance(other, ImmutableDict): + other = other.mutable() + return dict.__ne__(self._dict, other) + + def __contains__(self, item): + if isinstance(item, Immutable): + item = item.mutable() + return dict.__contains__(self._dict, item) + + def __getitem__(self, item): + proxy = self._proxy.get(item, None) + if proxy is None: + proxy = self._proxy[item] = make_immutable(self._dict[item]) + return proxy + + def __len__(self) -> int: + return len(self._dict) + + def __iter__(self): + if len(self._proxy) != len(self._dict): + for key in self._dict.keys() - self._proxy.keys(): + self._proxy[key] = make_immutable(self._dict[key]) + return iter(self._proxy) + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self._dict)) + + +class MutableNotificationDict(dict, MutableMapping): + """A simple descriptor for dict type to notify data changes. + :note: Only the first level data report change. + """ + + ChangeItem = namedtuple("DictChangeItem", ["key", "value"]) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._signal = Signal(self) + + def mutable(self): + return self + + @property + def signal(self): + return self._signal + + def __setitem__(self, key, value): + old = self.pop(key, None) + super().__setitem__(key, value) + if len(self._signal) and old != value: + if old is None: + co = self._signal.send( + Change(owner=self, new=Dict.ChangeItem(key, value)) + ) + else: + co = self._signal.send( + Change( + owner=self, + old=Dict.ChangeItem(key, old), + new=Dict.ChangeItem(key, value), + ) + ) + NotifyQueue.put(co) + + def __delitem__(self, key): + old = self.pop(key, None) + if len(self._signal) and old is not None: + co = self._signal.send(Change(owner=self, old=Dict.ChangeItem(key, old))) + NotifyQueue.put(co) + + def reset(self, d): + assert isinstance(d, Mapping) + for key in self.keys() - d.keys(): + del self[key] + for key, value in d.items(): + self[key] = value + + +class Dict(ImmutableDict, MutableMapping): + """A simple descriptor for dict type to notify data changes. + :note: Only the first level data report change. + """ + + ChangeItem = namedtuple("DictChangeItem", ["key", "value"]) + + def __init__(self, *args, **kwargs): + super().__init__(dict(*args, **kwargs)) + self.signal = Signal(self) + + def __setitem__(self, key, value): + old = self._dict.pop(key, None) + self._proxy.pop(key, None) + self._dict[key] = value + if len(self.signal) and old != value: + if old is None: + co = self.signal.send( + Change(owner=self, new=Dict.ChangeItem(key, value)) + ) + else: + co = self.signal.send( + Change( + owner=self, + old=Dict.ChangeItem(key, old), + new=Dict.ChangeItem(key, value), + ) + ) + NotifyQueue.put(co) + + def __delitem__(self, key): + old = self._dict.pop(key, None) + self._proxy.pop(key, None) + if len(self.signal) and old is not None: + co = self.signal.send(Change(owner=self, old=Dict.ChangeItem(key, old))) + NotifyQueue.put(co) + + def reset(self, d): + assert isinstance(d, Mapping) + for key in self._dict.keys() - d.keys(): + del self[key] + for key, value in d.items(): + self[key] = value + + +# Register immutable types. +for immutable_type in Immutable.__subclasses__(): + _json_compatible_types.add(immutable_type) + + +def async_loop_forever(interval_seconds, cancellable=False): + def _wrapper(coro): + @functools.wraps(coro) + async def _looper(*args, **kwargs): + while True: + try: + await coro(*args, **kwargs) + except asyncio.CancelledError as ex: + if cancellable: + logger.info( + f"An async loop forever coroutine " f"is cancelled {coro}." + ) + raise ex + else: + logger.exception( + f"Can not cancel the async loop " + f"forever coroutine {coro}." + ) + except Exception: + logger.exception(f"Error looping coroutine {coro}.") + await asyncio.sleep(interval_seconds) + + return _looper + + return _wrapper + + +def ray_client_address_to_api_server_url(address: str): + """Convert a Ray Client address of a running Ray cluster to its API server URL. + + Args: + address: The Ray Client address, e.g. "ray://my-cluster". + + Returns: + str: The API server URL of the cluster, e.g. "http://:8265". + """ + with ray.init(address=address) as client_context: + dashboard_url = client_context.dashboard_url + + return f"http://{dashboard_url}" + + +def ray_address_to_api_server_url(address: Optional[str]) -> str: + """Parse a Ray cluster address into API server URL. + + When an address is provided, it will be used to query GCS for + API server address from GCS, so a Ray cluster must be running. + + When an address is not provided, it will first try to auto-detect + a running Ray instance, or look for local GCS process. + + Args: + address: Ray cluster bootstrap address or Ray Client address. + Could also be `auto`. + + Returns: + API server HTTP URL. + """ + + address = services.canonicalize_bootstrap_address_or_die(address) + gcs_client = GcsClient(address=address, nums_reconnect_retry=0) + + ray.experimental.internal_kv._initialize_internal_kv(gcs_client) + api_server_url = ray._private.utils.internal_kv_get_with_retry( + gcs_client, + ray_constants.DASHBOARD_ADDRESS, + namespace=ray_constants.KV_NAMESPACE_DASHBOARD, + num_retries=20, + ) + + if api_server_url is None: + raise ValueError( + ( + "Couldn't obtain the API server address from GCS. It is likely that " + "the GCS server is down. Check gcs_server.[out | err] to see if it is " + "still alive." + ) + ) + api_server_url = f"http://{api_server_url.decode()}" + return api_server_url + + +def get_address_for_submission_client(address: Optional[str]) -> str: + """Get Ray API server address from Ray bootstrap or Client address. + + If None, it will try to auto-detect a running Ray instance, or look + for local GCS process. + + `address` is always overridden by the RAY_ADDRESS environment + variable, just like the `address` argument in `ray.init()`. + + Args: + address: Ray cluster bootstrap address or Ray Client address. + Could also be "auto". + + Returns: + API server HTTP URL, e.g. "http://:8265". + """ + if os.environ.get("RAY_ADDRESS"): + logger.debug(f"Using RAY_ADDRESS={os.environ['RAY_ADDRESS']}") + address = os.environ["RAY_ADDRESS"] + + if address and "://" in address: + module_string, _ = split_address(address) + if module_string == "ray": + logger.debug( + f"Retrieving API server address from Ray Client address {address}..." + ) + address = ray_client_address_to_api_server_url(address) + else: + # User specified a non-Ray-Client Ray cluster address. + address = ray_address_to_api_server_url(address) + logger.debug(f"Using API server address {address}.") + return address + + +def compose_state_message( + death_reason: Optional[str], death_reason_message: Optional[str] +) -> Optional[str]: + """Compose node state message based on death information. + + Args: + death_reason: The reason of node death. + This is a string representation of `gcs_pb2.NodeDeathInfo.Reason`. + death_reason_message: The message of node death. + This corresponds to `gcs_pb2.NodeDeathInfo.ReasonMessage`. + """ + if death_reason == "EXPECTED_TERMINATION": + state_message = "Expected termination" + elif death_reason == "UNEXPECTED_TERMINATION": + state_message = "Unexpected termination" + elif death_reason == "AUTOSCALER_DRAIN_PREEMPTED": + state_message = "Terminated due to preemption" + elif death_reason == "AUTOSCALER_DRAIN_IDLE": + state_message = "Terminated due to idle (no Ray activity)" + else: + state_message = None + + if death_reason_message: + if state_message: + state_message += f": {death_reason_message}" + else: + state_message = death_reason_message + return state_message + + +def close_logger_file_descriptor(logger_instance): + for handler in logger_instance.handlers: + handler.close() diff --git a/vllm/lib/python3.10/site-packages/ray/util/__pycache__/debugpy.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/__pycache__/debugpy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..166f8a7894824a50eaefb39057c695858ac250f9 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/__pycache__/debugpy.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/__pycache__/placement_group.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/__pycache__/placement_group.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc63c8c3710aacc8ce29de435ef043aa6cf19318 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/__pycache__/placement_group.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/__pycache__/rpdb.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/__pycache__/rpdb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9834e5c374f4c9de28827a7f5414c8f0aace3724 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/__pycache__/rpdb.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/dask/__pycache__/scheduler_utils.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/dask/__pycache__/scheduler_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d375a6b85fdbc60d88fbde75c74b9c7e17b9474d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/dask/__pycache__/scheduler_utils.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/dask/common.py b/vllm/lib/python3.10/site-packages/ray/util/dask/common.py new file mode 100644 index 0000000000000000000000000000000000000000..74c793b32e1ea0d4f610d8eedaa617442aaed8a9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/util/dask/common.py @@ -0,0 +1,88 @@ +from collections import OrderedDict +from collections.abc import Iterator +from operator import getitem +import uuid + +import ray + +from dask.base import quote +from dask.core import get as get_sync +from dask.utils import apply + +try: + from dataclasses import is_dataclass, fields as dataclass_fields +except ImportError: + # Python < 3.7 + def is_dataclass(x): + return False + + def dataclass_fields(x): + return [] + + +def unpack_object_refs(*args): + """ + Extract Ray object refs from a set of potentially arbitrarily nested + Python objects. + + Intended use is to find all Ray object references in a set of (possibly + nested) Python objects, do something to them (get(), wait(), etc.), then + repackage them into equivalent Python objects. + + Args: + *args: One or more (potentially nested) Python objects that contain + Ray object references. + + Returns: + A 2-tuple of a flat list of all contained Ray object references, and a + function that, when given the corresponding flat list of concrete + values, will return a set of Python objects equivalent to that which + was given in *args, but with all Ray object references replaced with + their corresponding concrete values. + """ + object_refs = [] + repack_dsk = {} + + object_refs_token = uuid.uuid4().hex + + def _unpack(expr): + if isinstance(expr, ray.ObjectRef): + token = expr.hex() + repack_dsk[token] = (getitem, object_refs_token, len(object_refs)) + object_refs.append(expr) + return token + + token = uuid.uuid4().hex + # Treat iterators like lists + typ = list if isinstance(expr, Iterator) else type(expr) + if typ in (list, tuple, set): + repack_task = (typ, [_unpack(i) for i in expr]) + elif typ in (dict, OrderedDict): + repack_task = (typ, [[_unpack(k), _unpack(v)] for k, v in expr.items()]) + elif is_dataclass(expr): + repack_task = ( + apply, + typ, + (), + ( + dict, + [ + [f.name, _unpack(getattr(expr, f.name))] + for f in dataclass_fields(expr) + ], + ), + ) + else: + return expr + repack_dsk[token] = repack_task + return token + + out = uuid.uuid4().hex + repack_dsk[out] = (tuple, [_unpack(i) for i in args]) + + def repack(results): + dsk = repack_dsk.copy() + dsk[object_refs_token] = quote(results) + return get_sync(dsk, out) + + return object_refs, repack diff --git a/vllm/lib/python3.10/site-packages/ray/util/dask/optimizations.py b/vllm/lib/python3.10/site-packages/ray/util/dask/optimizations.py new file mode 100644 index 0000000000000000000000000000000000000000..1f1f910f07b1e9ea3e32a5a6fb3f9ca8c5c53c29 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/util/dask/optimizations.py @@ -0,0 +1,167 @@ +import operator +import warnings + +import dask +from dask import core +from dask.core import istask +from dask.dataframe.core import _concat +from dask.dataframe.optimize import optimize +from dask.dataframe.shuffle import shuffle_group +from dask.highlevelgraph import HighLevelGraph + +from .scheduler import MultipleReturnFunc, multiple_return_get + +try: + from dask.dataframe.shuffle import SimpleShuffleLayer +except ImportError: + # SimpleShuffleLayer doesn't exist in this version of Dask. + SimpleShuffleLayer = None + +if SimpleShuffleLayer is not None: + + class MultipleReturnSimpleShuffleLayer(SimpleShuffleLayer): + @classmethod + def clone(cls, layer: SimpleShuffleLayer): + # TODO(Clark): Probably don't need this since SimpleShuffleLayer + # implements __copy__() and the shallow clone should be enough? + return cls( + name=layer.name, + column=layer.column, + npartitions=layer.npartitions, + npartitions_input=layer.npartitions_input, + ignore_index=layer.ignore_index, + name_input=layer.name_input, + meta_input=layer.meta_input, + parts_out=layer.parts_out, + annotations=layer.annotations, + ) + + def __repr__(self): + return ( + f"MultipleReturnSimpleShuffleLayer" + ) + + def __reduce__(self): + attrs = [ + "name", + "column", + "npartitions", + "npartitions_input", + "ignore_index", + "name_input", + "meta_input", + "parts_out", + "annotations", + ] + return ( + MultipleReturnSimpleShuffleLayer, + tuple(getattr(self, attr) for attr in attrs), + ) + + def _cull(self, parts_out): + return MultipleReturnSimpleShuffleLayer( + self.name, + self.column, + self.npartitions, + self.npartitions_input, + self.ignore_index, + self.name_input, + self.meta_input, + parts_out=parts_out, + ) + + def _construct_graph(self): + """Construct graph for a simple shuffle operation.""" + + shuffle_group_name = "group-" + self.name + shuffle_split_name = "split-" + self.name + + dsk = {} + n_parts_out = len(self.parts_out) + for part_out in self.parts_out: + # TODO(Clark): Find better pattern than in-scheduler concat. + _concat_list = [ + (shuffle_split_name, part_out, part_in) + for part_in in range(self.npartitions_input) + ] + dsk[(self.name, part_out)] = (_concat, _concat_list, self.ignore_index) + for _, _part_out, _part_in in _concat_list: + dsk[(shuffle_split_name, _part_out, _part_in)] = ( + multiple_return_get, + (shuffle_group_name, _part_in), + _part_out, + ) + if (shuffle_group_name, _part_in) not in dsk: + dsk[(shuffle_group_name, _part_in)] = ( + MultipleReturnFunc( + shuffle_group, + n_parts_out, + ), + (self.name_input, _part_in), + self.column, + 0, + self.npartitions, + self.npartitions, + self.ignore_index, + self.npartitions, + ) + + return dsk + + def rewrite_simple_shuffle_layer(dsk, keys): + if not isinstance(dsk, HighLevelGraph): + dsk = HighLevelGraph.from_collections(id(dsk), dsk, dependencies=()) + else: + dsk = dsk.copy() + + layers = dsk.layers.copy() + for key, layer in layers.items(): + if type(layer) is SimpleShuffleLayer: + dsk.layers[key] = MultipleReturnSimpleShuffleLayer.clone(layer) + return dsk + + def dataframe_optimize(dsk, keys, **kwargs): + if not isinstance(keys, (list, set)): + keys = [keys] + keys = list(core.flatten(keys)) + + if not isinstance(dsk, HighLevelGraph): + dsk = HighLevelGraph.from_collections(id(dsk), dsk, dependencies=()) + + dsk = rewrite_simple_shuffle_layer(dsk, keys=keys) + return optimize(dsk, keys, **kwargs) + +else: + + def dataframe_optimize(dsk, keys, **kwargs): + warnings.warn( + "Custom dataframe shuffle optimization only works on " + "dask>=2020.12.0, you are on version " + f"{dask.__version__}, please upgrade Dask." + "Falling back to default dataframe optimizer." + ) + return optimize(dsk, keys, **kwargs) + + +# Stale approaches below. + + +def fuse_splits_into_multiple_return(dsk, keys): + if not isinstance(dsk, HighLevelGraph): + dsk = HighLevelGraph.from_collections(id(dsk), dsk, dependencies=()) + else: + dsk = dsk.copy() + dependencies = dsk.dependencies.copy() + for k, v in dsk.items(): + if istask(v) and v[0] == shuffle_group: + task_deps = dependencies[k] + # Only rewrite shuffle group split if all downstream dependencies + # are splits. + if all( + istask(dsk[dep]) and dsk[dep][0] == operator.getitem + for dep in task_deps + ): + for dep in task_deps: + # Rewrite split + pass diff --git a/vllm/lib/python3.10/site-packages/ray/util/dask/scheduler.py b/vllm/lib/python3.10/site-packages/ray/util/dask/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..f3dbca063b5a643a0263a313ed9b4600fe775e67 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/util/dask/scheduler.py @@ -0,0 +1,634 @@ +import atexit +import threading +from collections import defaultdict +from collections import OrderedDict +from dataclasses import dataclass +from multiprocessing.pool import ThreadPool +from typing import Optional + +import ray + +import dask +from dask.core import istask, ishashable, _execute_task +from dask.system import CPU_COUNT +from dask.threaded import pack_exception, _thread_get_id + +from ray.util.dask.callbacks import local_ray_callbacks, unpack_ray_callbacks +from ray.util.dask.common import unpack_object_refs +from ray.util.dask.scheduler_utils import get_async, apply_sync + +main_thread = threading.current_thread() +default_pool = None +pools = defaultdict(dict) +pools_lock = threading.Lock() + +TOP_LEVEL_RESOURCES_ERR_MSG = ( + 'Use ray_remote_args={"resources": {...}} instead of resources={...} to specify ' + "required Ray task resources; see " + "https://docs.ray.io/en/master/ray-core/package-ref.html#ray-remote." +) + + +def enable_dask_on_ray( + shuffle: Optional[str] = "tasks", + use_shuffle_optimization: Optional[bool] = True, +) -> dask.config.set: + """ + Enable Dask-on-Ray scheduler. This helper sets the Dask-on-Ray scheduler + as the default Dask scheduler in the Dask config. By default, it will also + cause the task-based shuffle to be used for any Dask shuffle operations + (required for multi-node Ray clusters, not sharing a filesystem), and will + enable a Ray-specific shuffle optimization. + + >>> enable_dask_on_ray() + >>> ddf.compute() # <-- will use the Dask-on-Ray scheduler. + + If used as a context manager, the Dask-on-Ray scheduler will only be used + within the context's scope. + + >>> with enable_dask_on_ray(): + ... ddf.compute() # <-- will use the Dask-on-Ray scheduler. + >>> ddf.compute() # <-- won't use the Dask-on-Ray scheduler. + + Args: + shuffle: The shuffle method used by Dask, either "tasks" or + "disk". This should be "tasks" if using a multi-node Ray cluster. + Defaults to "tasks". + use_shuffle_optimization: Enable our custom Ray-specific shuffle + optimization. Defaults to True. + Returns: + The Dask config object, which can be used as a context manager to limit + the scope of the Dask-on-Ray scheduler to the corresponding context. + """ + if use_shuffle_optimization: + from ray.util.dask.optimizations import dataframe_optimize + else: + dataframe_optimize = None + # Manually set the global Dask scheduler config. + # We also force the task-based shuffle to be used since the disk-based + # shuffle doesn't work for a multi-node Ray cluster that doesn't share + # the filesystem. + return dask.config.set( + scheduler=ray_dask_get, shuffle=shuffle, dataframe_optimize=dataframe_optimize + ) + + +def disable_dask_on_ray(): + """ + Unsets the scheduler, shuffle method, and DataFrame optimizer. + """ + return dask.config.set(scheduler=None, shuffle=None, dataframe_optimize=None) + + +def ray_dask_get(dsk, keys, **kwargs): + """ + A Dask-Ray scheduler. This scheduler will send top-level (non-inlined) Dask + tasks to a Ray cluster for execution. The scheduler will wait for the + tasks to finish executing, fetch the results, and repackage them into the + appropriate Dask collections. This particular scheduler uses a threadpool + to submit Ray tasks. + + This can be passed directly to `dask.compute()`, as the scheduler: + + >>> dask.compute(obj, scheduler=ray_dask_get) + + You can override the currently active global Dask-Ray callbacks (e.g. + supplied via a context manager), the number of threads to use when + submitting the Ray tasks, or the threadpool used to submit Ray tasks: + + >>> dask.compute( + obj, + scheduler=ray_dask_get, + ray_callbacks=some_ray_dask_callbacks, + num_workers=8, + pool=some_cool_pool, + ) + + Args: + dsk: Dask graph, represented as a task DAG dictionary. + keys (List[str]): List of Dask graph keys whose values we wish to + compute and return. + ray_callbacks (Optional[list[callable]]): Dask-Ray callbacks. + num_workers (Optional[int]): The number of worker threads to use in + the Ray task submission traversal of the Dask graph. + pool (Optional[ThreadPool]): A multiprocessing threadpool to use to + submit Ray tasks. + + Returns: + Computed values corresponding to the provided keys. + """ + num_workers = kwargs.pop("num_workers", None) + pool = kwargs.pop("pool", None) + # We attempt to reuse any other thread pools that have been created within + # this thread and with the given number of workers. We reuse a global + # thread pool if num_workers is not given and we're in the main thread. + global default_pool + thread = threading.current_thread() + if pool is None: + with pools_lock: + if num_workers is None and thread is main_thread: + if default_pool is None: + default_pool = ThreadPool(CPU_COUNT) + atexit.register(default_pool.close) + pool = default_pool + elif thread in pools and num_workers in pools[thread]: + pool = pools[thread][num_workers] + else: + pool = ThreadPool(num_workers) + atexit.register(pool.close) + pools[thread][num_workers] = pool + + ray_callbacks = kwargs.pop("ray_callbacks", None) + persist = kwargs.pop("ray_persist", False) + enable_progress_bar = kwargs.pop("_ray_enable_progress_bar", None) + + # Handle Ray remote args and resource annotations. + if "resources" in kwargs: + raise ValueError(TOP_LEVEL_RESOURCES_ERR_MSG) + ray_remote_args = kwargs.pop("ray_remote_args", {}) + try: + annotations = dask.config.get("annotations") + except KeyError: + annotations = {} + if "resources" in annotations: + raise ValueError(TOP_LEVEL_RESOURCES_ERR_MSG) + + scoped_ray_remote_args = _build_key_scoped_ray_remote_args( + dsk, annotations, ray_remote_args + ) + + with local_ray_callbacks(ray_callbacks) as ray_callbacks: + # Unpack the Ray-specific callbacks. + ( + ray_presubmit_cbs, + ray_postsubmit_cbs, + ray_pretask_cbs, + ray_posttask_cbs, + ray_postsubmit_all_cbs, + ray_finish_cbs, + ) = unpack_ray_callbacks(ray_callbacks) + # NOTE: We hijack Dask's `get_async` function, injecting a different + # task executor. + object_refs = get_async( + _apply_async_wrapper( + pool.apply_async, + _rayify_task_wrapper, + ray_presubmit_cbs, + ray_postsubmit_cbs, + ray_pretask_cbs, + ray_posttask_cbs, + scoped_ray_remote_args, + ), + len(pool._pool), + dsk, + keys, + get_id=_thread_get_id, + pack_exception=pack_exception, + **kwargs, + ) + if ray_postsubmit_all_cbs is not None: + for cb in ray_postsubmit_all_cbs: + cb(object_refs, dsk) + # NOTE: We explicitly delete the Dask graph here so object references + # are garbage-collected before this function returns, i.e. before all + # Ray tasks are done. Otherwise, no intermediate objects will be + # cleaned up until all Ray tasks are done. + del dsk + if persist: + result = object_refs + else: + pb_actor = None + if enable_progress_bar: + pb_actor = ray.get_actor("_dask_on_ray_pb") + result = ray_get_unpack(object_refs, progress_bar_actor=pb_actor) + if ray_finish_cbs is not None: + for cb in ray_finish_cbs: + cb(result) + + # cleanup pools associated with dead threads. + with pools_lock: + active_threads = set(threading.enumerate()) + if thread is not main_thread: + for t in list(pools): + if t not in active_threads: + for p in pools.pop(t).values(): + p.close() + return result + + +def _apply_async_wrapper(apply_async, real_func, *extra_args, **extra_kwargs): + """ + Wraps the given pool `apply_async` function, hotswapping `real_func` in as + the function to be applied and adding `extra_args` and `extra_kwargs` to + `real_func`'s call. + + Args: + apply_async: The pool function to be wrapped. + real_func: The real function that we wish the pool apply + function to execute. + *extra_args: Extra positional arguments to pass to the `real_func`. + **extra_kwargs: Extra keyword arguments to pass to the `real_func`. + + Returns: + A wrapper function that will ignore it's first `func` argument and + pass `real_func` in its place. To be passed to `dask.local.get_async`. + """ + + def wrapper(func, args=(), kwds=None, callback=None): # noqa: M511 + if not kwds: + kwds = {} + return apply_async( + real_func, + args=args + extra_args, + kwds=dict(kwds, **extra_kwargs), + callback=callback, + ) + + return wrapper + + +def _rayify_task_wrapper( + key, + task_info, + dumps, + loads, + get_id, + pack_exception, + ray_presubmit_cbs, + ray_postsubmit_cbs, + ray_pretask_cbs, + ray_posttask_cbs, + scoped_ray_remote_args, +): + """ + The core Ray-Dask task execution wrapper, to be given to the thread pool's + `apply_async` function. Exactly the same as `execute_task`, except that it + calls `_rayify_task` on the task instead of `_execute_task`. + + Args: + key: The Dask graph key whose corresponding task we wish to + execute. + task_info: The task to execute and its dependencies. + dumps: A result serializing function. + loads: A task_info deserializing function. + get_id: An ID generating function. + pack_exception: An exception serializing function. + ray_presubmit_cbs: Pre-task submission callbacks. + ray_postsubmit_cbs: Post-task submission callbacks. + ray_pretask_cbs: Pre-task execution callbacks. + ray_posttask_cbs: Post-task execution callbacks. + scoped_ray_remote_args: Ray task options for each key. + + Returns: + A 3-tuple of the task's key, a literal or a Ray object reference for a + Ray task's result, and whether the Ray task submission failed. + """ + try: + task, deps = loads(task_info) + result = _rayify_task( + task, + key, + deps, + ray_presubmit_cbs, + ray_postsubmit_cbs, + ray_pretask_cbs, + ray_posttask_cbs, + scoped_ray_remote_args.get(key, {}), + ) + id = get_id() + result = dumps((result, id)) + failed = False + except BaseException as e: + result = pack_exception(e, dumps) + failed = True + return key, result, failed + + +def _rayify_task( + task, + key, + deps, + ray_presubmit_cbs, + ray_postsubmit_cbs, + ray_pretask_cbs, + ray_posttask_cbs, + ray_remote_args, +): + """ + Rayifies the given task, submitting it as a Ray task to the Ray cluster. + + Args: + task: A Dask graph value, being either a literal, dependency + key, Dask task, or a list thereof. + key: The Dask graph key for the given task. + deps: The dependencies of this task. + ray_presubmit_cbs: Pre-task submission callbacks. + ray_postsubmit_cbs: Post-task submission callbacks. + ray_pretask_cbs: Pre-task execution callbacks. + ray_posttask_cbs: Post-task execution callbacks. + ray_remote_args: Ray task options. + + Returns: + A literal, a Ray object reference representing a submitted task, or a + list thereof. + """ + if isinstance(task, list): + # Recursively rayify this list. This will still bottom out at the first + # actual task encountered, inlining any tasks in that task's arguments. + return [ + _rayify_task( + t, + key, + deps, + ray_presubmit_cbs, + ray_postsubmit_cbs, + ray_pretask_cbs, + ray_posttask_cbs, + ray_remote_args, + ) + for t in task + ] + elif istask(task): + # Unpacks and repacks Ray object references and submits the task to the + # Ray cluster for execution. + if ray_presubmit_cbs is not None: + alternate_returns = [cb(task, key, deps) for cb in ray_presubmit_cbs] + for alternate_return in alternate_returns: + # We don't submit a Ray task if a presubmit callback returns + # a non-`None` value, instead we return said value. + # NOTE: This returns the first non-None presubmit callback + # return value. + if alternate_return is not None: + return alternate_return + + func, args = task[0], task[1:] + if func is multiple_return_get: + return _execute_task(task, deps) + # If the function's arguments contain nested object references, we must + # unpack said object references into a flat set of arguments so that + # Ray properly tracks the object dependencies between Ray tasks. + arg_object_refs, repack = unpack_object_refs(args, deps) + # Submit the task using a wrapper function. + object_refs = dask_task_wrapper.options( + name=f"dask:{key!s}", + num_returns=( + 1 if not isinstance(func, MultipleReturnFunc) else func.num_returns + ), + **ray_remote_args, + ).remote( + func, + repack, + key, + ray_pretask_cbs, + ray_posttask_cbs, + *arg_object_refs, + ) + + if ray_postsubmit_cbs is not None: + for cb in ray_postsubmit_cbs: + cb(task, key, deps, object_refs) + + return object_refs + elif not ishashable(task): + return task + elif task in deps: + return deps[task] + else: + return task + + +@ray.remote +def dask_task_wrapper(func, repack, key, ray_pretask_cbs, ray_posttask_cbs, *args): + """ + A Ray remote function acting as a Dask task wrapper. This function will + repackage the given flat `args` into its original data structures using + `repack`, execute any Dask subtasks within the repackaged arguments + (inlined by Dask's optimization pass), and then pass the concrete task + arguments to the provide Dask task function, `func`. + + Args: + func: The Dask task function to execute. + repack: A function that repackages the provided args into + the original (possibly nested) Python objects. + key: The Dask key for this task. + ray_pretask_cbs: Pre-task execution callbacks. + ray_posttask_cbs: Post-task execution callback. + *args (ObjectRef): Ray object references representing the Dask task's + arguments. + + Returns: + The output of the Dask task. In the context of Ray, a + dask_task_wrapper.remote() invocation will return a Ray object + reference representing the Ray task's result. + """ + if ray_pretask_cbs is not None: + pre_states = [ + cb(key, args) if cb is not None else None for cb in ray_pretask_cbs + ] + repacked_args, repacked_deps = repack(args) + # Recursively execute Dask-inlined tasks. + actual_args = [_execute_task(a, repacked_deps) for a in repacked_args] + # Execute the actual underlying Dask task. + result = func(*actual_args) + + if ray_posttask_cbs is not None: + for cb, pre_state in zip(ray_posttask_cbs, pre_states): + if cb is not None: + cb(key, result, pre_state) + + return result + + +def render_progress_bar(tracker, object_refs): + from tqdm import tqdm + + # At this time, every task should be submitted. + total, finished = ray.get(tracker.result.remote()) + reported_finished_so_far = 0 + pb_bar = tqdm(total=total, position=0) + pb_bar.set_description("") + + ready_refs = [] + + while finished < total: + submitted, finished = ray.get(tracker.result.remote()) + pb_bar.update(finished - reported_finished_so_far) + reported_finished_so_far = finished + ready_refs, _ = ray.wait( + object_refs, timeout=0, num_returns=len(object_refs), fetch_local=False + ) + if len(ready_refs) == len(object_refs): + break + import time + + time.sleep(0.1) + pb_bar.close() + submitted, finished = ray.get(tracker.result.remote()) + if submitted != finished: + print("Completed. There was state inconsistency.") + from pprint import pprint + + pprint(ray.get(tracker.report.remote())) + + +def ray_get_unpack(object_refs, progress_bar_actor=None): + """ + Unpacks object references, gets the object references, and repacks. + Traverses arbitrary data structures. + + Args: + object_refs: A (potentially nested) Python object containing Ray object + references. + + Returns: + The input Python object with all contained Ray object references + resolved with their concrete values. + """ + + def get_result(object_refs): + if progress_bar_actor: + render_progress_bar(progress_bar_actor, object_refs) + return ray.get(object_refs) + + if isinstance(object_refs, tuple): + object_refs = list(object_refs) + + if isinstance(object_refs, list) and any( + not isinstance(x, ray.ObjectRef) for x in object_refs + ): + # We flatten the object references before calling ray.get(), since Dask + # loves to nest collections in nested tuples and Ray expects a flat + # list of object references. We repack the results after ray.get() + # completes. + object_refs, repack = unpack_object_refs(*object_refs) + computed_result = get_result(object_refs) + return repack(computed_result) + else: + return get_result(object_refs) + + +def ray_dask_get_sync(dsk, keys, **kwargs): + """ + A synchronous Dask-Ray scheduler. This scheduler will send top-level + (non-inlined) Dask tasks to a Ray cluster for execution. The scheduler will + wait for the tasks to finish executing, fetch the results, and repackage + them into the appropriate Dask collections. This particular scheduler + submits Ray tasks synchronously, which can be useful for debugging. + + This can be passed directly to `dask.compute()`, as the scheduler: + + >>> dask.compute(obj, scheduler=ray_dask_get_sync) + + You can override the currently active global Dask-Ray callbacks (e.g. + supplied via a context manager): + + >>> dask.compute( + obj, + scheduler=ray_dask_get_sync, + ray_callbacks=some_ray_dask_callbacks, + ) + + Args: + dsk: Dask graph, represented as a task DAG dictionary. + keys (List[str]): List of Dask graph keys whose values we wish to + compute and return. + + Returns: + Computed values corresponding to the provided keys. + """ + + ray_callbacks = kwargs.pop("ray_callbacks", None) + persist = kwargs.pop("ray_persist", False) + + with local_ray_callbacks(ray_callbacks) as ray_callbacks: + # Unpack the Ray-specific callbacks. + ( + ray_presubmit_cbs, + ray_postsubmit_cbs, + ray_pretask_cbs, + ray_posttask_cbs, + ray_postsubmit_all_cbs, + ray_finish_cbs, + ) = unpack_ray_callbacks(ray_callbacks) + # NOTE: We hijack Dask's `get_async` function, injecting a different + # task executor. + object_refs = get_async( + _apply_async_wrapper( + apply_sync, + _rayify_task_wrapper, + ray_presubmit_cbs, + ray_postsubmit_cbs, + ray_pretask_cbs, + ray_posttask_cbs, + ), + 1, + dsk, + keys, + **kwargs, + ) + if ray_postsubmit_all_cbs is not None: + for cb in ray_postsubmit_all_cbs: + cb(object_refs, dsk) + # NOTE: We explicitly delete the Dask graph here so object references + # are garbage-collected before this function returns, i.e. before all + # Ray tasks are done. Otherwise, no intermediate objects will be + # cleaned up until all Ray tasks are done. + del dsk + if persist: + result = object_refs + else: + result = ray_get_unpack(object_refs) + if ray_finish_cbs is not None: + for cb in ray_finish_cbs: + cb(result) + + return result + + +@dataclass +class MultipleReturnFunc: + func: callable + num_returns: int + + def __call__(self, *args, **kwargs): + returns = self.func(*args, **kwargs) + if isinstance(returns, dict) or isinstance(returns, OrderedDict): + returns = [returns[k] for k in range(len(returns))] + return returns + + +def multiple_return_get(multiple_returns, idx): + return multiple_returns[idx] + + +def _build_key_scoped_ray_remote_args(dsk, annotations, ray_remote_args): + # Handle per-layer annotations. + if not isinstance(dsk, dask.highlevelgraph.HighLevelGraph): + dsk = dask.highlevelgraph.HighLevelGraph.from_collections( + id(dsk), dsk, dependencies=() + ) + # Build key-scoped annotations. + scoped_annotations = {} + layers = [(name, dsk.layers[name]) for name in dsk._toposort_layers()] + for id_, layer in layers: + layer_annotations = layer.annotations + if layer_annotations is None: + layer_annotations = annotations + elif "resources" in layer_annotations: + raise ValueError(TOP_LEVEL_RESOURCES_ERR_MSG) + for key in layer.get_output_keys(): + layer_annotations_for_key = annotations.copy() + # Layer annotations override global annotations. + layer_annotations_for_key.update(layer_annotations) + # Let same-key annotations earlier in the topological sort take precedence. + layer_annotations_for_key.update(scoped_annotations.get(key, {})) + scoped_annotations[key] = layer_annotations_for_key + # Build key-scoped Ray remote args. + scoped_ray_remote_args = {} + for key, annotations in scoped_annotations.items(): + layer_ray_remote_args = ray_remote_args.copy() + # Layer Ray remote args override global Ray remote args given in the compute + # call. + layer_ray_remote_args.update(annotations.get("ray_remote_args", {})) + scoped_ray_remote_args[key] = layer_ray_remote_args + return scoped_ray_remote_args diff --git a/vllm/lib/python3.10/site-packages/ray/util/dask/scheduler_utils.py b/vllm/lib/python3.10/site-packages/ray/util/dask/scheduler_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..efb7b18bd9111f163ad23936253964b625ad8765 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/util/dask/scheduler_utils.py @@ -0,0 +1,371 @@ +""" +The following is adapted from Dask release 2021.03.1: + https://github.com/dask/dask/blob/2021.03.1/dask/local.py +""" + +import os +from queue import Queue, Empty + +from dask import config +from dask.callbacks import local_callbacks, unpack_callbacks +from dask.core import _execute_task, flatten, get_dependencies, has_tasks, reverse_dict +from dask.order import order + +if os.name == "nt": + # Python 3 windows Queue.get doesn't handle interrupts properly. To + # workaround this we poll at a sufficiently large interval that it + # shouldn't affect performance, but small enough that users trying to kill + # an application shouldn't care. + def queue_get(q): + while True: + try: + return q.get(block=True, timeout=0.1) + except Empty: + pass + +else: + + def queue_get(q): + return q.get() + + +def start_state_from_dask(dsk, cache=None, sortkey=None): + """Start state from a dask + Examples + -------- + >>> dsk = { + 'x': 1, + 'y': 2, + 'z': (inc, 'x'), + 'w': (add, 'z', 'y')} # doctest: +SKIP + >>> from pprint import pprint # doctest: +SKIP + >>> pprint(start_state_from_dask(dsk)) # doctest: +SKIP + {'cache': {'x': 1, 'y': 2}, + 'dependencies': {'w': {'z', 'y'}, 'x': set(), 'y': set(), 'z': {'x'}}, + 'dependents': {'w': set(), 'x': {'z'}, 'y': {'w'}, 'z': {'w'}}, + 'finished': set(), + 'ready': ['z'], + 'released': set(), + 'running': set(), + 'waiting': {'w': {'z'}}, + 'waiting_data': {'x': {'z'}, 'y': {'w'}, 'z': {'w'}}} + """ + if sortkey is None: + sortkey = order(dsk).get + if cache is None: + cache = config.get("cache", None) + if cache is None: + cache = dict() + data_keys = set() + for k, v in dsk.items(): + if not has_tasks(dsk, v): + cache[k] = v + data_keys.add(k) + + dsk2 = dsk.copy() + dsk2.update(cache) + + dependencies = {k: get_dependencies(dsk2, k) for k in dsk} + waiting = {k: v.copy() for k, v in dependencies.items() if k not in data_keys} + + dependents = reverse_dict(dependencies) + for a in cache: + for b in dependents.get(a, ()): + waiting[b].remove(a) + waiting_data = {k: v.copy() for k, v in dependents.items() if v} + + ready_set = {k for k, v in waiting.items() if not v} + ready = sorted(ready_set, key=sortkey, reverse=True) + waiting = {k: v for k, v in waiting.items() if v} + + state = { + "dependencies": dependencies, + "dependents": dependents, + "waiting": waiting, + "waiting_data": waiting_data, + "cache": cache, + "ready": ready, + "running": set(), + "finished": set(), + "released": set(), + } + + return state + + +def execute_task(key, task_info, dumps, loads, get_id, pack_exception): + """ + Compute task and handle all administration + See Also + -------- + _execute_task : actually execute task + """ + try: + task, data = loads(task_info) + result = _execute_task(task, data) + id = get_id() + result = dumps((result, id)) + failed = False + except BaseException as e: + result = pack_exception(e, dumps) + failed = True + return key, result, failed + + +def release_data(key, state, delete=True): + """Remove data from temporary storage + See Also + -------- + finish_task + """ + if key in state["waiting_data"]: + assert not state["waiting_data"][key] + del state["waiting_data"][key] + + state["released"].add(key) + + if delete: + del state["cache"][key] + + +DEBUG = False + + +def finish_task( + dsk, key, state, results, sortkey, delete=True, release_data=release_data +): + """ + Update execution state after a task finishes + Mutates. This should run atomically (with a lock). + """ + for dep in sorted(state["dependents"][key], key=sortkey, reverse=True): + s = state["waiting"][dep] + s.remove(key) + if not s: + del state["waiting"][dep] + state["ready"].append(dep) + + for dep in state["dependencies"][key]: + if dep in state["waiting_data"]: + s = state["waiting_data"][dep] + s.remove(key) + if not s and dep not in results: + if DEBUG: + from chest.core import nbytes + + print( + "Key: %s\tDep: %s\t NBytes: %.2f\t Release" + % (key, dep, sum(map(nbytes, state["cache"].values()) / 1e6)) + ) + release_data(dep, state, delete=delete) + elif delete and dep not in results: + release_data(dep, state, delete=delete) + + state["finished"].add(key) + state["running"].remove(key) + + return state + + +def nested_get(ind, coll): + """Get nested index from collection + Examples + -------- + >>> nested_get(1, 'abc') + 'b' + >>> nested_get([1, 0], 'abc') + ('b', 'a') + >>> nested_get([[1, 0], [0, 1]], 'abc') + (('b', 'a'), ('a', 'b')) + """ + if isinstance(ind, list): + return tuple(nested_get(i, coll) for i in ind) + else: + return coll[ind] + + +def default_get_id(): + """Default get_id""" + return None + + +def default_pack_exception(e, dumps): + raise + + +def reraise(exc, tb=None): + if exc.__traceback__ is not tb: + raise exc.with_traceback(tb) + raise exc + + +def identity(x): + """Identity function. Returns x. + >>> identity(3) + 3 + """ + return x + + +def get_async( + apply_async, + num_workers, + dsk, + result, + cache=None, + get_id=default_get_id, + rerun_exceptions_locally=None, + pack_exception=default_pack_exception, + raise_exception=reraise, + callbacks=None, + dumps=identity, + loads=identity, + **kwargs +): + """Asynchronous get function + This is a general version of various asynchronous schedulers for dask. It + takes a an apply_async function as found on Pool objects to form a more + specific ``get`` method that walks through the dask array with parallel + workers, avoiding repeat computation and minimizing memory use. + Parameters + ---------- + apply_async : function + Asynchronous apply function as found on Pool or ThreadPool + num_workers : int + The number of active tasks we should have at any one time + dsk : dict + A dask dictionary specifying a workflow + result : key or list of keys + Keys corresponding to desired data + cache : dict-like, optional + Temporary storage of results + get_id : callable, optional + Function to return the worker id, takes no arguments. Examples are + `threading.current_thread` and `multiprocessing.current_process`. + rerun_exceptions_locally : bool, optional + Whether to rerun failing tasks in local process to enable debugging + (False by default) + pack_exception : callable, optional + Function to take an exception and ``dumps`` method, and return a + serialized tuple of ``(exception, traceback)`` to send back to the + scheduler. Default is to just raise the exception. + raise_exception : callable, optional + Function that takes an exception and a traceback, and raises an error. + dumps: callable, optional + Function to serialize task data and results to communicate between + worker and parent. Defaults to identity. + loads: callable, optional + Inverse function of `dumps`. Defaults to identity. + callbacks : tuple or list of tuples, optional + Callbacks are passed in as tuples of length 5. Multiple sets of + callbacks may be passed in as a list of tuples. For more information, + see the dask.diagnostics documentation. + See Also + -------- + threaded.get + """ + queue = Queue() + + if isinstance(result, list): + result_flat = set(flatten(result)) + else: + result_flat = {result} + results = set(result_flat) + + dsk = dict(dsk) + with local_callbacks(callbacks) as callbacks: + _, _, pretask_cbs, posttask_cbs, _ = unpack_callbacks(callbacks) + started_cbs = [] + succeeded = False + # if start_state_from_dask fails, we will have something + # to pass to the final block. + state = {} + try: + for cb in callbacks: + if cb[0]: + cb[0](dsk) + started_cbs.append(cb) + + keyorder = order(dsk) + + state = start_state_from_dask(dsk, cache=cache, sortkey=keyorder.get) + + for _, start_state, _, _, _ in callbacks: + if start_state: + start_state(dsk, state) + + if rerun_exceptions_locally is None: + rerun_exceptions_locally = config.get("rerun_exceptions_locally", False) + + if state["waiting"] and not state["ready"]: + raise ValueError("Found no accessible jobs in dask") + + def fire_task(): + """Fire off a task to the thread pool""" + # Choose a good task to compute + key = state["ready"].pop() + state["running"].add(key) + for f in pretask_cbs: + f(key, dsk, state) + + # Prep data to send + data = {dep: state["cache"][dep] for dep in get_dependencies(dsk, key)} + # Submit + apply_async( + execute_task, + args=( + key, + dumps((dsk[key], data)), + dumps, + loads, + get_id, + pack_exception, + ), + callback=queue.put, + ) + + # Seed initial tasks into the thread pool + while state["ready"] and len(state["running"]) < num_workers: + fire_task() + + # Main loop, wait on tasks to finish, insert new ones + while state["waiting"] or state["ready"] or state["running"]: + key, res_info, failed = queue_get(queue) + if failed: + exc, tb = loads(res_info) + if rerun_exceptions_locally: + data = { + dep: state["cache"][dep] + for dep in get_dependencies(dsk, key) + } + task = dsk[key] + _execute_task(task, data) # Re-execute locally + else: + raise_exception(exc, tb) + res, worker_id = loads(res_info) + state["cache"][key] = res + finish_task(dsk, key, state, results, keyorder.get) + for f in posttask_cbs: + f(key, res, dsk, state, worker_id) + + while state["ready"] and len(state["running"]) < num_workers: + fire_task() + + succeeded = True + + finally: + for _, _, _, _, finish in started_cbs: + if finish: + finish(dsk, state, not succeeded) + + return nested_get(result, state["cache"]) + + +def apply_sync(func, args=(), kwds=None, callback=None): + """A naive synchronous version of apply_async""" + if kwds is None: + kwds = {} + + res = func(*args, **kwds) + if callback is not None: + callback(res) diff --git a/vllm/lib/python3.10/site-packages/ray/util/lightgbm/__init__.py b/vllm/lib/python3.10/site-packages/ray/util/lightgbm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a46aefde633525e93463c500b0a229d05391449 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/util/lightgbm/__init__.py @@ -0,0 +1,4 @@ +raise DeprecationWarning( + "ray.util.lightgbm has been removed as of Ray 2.0. Instead, use the `lightgbm-ray` " + "library directly or the `LightGBMTrainer` in Ray Train." +) diff --git a/vllm/lib/python3.10/site-packages/ray/util/lightgbm/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/lightgbm/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d96b63bf5492caa8a6253ae45e32301fdf496d5 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/lightgbm/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adc7c7729c0338741e5655693556eca0f25eb244 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/api.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fddaee99a27a42f49c1e07a6b466eb8574ef4fb6 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/api.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/common.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..017226cd6eb0542cd92056647247ed72c4ccf9a8 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/common.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/custom_types.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/custom_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31bfd625691152871d34fb2a2b103b1056ac56b0 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/custom_types.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/state_cli.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/state_cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6d8eb5e67b42fb6f8f78837492beaea87cec08f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/state_cli.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/state_manager.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/state_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd6913df9636e000f12de9ab73cfe63f332dc0bf Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/state_manager.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/util.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67e409b9c124ea4b80f7be2cb1b587107914c5e2 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/util/state/__pycache__/util.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/util/state/common.py b/vllm/lib/python3.10/site-packages/ray/util/state/common.py new file mode 100644 index 0000000000000000000000000000000000000000..686d5355af4a054af0f3ff686a4fd01a628d3354 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/util/state/common.py @@ -0,0 +1,1685 @@ +import datetime +import json +import logging +import sys +from abc import ABC +from dataclasses import asdict, field, fields +from enum import Enum, unique +from typing import Any, Dict, List, Optional, Set, Tuple, Union + +import ray.dashboard.utils as dashboard_utils +from ray._private.ray_constants import env_integer +from ray.core.generated.common_pb2 import TaskStatus, TaskType +from ray.core.generated.gcs_pb2 import TaskEvents +from ray.util.state.custom_types import ( + TypeActorStatus, + TypeNodeStatus, + TypePlacementGroupStatus, + TypeReferenceType, + TypeTaskStatus, + TypeTaskType, + TypeWorkerExitType, + TypeWorkerType, +) +from ray.util.state.exception import RayStateApiException +from ray.dashboard.modules.job.pydantic_models import JobDetails + +# TODO(aguo): Instead of a version check, modify the below models +# to use pydantic BaseModel instead of dataclass. +# In pydantic 2, dataclass no longer needs the `init=True` kwarg to +# generate an __init__ method. Additionally, it will raise an error if +# it detects `init=True` to be set. +from ray._private.pydantic_compat import IS_PYDANTIC_2 + +try: + from pydantic.dataclasses import dataclass + + +except ImportError: + # pydantic is not available in the dashboard. + # We will use the dataclass from the standard library. + from dataclasses import dataclass + + +logger = logging.getLogger(__name__) + +DEFAULT_RPC_TIMEOUT = 30 +DEFAULT_LIMIT = 100 +DEFAULT_LOG_LIMIT = 1000 + +# Max number of entries from API server to the client +RAY_MAX_LIMIT_FROM_API_SERVER = env_integer( + "RAY_MAX_LIMIT_FROM_API_SERVER", 10 * 1000 +) # 10k + +# Max number of entries from data sources (rest will be truncated at the +# data source, e.g. raylet) +RAY_MAX_LIMIT_FROM_DATA_SOURCE = env_integer( + "RAY_MAX_LIMIT_FROM_DATA_SOURCE", 10 * 1000 +) # 10k + + +@unique +class StateResource(Enum): + ACTORS = "actors" + JOBS = "jobs" + PLACEMENT_GROUPS = "placement_groups" + NODES = "nodes" + WORKERS = "workers" + TASKS = "tasks" + OBJECTS = "objects" + RUNTIME_ENVS = "runtime_envs" + CLUSTER_EVENTS = "cluster_events" + + +@unique +class SummaryResource(Enum): + ACTORS = "actors" + TASKS = "tasks" + OBJECTS = "objects" + + +SupportedFilterType = Union[str, bool, int, float] + + +PredicateType = str # Literal["=", "!="] + + +class Humanify: + """A class containing default methods to + convert units into a human readable string.""" + + def timestamp(x: float): + """Converts milliseconds to a datetime object.""" + return str(datetime.datetime.fromtimestamp(x / 1000)) + + def memory(x: int): + """Converts raw bytes to a human readable memory size.""" + if x >= 2**30: + return str(format(x / (2**30), ".3f")) + " GiB" + elif x >= 2**20: + return str(format(x / (2**20), ".3f")) + " MiB" + elif x >= 2**10: + return str(format(x / (2**10), ".3f")) + " KiB" + return str(format(x, ".3f")) + " B" + + def duration(x: int): + """Converts milliseconds to a human readable duration.""" + return str(datetime.timedelta(milliseconds=x)) + + def events(events: List[dict]): + """Converts a list of task events into a human readable format.""" + for event in events: + if "created_ms" in event: + event["created_ms"] = Humanify.timestamp(event["created_ms"]) + return events + + def node_resources(resources: dict): + """Converts a node's resources into a human readable format.""" + for resource in resources: + if "memory" in resource: + resources[resource] = Humanify.memory(resources[resource]) + return resources + + +@dataclass(init=not IS_PYDANTIC_2) +class ListApiOptions: + # Maximum number of entries to return + limit: int = DEFAULT_LIMIT + # The timeout for the API call. + timeout: int = DEFAULT_RPC_TIMEOUT + # If True, more detailed output will be printed. + # The API could query more sources than detail == False + # to get more data in detail. + detail: bool = False + # Filters. Each tuple pair (key, predicate, value) means key predicate value. + # If there's more than 1 filter, it means AND. + # E.g., [(key, "=", val), (key2, "!=" val2)] means (key=val) AND (key2!=val2) + filters: Optional[List[Tuple[str, PredicateType, SupportedFilterType]]] = field( + default_factory=list + ) + # [only tasks] If driver tasks should be excluded. + exclude_driver: bool = True + # When the request is processed on the server side, + # we should apply multiplier so that server side can finish + # processing a request within timeout. Otherwise, + # timeout will always lead Http timeout. + server_timeout_multiplier: float = 0.8 + + def __post_init__(self): + # To return the data to users, when there's a partial failure + # we need to have a timeout that's smaller than the users' timeout. + # 80% is configured arbitrarily. + self.timeout = int(self.timeout * self.server_timeout_multiplier) + assert self.timeout != 0, "0 second timeout is not supported." + if self.filters is None: + self.filters = [] + + for filter in self.filters: + _, filter_predicate, _ = filter + if filter_predicate != "=" and filter_predicate != "!=": + raise ValueError( + f"Unsupported filter predicate {filter_predicate} is given. " + "Available predicates: =, !=." + ) + + +@dataclass(init=not IS_PYDANTIC_2) +class GetApiOptions: + # Timeout for the HTTP request + timeout: int = DEFAULT_RPC_TIMEOUT + + +@dataclass(init=not IS_PYDANTIC_2) +class SummaryApiOptions: + # Timeout for the HTTP request + timeout: int = DEFAULT_RPC_TIMEOUT + + # Filters. Each tuple pair (key, predicate, value) means key predicate value. + # If there's more than 1 filter, it means AND. + # E.g., [(key, "=", val), (key2, "!=" val2)] means (key=val) AND (key2!=val2) + # For summary endpoints that call list under the hood, we'll pass + # these filters directly into the list call. + filters: Optional[List[Tuple[str, PredicateType, SupportedFilterType]]] = field( + default_factory=list + ) + + # Change out to summarize the output. There is a summary_by value for each entity. + # Tasks: by func_name + # Actors: by class + # Objects: by callsite + summary_by: Optional[str] = None + + +def state_column(*, filterable: bool, detail: bool = False, format_fn=None, **kwargs): + """A wrapper around dataclass.field to add additional metadata. + + The metadata is used to define detail / filterable option of + each column. + + Args: + detail: If True, the column is used when detail == True + filterable: If True, the column can be used for filtering. + kwargs: The same kwargs for the `dataclasses.field` function. + """ + m = {"detail": detail, "filterable": filterable, "format_fn": format_fn} + # Default for detail field is None since it could be missing. + if detail and "default" not in kwargs: + kwargs["default"] = None + + if "metadata" in kwargs: + # Metadata explicitly specified, so add detail and filterable if missing. + kwargs["metadata"].update(m) + else: + # Metadata not explicitly specified, so add it. + kwargs["metadata"] = m + return field(**kwargs) + + +class StateSchema(ABC): + """Schema class for Ray resource abstraction. + + The child class must be dataclass. All child classes + - perform runtime type checking upon initialization. + - are supposed to use `state_column` instead of `field`. + It will allow the class to return filterable/detail columns. + If `state_column` is not specified, that column is not filterable + and for non-detail output. + + For example, + ``` + @dataclass + class State(StateSchema): + column_a: str + column_b: int = state_column(detail=True, filterable=True) + + s = State(column_a="abc", b=1) + # Returns {"column_b"} + s.filterable_columns() + # Returns {"column_a"} + s.base_columns() + # Returns {"column_a", "column_b"} + s.columns() + ``` + + In addition, the schema also provides a humanify abstract method to + convert the state object into something human readable, ready for printing. + + Subclasses should override this method, providing logic to convert its own fields + to something human readable, packaged and returned in a dict. + + Each field that wants to be humanified should include a 'format_fn' key in its + metadata dictionary. + """ + + @classmethod + def humanify(cls, state: dict) -> dict: + """Convert the given state object into something human readable.""" + for f in fields(cls): + if ( + f.metadata.get("format_fn") is not None + and f.name in state + and state[f.name] is not None + ): + try: + state[f.name] = f.metadata["format_fn"](state[f.name]) + except Exception as e: + logger.error(f"Failed to format {f.name}:{state[f.name]} with {e}") + return state + + @classmethod + def list_columns(cls, detail: bool = True) -> List[str]: + """Return a list of columns.""" + cols = [] + for f in fields(cls): + if detail: + cols.append(f.name) + elif not f.metadata.get("detail", False): + cols.append(f.name) + + return cols + + @classmethod + def columns(cls) -> Set[str]: + """Return a set of all columns.""" + return set(cls.list_columns(detail=True)) + + @classmethod + def filterable_columns(cls) -> Set[str]: + """Return a list of filterable columns""" + filterable = set() + for f in fields(cls): + if f.metadata.get("filterable", False): + filterable.add(f.name) + return filterable + + @classmethod + def base_columns(cls) -> Set[str]: + """Return a list of base columns. + + Base columns mean columns to return when detail == False. + """ + return set(cls.list_columns(detail=False)) + + @classmethod + def detail_columns(cls) -> Set[str]: + """Return a list of detail columns. + + Detail columns mean columns to return when detail == True. + """ + return set(cls.list_columns(detail=True)) + + def asdict(self): + return asdict(self) + + # Allow dict like access on the class directly for backward compatibility. + def __getitem__(self, key): + return getattr(self, key) + + def __setitem__(self, key, value): + setattr(self, key, value) + + def get(self, key, default=None): + return getattr(self, key, default) + + +def filter_fields(data: dict, state_dataclass: StateSchema, detail: bool) -> dict: + """Filter the given data's columns based on the given schema. + + Args: + data: A single data entry to filter columns. + state_dataclass: The schema to filter data. + detail: Whether or not it should include columns for detail output. + """ + filtered_data = {} + columns = state_dataclass.columns() if detail else state_dataclass.base_columns() + for col in columns: + if col in data: + filtered_data[col] = data[col] + else: + filtered_data[col] = None + return filtered_data + + +@dataclass(init=not IS_PYDANTIC_2) +class GetLogOptions: + timeout: int + node_id: Optional[str] = None + node_ip: Optional[str] = None + # One of {file, stream}. File means it will return the whole log. + # stream means it will keep the connection and streaming the log. + media_type: str = "file" + # The file name of the log. + filename: Optional[str] = None + # The actor id of the log. It is used only for worker logs. + actor_id: Optional[str] = None + # The task id of the log. + task_id: Optional[str] = None + # The attempt number of the task. + attempt_number: int = 0 + # The pid of the log. It is used only for worker logs. + pid: Optional[int] = None + # Total log lines to return. + lines: int = 1000 + # The interval where new logs are streamed to. + # Should be used only when media_type == stream. + interval: Optional[float] = None + # The suffix of the log file if file resolution not through filename directly. + # Default to "out". + suffix: str = "out" + # The job submission id for submission job. This doesn't work for driver job + # since Ray doesn't log driver logs to file in the ray logs directory. + submission_id: Optional[str] = None + + def __post_init__(self): + if self.pid: + self.pid = int(self.pid) + if self.interval: + self.interval = float(self.interval) + self.lines = int(self.lines) + + if self.media_type == "file": + assert self.interval is None + if self.media_type not in ["file", "stream"]: + raise ValueError(f"Invalid media type: {self.media_type}") + if not (self.node_id or self.node_ip) and not (self.actor_id or self.task_id): + raise ValueError( + "node_id or node_ip must be provided as constructor arguments when no " + "actor or task_id is supplied as arguments." + ) + if self.node_id and self.node_ip: + raise ValueError( + "Both node_id and node_ip are given. Only one of them can be provided. " + f"Given node id: {self.node_id}, given node ip: {self.node_ip}" + ) + if not ( + self.actor_id + or self.task_id + or self.pid + or self.filename + or self.submission_id + ): + raise ValueError( + "None of actor_id, task_id, pid, submission_id or filename " + "is provided. At least one of them is required to fetch logs." + ) + + if self.suffix not in ["out", "err"]: + raise ValueError( + f"Invalid suffix: {self.suffix}. Must be one of 'out' or 'err'." + ) + + +# See the ActorTableData message in gcs.proto for all potential options that +# can be included in this class. +@dataclass(init=not IS_PYDANTIC_2) +class ActorState(StateSchema): + """Actor State""" + + #: The id of the actor. + actor_id: str = state_column(filterable=True) + #: The class name of the actor. + class_name: str = state_column(filterable=True) + #: The state of the actor. + #: + #: - DEPENDENCIES_UNREADY: Actor is waiting for dependency to be ready. + #: E.g., a new actor is waiting for object ref that's created from + #: other remote task. + #: - PENDING_CREATION: Actor's dependency is ready, but it is not created yet. + #: It could be because there are not enough resources, too many actor + #: entries in the scheduler queue, or the actor creation is slow + #: (e.g., slow runtime environment creation, + #: slow worker startup, or etc.). + #: - ALIVE: The actor is created, and it is alive. + #: - RESTARTING: The actor is dead, and it is restarting. + #: It is equivalent to `PENDING_CREATION`, + #: but means the actor was dead more than once. + #: - DEAD: The actor is permanatly dead. + state: TypeActorStatus = state_column(filterable=True) + #: The job id of this actor. + job_id: str = state_column(filterable=True) + #: The name of the actor given by the `name` argument. + name: Optional[str] = state_column(filterable=True) + #: The node id of this actor. + #: If the actor is restarting, it could be the node id + #: of the dead actor (and it will be re-updated when + #: the actor is successfully restarted). + node_id: Optional[str] = state_column(filterable=True) + #: The pid of the actor. 0 if it is not created yet. + pid: Optional[int] = state_column(filterable=True) + #: The namespace of the actor. + ray_namespace: Optional[str] = state_column(filterable=True) + #: The runtime environment information of the actor. + serialized_runtime_env: Optional[str] = state_column(filterable=False, detail=True) + #: The resource requirement of the actor. + required_resources: Optional[dict] = state_column(filterable=False, detail=True) + #: Actor's death information in detail. None if the actor is not dead yet. + death_cause: Optional[dict] = state_column(filterable=False, detail=True) + #: True if the actor is detached. False otherwise. + is_detached: Optional[bool] = state_column(filterable=False, detail=True) + #: The placement group id that's associated with this actor. + placement_group_id: Optional[str] = state_column(detail=True, filterable=True) + #: Actor's repr name if a customized __repr__ method exists, else empty string. + repr_name: Optional[str] = state_column(detail=True, filterable=True) + #: Number of restarts that has been tried on this actor. + num_restarts: int = state_column(filterable=False, detail=True) + #: Number of times this actor is restarted due to lineage reconstructions. + num_restarts_due_to_lineage_reconstruction: int = state_column( + filterable=False, detail=True + ) + + +@dataclass(init=not IS_PYDANTIC_2) +class PlacementGroupState(StateSchema): + """PlacementGroup State""" + + #: The id of the placement group. + placement_group_id: str = state_column(filterable=True) + #: The name of the placement group if it is given by the name argument. + name: str = state_column(filterable=True) + #: The job id of the placement group. + creator_job_id: str = state_column(filterable=True) + #: The state of the placement group. + #: + #: - PENDING: The placement group creation is pending scheduling. + #: It could be because there's not enough resources, some of creation + #: stage has failed (e.g., failed to commit placement gropus because + #: the node is dead). + #: - CREATED: The placement group is created. + #: - REMOVED: The placement group is removed. + #: - RESCHEDULING: The placement group is rescheduling because some of + #: bundles are dead because they were on dead nodes. + state: TypePlacementGroupStatus = state_column(filterable=True) + #: The bundle specification of the placement group. + bundles: Optional[List[dict]] = state_column(filterable=False, detail=True) + #: True if the placement group is detached. False otherwise. + is_detached: Optional[bool] = state_column(filterable=True, detail=True) + #: The scheduling stats of the placement group. + stats: Optional[dict] = state_column(filterable=False, detail=True) + + +@dataclass(init=not IS_PYDANTIC_2) +class NodeState(StateSchema): + """Node State""" + + #: The id of the node. + node_id: str = state_column(filterable=True) + #: The ip address of the node. + node_ip: str = state_column(filterable=True) + #: If this is a head node. + is_head_node: bool = state_column(filterable=True) + #: The state of the node. + #: + #: ALIVE: The node is alive. + #: DEAD: The node is dead. + state: TypeNodeStatus = state_column(filterable=True) + #: The state message of the node. + #: This provides more detailed information about the node's state. + state_message: Optional[str] = state_column(filterable=False) + #: The name of the node if it is given by the name argument. + node_name: str = state_column(filterable=True) + #: The total resources of the node. + resources_total: dict = state_column( + filterable=False, format_fn=Humanify.node_resources + ) + #: The labels of the node. + labels: dict = state_column(filterable=False) + #: The time when the node (raylet) starts. + start_time_ms: Optional[int] = state_column( + filterable=False, detail=True, format_fn=Humanify.timestamp + ) + #: The time when the node exits. The timestamp could be delayed + #: if the node is dead unexpectedly (could be delayed + # up to 30 seconds). + end_time_ms: Optional[int] = state_column( + filterable=False, detail=True, format_fn=Humanify.timestamp + ) + + +# NOTE: Declaring this as dataclass would make __init__ not being called properly. +# NOTE: `JobDetails` will be `None` in the minimal install because Pydantic is not +# installed. Inheriting from `None` raises an exception. +class JobState(StateSchema, JobDetails if JobDetails is not None else object): + """The state of the job that's submitted by Ray's Job APIs or driver jobs""" + + def __init__(self, **kwargs): + JobDetails.__init__(self, **kwargs) + + @classmethod + def filterable_columns(cls) -> Set[str]: + # We are not doing any filtering since filtering is currently done + # at the backend. + return {"job_id", "type", "status", "submission_id"} + + @classmethod + def humanify(cls, state: dict) -> dict: + return state + + @classmethod + def list_columns(cls, detail: bool = True) -> List[str]: + if not detail: + return [ + "job_id", + "submission_id", + "entrypoint", + "type", + "status", + "message", + "error_type", + "driver_info", + ] + if JobDetails is None: + # We don't have pydantic in the dashboard. This is because + # we call this method at module import time, so we need to + # check if the class is a pydantic model. + return [] + + # 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`. + return ( + list(JobDetails.model_fields.keys()) + if hasattr(JobDetails, "model_fields") + else list(JobDetails.__fields__.keys()) + ) + + def asdict(self): + return JobDetails.dict(self) + + @classmethod + def schema_dict(cls) -> Dict[str, Any]: + schema_types = cls.schema()["properties"] + # Get type name to actual type mapping. + return { + k: v["type"] for k, v in schema_types.items() if v.get("type") is not None + } + + +@dataclass(init=not IS_PYDANTIC_2) +class WorkerState(StateSchema): + """Worker State""" + + #: The id of the worker. + worker_id: str = state_column(filterable=True) + #: Whether or not if the worker is alive. + is_alive: bool = state_column(filterable=True) + #: The type of the worker. + #: + #: - WORKER: The regular Ray worker process that executes tasks or + # instantiates an actor. + #: - DRIVER: The driver (Python script that calls `ray.init`). + #: - SPILL_WORKER: The worker that spills objects. + #: - RESTORE_WORKER: The worker that restores objects. + worker_type: TypeWorkerType = state_column(filterable=True) + #: The exit type of the worker if the worker is dead. + #: + #: - SYSTEM_ERROR: Worker exit due to system level failures (i.e. worker crash). + #: - INTENDED_SYSTEM_EXIT: System-level exit that is intended. E.g., + #: Workers are killed because they are idle for a long time. + #: - USER_ERROR: Worker exits because of user error. + #: E.g., execptions from the actor initialization. + #: - INTENDED_USER_EXIT: Intended exit from users (e.g., users exit + #: workers with exit code 0 or exit initated by Ray API such as ray.kill). + exit_type: Optional[TypeWorkerExitType] = state_column(filterable=True) + #: The node id of the worker. + node_id: str = state_column(filterable=True) + #: The ip address of the worker. + ip: str = state_column(filterable=True) + #: The pid of the worker. + pid: int = state_column(filterable=True) + #: The exit detail of the worker if the worker is dead. + exit_detail: Optional[str] = state_column(detail=True, filterable=False) + #: The time worker is first launched. + #: -1 if the value doesn't exist. + #: The lifecycle of worker is as follow. + #: worker_launch_time_ms (process startup requested). + #: -> worker_launched_time_ms (process started). + #: -> start_time_ms (worker is ready to be used). + #: -> end_time_ms (worker is destroyed). + worker_launch_time_ms: Optional[int] = state_column( + filterable=False, + detail=True, + format_fn=lambda x: "" if x == -1 else Humanify.timestamp(x), + ) + #: The time worker is succesfully launched + #: -1 if the value doesn't exist. + worker_launched_time_ms: Optional[int] = state_column( + filterable=False, + detail=True, + format_fn=lambda x: "" if x == -1 else Humanify.timestamp(x), + ) + #: The time when the worker is started and initialized. + #: 0 if the value doesn't exist. + start_time_ms: Optional[int] = state_column( + filterable=False, detail=True, format_fn=Humanify.timestamp + ) + #: The time when the worker exits. The timestamp could be delayed + #: if the worker is dead unexpectedly. + #: 0 if the value doesn't exist. + end_time_ms: Optional[int] = state_column( + filterable=False, detail=True, format_fn=Humanify.timestamp + ) + # the debugger port of the worker + debugger_port: Optional[int] = state_column(filterable=True, detail=True) + # the number of threads paused in this worker + num_paused_threads: Optional[int] = state_column(filterable=True, detail=True) + + +@dataclass(init=not IS_PYDANTIC_2) +class ClusterEventState(StateSchema): + severity: str = state_column(filterable=True) + time: str = state_column(filterable=False) + source_type: str = state_column(filterable=True) + message: str = state_column(filterable=False) + event_id: str = state_column(filterable=True) + custom_fields: Optional[dict] = state_column(filterable=False, detail=True) + + +@dataclass(init=not IS_PYDANTIC_2) +class TaskState(StateSchema): + """Task State""" + + #: The id of the task. + task_id: str = state_column(filterable=True) + #: The attempt (retry) number of the task. + attempt_number: int = state_column(filterable=True) + #: The name of the task if it is given by the name argument. + name: str = state_column(filterable=True) + #: The state of the task. + #: + #: Refer to src/ray/protobuf/common.proto for a detailed explanation of the state + #: breakdowns and typical state transition flow. + #: + state: TypeTaskStatus = state_column(filterable=True) + #: The job id of this task. + job_id: str = state_column(filterable=True) + #: The actor id that's associated with this task. + #: It is empty if there's no relevant actors. + actor_id: Optional[str] = state_column(filterable=True) + #: The type of the task. + #: + #: - NORMAL_TASK: Tasks created by `func.remote()`` + #: - ACTOR_CREATION_TASK: Actors created by `class.remote()` + #: - ACTOR_TASK: Actor tasks submitted by `actor.method.remote()` + #: - DRIVER_TASK: Driver (A script that calls `ray.init`). + type: TypeTaskType = state_column(filterable=True) + #: The name of the task. If is the name of the function + #: if the type is a task or an actor task. + #: It is the name of the class if it is a actor scheduling task. + func_or_class_name: str = state_column(filterable=True) + #: The parent task id. If the parent is a normal task, it will be the task's id. + #: If the parent runs in a concurrent actor (async actor or threaded actor), + #: it will be the actor's creation task id. + parent_task_id: str = state_column(filterable=True) + #: Id of the node that runs the task. If the task is retried, it could + #: contain the node id of the previous executed task. + #: If empty, it means the task hasn't been scheduled yet. + node_id: Optional[str] = state_column(filterable=True) + #: The worker id that's associated with this task. + worker_id: Optional[str] = state_column(filterable=True) + #: The worker's pid that's associated with this task. + worker_pid: Optional[int] = state_column(filterable=True) + #: Task error type. + error_type: Optional[str] = state_column(filterable=True) + #: The language of the task. E.g., Python, Java, or Cpp. + language: Optional[str] = state_column(detail=True, filterable=True) + #: The required resources to execute the task. + required_resources: Optional[dict] = state_column(detail=True, filterable=False) + #: The runtime environment information for the task. + runtime_env_info: Optional[dict] = state_column(detail=True, filterable=False) + #: The placement group id that's associated with this task. + placement_group_id: Optional[str] = state_column(detail=True, filterable=True) + #: The list of events of the given task. + #: Refer to src/ray/protobuf/common.proto for a detailed explanation of the state + #: breakdowns and typical state transition flow. + events: Optional[List[dict]] = state_column( + detail=True, filterable=False, format_fn=Humanify.events + ) + #: The list of profile events of the given task. + profiling_data: Optional[dict] = state_column(detail=True, filterable=False) + #: The time when the task is created. A Unix timestamp in ms. + creation_time_ms: Optional[int] = state_column( + detail=True, + filterable=False, + format_fn=Humanify.timestamp, + ) + #: The time when the task starts to run. A Unix timestamp in ms. + start_time_ms: Optional[int] = state_column( + detail=True, + filterable=False, + format_fn=Humanify.timestamp, + ) + #: The time when the task is finished or failed. A Unix timestamp in ms. + end_time_ms: Optional[int] = state_column( + detail=True, filterable=False, format_fn=Humanify.timestamp + ) + #: The task logs info, e.g. offset into the worker log file when the task + #: starts/finishes. + #: None if the task is from a concurrent actor (e.g. async actor or threaded actor) + task_log_info: Optional[dict] = state_column(detail=True, filterable=False) + #: Task error detail info. + error_message: Optional[str] = state_column(detail=True, filterable=False) + # Is task paused by the debugger + is_debugger_paused: Optional[bool] = state_column(detail=True, filterable=True) + + +@dataclass(init=not IS_PYDANTIC_2) +class ObjectState(StateSchema): + """Object State""" + + #: The id of the object. + object_id: str = state_column(filterable=True) + #: The size of the object in mb. + object_size: int = state_column(filterable=True, format_fn=Humanify.memory) + #: The status of the task that creates the object. + #: + #: - NIL: We don't have a status for this task because we are not the owner or the + #: task metadata has already been deleted. + #: - WAITING_FOR_DEPENDENCIES: The task is waiting for its dependencies + #: to be created. + #: - SCHEDULED: All dependencies have been created and the task is + #: scheduled to execute. + #: It could be because the task is waiting for resources, + #: runtime environmenet creation, fetching dependencies to the + #: local node, and etc.. + #: - FINISHED: The task finished successfully. + #: - WAITING_FOR_EXECUTION: The task is scheduled properly and + #: waiting for execution. It includes time to deliver the task + #: to the remote worker + queueing time from the execution side. + #: - RUNNING: The task that is running. + task_status: TypeTaskStatus = state_column(filterable=True) + #: The number of times the task has been executed (including the current execution) + attempt_number: int = state_column(filterable=True) + #: The reference type of the object. + #: See :ref:`Debugging with Ray Memory ` for more details. + #: + #: - ACTOR_HANDLE: The reference is an actor handle. + #: - PINNED_IN_MEMORY: The object is pinned in memory, meaning there's + #: in-flight `ray.get` on this reference. + #: - LOCAL_REFERENCE: There's a local reference (e.g., Python reference) + #: to this object reference. The object won't be GC'ed until all of them is gone. + #: - USED_BY_PENDING_TASK: The object reference is passed to other tasks. E.g., + #: `a = ray.put()` -> `task.remote(a)`. In this case, a is used by a + #: pending task `task`. + #: - CAPTURED_IN_OBJECT: The object is serialized by other objects. E.g., + #: `a = ray.put(1)` -> `b = ray.put([a])`. a is serialized within a list. + #: - UNKNOWN_STATUS: The object ref status is unkonwn. + reference_type: TypeReferenceType = state_column(filterable=True) + #: The callsite of the object. + call_site: str = state_column(filterable=True) + #: The worker type that creates the object. + #: + #: - WORKER: The regular Ray worker process that executes tasks or + #: instantiates an actor. + #: - DRIVER: The driver (Python script that calls `ray.init`). + #: - SPILL_WORKER: The worker that spills objects. + #: - RESTORE_WORKER: The worker that restores objects. + type: TypeWorkerType = state_column(filterable=True) + #: The pid of the owner. + pid: int = state_column(filterable=True) + #: The ip address of the owner. + ip: str = state_column(filterable=True) + + +@dataclass(init=not IS_PYDANTIC_2) +class RuntimeEnvState(StateSchema): + """Runtime Environment State""" + + #: The runtime environment spec. + runtime_env: dict = state_column(filterable=True) + #: Whether or not the runtime env creation has succeeded. + success: bool = state_column(filterable=True) + #: The latency of creating the runtime environment. + #: Available if the runtime env is successfully created. + creation_time_ms: Optional[float] = state_column( + filterable=False, format_fn=Humanify.timestamp + ) + #: The node id of this runtime environment. + node_id: str = state_column(filterable=True) + #: The number of actors and tasks that use this runtime environment. + ref_cnt: Optional[int] = state_column(detail=True, filterable=False) + #: The error message if the runtime environment creation has failed. + #: Available if the runtime env is failed to be created. + error: Optional[str] = state_column(detail=True, filterable=True) + + +AVAILABLE_STATES = [ + ActorState, + PlacementGroupState, + NodeState, + WorkerState, + JobState, + TaskState, + ObjectState, + RuntimeEnvState, +] + + +for state in AVAILABLE_STATES: + if len(state.filterable_columns()) > 0: + filterable_cols = "\n\n ".join(state.filterable_columns()) + state.__doc__ += f""" +\nBelow columns can be used for the `--filter` option. +\n + {filterable_cols} +\n +""" + + if len(state.detail_columns()) > 0: + detail_cols = "\n\n ".join(state.detail_columns()) + state.__doc__ += f""" +\nBelow columns are available only when `get` API is used, +\n`--detail` is specified through CLI, or `detail=True` is given to Python APIs. +\n +\n + {detail_cols} +\n +""" + + +@dataclass(init=not IS_PYDANTIC_2) +class ListApiResponse: + # NOTE(rickyyx): We currently perform hard truncation when querying + # resources which could have a large number (e.g. asking raylets for + # the number of all objects). + # The returned of resources seen by the user will go through from the + # below funnel: + # - total + # | With truncation at the data source if the number of returned + # | resource exceeds `RAY_MAX_LIMIT_FROM_DATA_SOURCE` + # v + # - num_after_truncation + # | With filtering at the state API server + # v + # - num_filtered + # | With limiting, + # | set by min(`RAY_MAX_LIMIT_FROM_API_SERER`, ) + # v + # - len(result) + + # Total number of the available resource from the cluster. + total: int + # Number of resources returned by data sources after truncation + num_after_truncation: int + # Number of resources after filtering + num_filtered: int + # Returned data. None if no data is returned. + result: List[Dict] + # List API can have a partial failure if queries to + # all sources fail. For example, getting object states + # require to ping all raylets, and it is possible some of + # them fails. Note that it is impossible to guarantee high + # availability of data because ray's state information is + # not replicated. + partial_failure_warning: Optional[str] = "" + # A list of warnings to print. + warnings: Optional[List[str]] = None + + +""" +Summary API schema +""" + +DRIVER_TASK_ID_PREFIX = "ffffffffffffffffffffffffffffffffffffffff" + + +@dataclass(init=not IS_PYDANTIC_2) +class TaskSummaryPerFuncOrClassName: + #: The function or class name of this task. + func_or_class_name: str + #: The type of the class. Equivalent to protobuf TaskType. + type: str + #: State name to the count dict. State name is equivalent to + #: the protobuf TaskStatus. + state_counts: Dict[TypeTaskStatus, int] = field(default_factory=dict) + + +@dataclass +class Link: + #: The type of entity to link to + type: str + #: The id of the entity to link to + id: str + + +@dataclass(init=not IS_PYDANTIC_2) +class NestedTaskSummary: + #: The name of this task group + name: str + #: A unique identifier for this group + key: str + #: The type of the class. Equivalent to protobuf TaskType, + #: "ACTOR" if it represents an Actor, or "GROUP" if it's a grouping of tasks. + type: str + #: Unix timestamp to use to sort the task group. + timestamp: Optional[int] = None + #: State name to the count dict. State name is equivalent to + #: the protobuf TaskStatus. + state_counts: Dict[TypeTaskStatus, int] = field(default_factory=dict) + #: The child + children: List["NestedTaskSummary"] = field(default_factory=list) + #: A link to more details about this summary. + link: Optional[Link] = None + + +@dataclass +class TaskSummaries: + #: Group key -> summary. + #: Right now, we only have func_class_name as a key. + # TODO(sang): Support the task group abstraction. + summary: Union[Dict[str, TaskSummaryPerFuncOrClassName], List[NestedTaskSummary]] + #: Total Ray tasks. + total_tasks: int + #: Total actor tasks. + total_actor_tasks: int + #: Total scheduled actors. + total_actor_scheduled: int + summary_by: str = "func_name" + + @classmethod + def to_summary_by_func_name(cls, *, tasks: List[Dict]) -> "TaskSummaries": + # NOTE: The argument tasks contains a list of dictionary + # that have the same k/v as TaskState. + summary = {} + total_tasks = 0 + total_actor_tasks = 0 + total_actor_scheduled = 0 + + for task in tasks: + key = task["func_or_class_name"] + if key not in summary: + summary[key] = TaskSummaryPerFuncOrClassName( + func_or_class_name=task["func_or_class_name"], + type=task["type"], + ) + task_summary = summary[key] + + state = task["state"] + if state not in task_summary.state_counts: + task_summary.state_counts[state] = 0 + task_summary.state_counts[state] += 1 + + type_enum = TaskType.DESCRIPTOR.values_by_name[task["type"]].number + if type_enum == TaskType.NORMAL_TASK: + total_tasks += 1 + elif type_enum == TaskType.ACTOR_CREATION_TASK: + total_actor_scheduled += 1 + elif type_enum == TaskType.ACTOR_TASK: + total_actor_tasks += 1 + + return TaskSummaries( + summary=summary, + total_tasks=total_tasks, + total_actor_tasks=total_actor_tasks, + total_actor_scheduled=total_actor_scheduled, + summary_by="func_name", + ) + + @classmethod + def to_summary_by_lineage( + cls, *, tasks: List[Dict], actors: List[Dict] + ) -> "TaskSummaries": + """ + This summarizes tasks by lineage. + i.e. A task will be grouped with another task if they have the + same parent. + + This does things in 4 steps. + Step 1: Iterate through all tasks and keep track of them by id and ownership + Step 2: Put the tasks in a tree structure based on ownership + Step 3: Merge together siblings in the tree if there are more + than one with the same name. + Step 4: Sort by running and then errored and then successful tasks + Step 5: Total the children + + This can probably be more efficient if we merge together some steps to + reduce the amount of iterations but this algorithm produces very easy to + understand code. We can optimize in the future. + """ + # NOTE: The argument tasks contains a list of dictionary + # that have the same k/v as TaskState. + + tasks_by_id = {} + task_group_by_id = {} + actor_creation_task_id_for_actor_id = {} + summary = [] + total_tasks = 0 + total_actor_tasks = 0 + total_actor_scheduled = 0 + + # Step 1 + # We cannot assume that a parent task always comes before the child task + # So we need to keep track of all tasks by ids so we can quickly find the + # parent. + # We also track the actor creation tasks so we can quickly figure out the + # ownership of actors. + for task in tasks: + tasks_by_id[task["task_id"]] = task + type_enum = TaskType.DESCRIPTOR.values_by_name[task["type"]].number + if type_enum == TaskType.ACTOR_CREATION_TASK: + actor_creation_task_id_for_actor_id[task["actor_id"]] = task["task_id"] + + actor_dict = {actor["actor_id"]: actor for actor in actors} + + def get_or_create_task_group(task_id: str) -> Optional[NestedTaskSummary]: + """ + Gets an already created task_group + OR + Creates a task group and puts it in the right place under its parent. + For actor tasks, the parent is the Actor that owns it. For all other + tasks, the owner is the driver or task that created it. + + Returns None if there is missing data about the task or one of its parents. + + For task groups that represents actors, the id is in the + format actor:{actor_id} + """ + if task_id in task_group_by_id: + return task_group_by_id[task_id] + + task = tasks_by_id.get(task_id) + if not task: + logger.debug(f"We're missing data about {task_id}") + # We're missing data about this parent. So we're dropping the whole + # tree at that node. + return None + + # Use name first which allows users to customize the name of + # their remote function call using the name option. + func_name = task["name"] or task["func_or_class_name"] + task_id = task["task_id"] + type_enum = TaskType.DESCRIPTOR.values_by_name[task["type"]].number + + task_group_by_id[task_id] = NestedTaskSummary( + name=func_name, + key=task_id, + type=task["type"], + timestamp=task["creation_time_ms"], + link=Link(type="task", id=task_id), + ) + + # Set summary in right place under parent + if ( + type_enum == TaskType.ACTOR_TASK + or type_enum == TaskType.ACTOR_CREATION_TASK + ): + # For actor tasks, the parent is the actor and not the parent task. + parent_task_group = get_or_create_actor_task_group(task["actor_id"]) + if parent_task_group: + parent_task_group.children.append(task_group_by_id[task_id]) + else: + parent_task_id = task["parent_task_id"] + if not parent_task_id or parent_task_id.startswith( + DRIVER_TASK_ID_PREFIX + ): + summary.append(task_group_by_id[task_id]) + else: + parent_task_group = get_or_create_task_group(parent_task_id) + if parent_task_group: + parent_task_group.children.append(task_group_by_id[task_id]) + + return task_group_by_id[task_id] + + def get_or_create_actor_task_group( + actor_id: str, + ) -> Optional[NestedTaskSummary]: + """ + Gets an existing task group that represents an actor. + OR + Creates a task group that represents an actor. The owner of the actor is + the parent of the creation_task that created that actor. + + Returns None if there is missing data about the actor or one of its parents. + """ + key = f"actor:{actor_id}" + actor = actor_dict.get(actor_id) + if key not in task_group_by_id: + creation_task_id = actor_creation_task_id_for_actor_id.get(actor_id) + creation_task = tasks_by_id.get(creation_task_id) + + if not creation_task: + logger.debug(f"We're missing data about actor {actor_id}") + # We're missing data about the parent. So we're dropping the whole + # tree at that node. + return None + + # TODO(rickyx) + # We are using repr name for grouping actors if exists, + # else use class name. We should be using some group_name in the future. + if actor is None: + logger.debug( + f"We are missing actor info for actor {actor_id}, " + f"even though creation task exists: {creation_task}" + ) + [actor_name, *rest] = creation_task["func_or_class_name"].split(".") + else: + actor_name = ( + actor["repr_name"] + if actor["repr_name"] + else actor["class_name"] + ) + + task_group_by_id[key] = NestedTaskSummary( + name=actor_name, + key=key, + type="ACTOR", + timestamp=task["creation_time_ms"], + link=Link(type="actor", id=actor_id), + ) + + parent_task_id = creation_task["parent_task_id"] + if not parent_task_id or parent_task_id.startswith( + DRIVER_TASK_ID_PREFIX + ): + summary.append(task_group_by_id[key]) + else: + parent_task_group = get_or_create_task_group(parent_task_id) + if parent_task_group: + parent_task_group.children.append(task_group_by_id[key]) + + return task_group_by_id[key] + + # Step 2: Create the tree structure based on ownership + for task in tasks: + task_id = task["task_id"] + + task_group = get_or_create_task_group(task_id) + + if not task_group: + # We are probably missing data about this task or one of its parents. + continue + + state = task["state"] + if state not in task_group.state_counts: + task_group.state_counts[state] = 0 + task_group.state_counts[state] += 1 + + type_enum = TaskType.DESCRIPTOR.values_by_name[task["type"]].number + if type_enum == TaskType.NORMAL_TASK: + total_tasks += 1 + elif type_enum == TaskType.ACTOR_CREATION_TASK: + total_actor_scheduled += 1 + elif type_enum == TaskType.ACTOR_TASK: + total_actor_tasks += 1 + + def merge_sibings_for_task_group( + siblings: List[NestedTaskSummary], + ) -> Tuple[List[NestedTaskSummary], Optional[int]]: + """ + Merges task summaries with the same name into a group if there are more than + one child with that name. + + Args: + siblings: A list of NestedTaskSummary's to merge together + + Returns + Index 0: A list of NestedTaskSummary's which have been merged + Index 1: The smallest timestamp amongst the siblings + """ + if not len(siblings): + return siblings, None + + # Group by name + groups = {} + min_timestamp = None + + for child in siblings: + child.children, child_min_timestamp = merge_sibings_for_task_group( + child.children + ) + if child_min_timestamp and child_min_timestamp < ( + child.timestamp or sys.maxsize + ): + child.timestamp = child_min_timestamp + + if child.name not in groups: + groups[child.name] = NestedTaskSummary( + name=child.name, + key=child.name, + type="GROUP", + ) + groups[child.name].children.append(child) + if child.timestamp and child.timestamp < ( + groups[child.name].timestamp or sys.maxsize + ): + groups[child.name].timestamp = child.timestamp + if child.timestamp < (min_timestamp or sys.maxsize): + min_timestamp = child.timestamp + + # Take the groups that have more than one children and return it. + # For groups with just one child, return the child itself instead of + # creating a group. + return [ + group if len(group.children) > 1 else group.children[0] + for group in groups.values() + ], min_timestamp + + # Step 3 + summary, _ = merge_sibings_for_task_group(summary) + + def get_running_tasks_count(task_group: NestedTaskSummary) -> int: + return ( + task_group.state_counts.get("RUNNING", 0) + + task_group.state_counts.get("RUNNING_IN_RAY_GET", 0) + + task_group.state_counts.get("RUNNING_IN_RAY_WAIT", 0) + ) + + def get_pending_tasks_count(task_group: NestedTaskSummary) -> int: + return ( + task_group.state_counts.get("PENDING_ARGS_AVAIL", 0) + + task_group.state_counts.get("PENDING_NODE_ASSIGNMENT", 0) + + task_group.state_counts.get("PENDING_OBJ_STORE_MEM_AVAIL", 0) + + task_group.state_counts.get("PENDING_ARGS_FETCH", 0) + ) + + def sort_task_groups(task_groups: List[NestedTaskSummary]) -> None: + # Sort by running tasks, pending tasks, failed tasks, timestamp, + # and actor_creation_task + # Put actor creation tasks above other tasks with the same timestamp + task_groups.sort(key=lambda x: 0 if x.type == "ACTOR_CREATION_TASK" else 1) + task_groups.sort(key=lambda x: x.timestamp or sys.maxsize) + task_groups.sort( + key=lambda x: x.state_counts.get("FAIELD", 0), reverse=True + ) + task_groups.sort(key=get_pending_tasks_count, reverse=True) + task_groups.sort(key=get_running_tasks_count, reverse=True) + + def calc_total_for_task_group( + task_group: NestedTaskSummary, + ) -> NestedTaskSummary: + """ + Calculates the total of a group as the sum of all children. + Sorts children by timestamp + """ + if not len(task_group.children): + return task_group + + for child in task_group.children: + totaled = calc_total_for_task_group(child) + + for state, count in totaled.state_counts.items(): + task_group.state_counts[state] = ( + task_group.state_counts.get(state, 0) + count + ) + + sort_task_groups(task_group.children) + + return task_group + + # Step 4 + summary = [calc_total_for_task_group(task_group) for task_group in summary] + sort_task_groups(summary) + + return TaskSummaries( + summary=summary, + total_tasks=total_tasks, + total_actor_tasks=total_actor_tasks, + total_actor_scheduled=total_actor_scheduled, + summary_by="lineage", + ) + + +@dataclass(init=not IS_PYDANTIC_2) +class ActorSummaryPerClass: + #: The class name of the actor. + class_name: str + #: State name to the count dict. State name is equivalent to + #: the protobuf ActorState. + state_counts: Dict[TypeActorStatus, int] = field(default_factory=dict) + + +@dataclass +class ActorSummaries: + #: Group key (actor class name) -> summary + summary: Dict[str, ActorSummaryPerClass] + #: Total number of actors + total_actors: int + summary_by: str = "class" + + @classmethod + def to_summary(cls, *, actors: List[Dict]): + # NOTE: The argument tasks contains a list of dictionary + # that have the same k/v as ActorState. + summary = {} + total_actors = 0 + + for actor in actors: + key = actor["class_name"] + if key not in summary: + summary[key] = ActorSummaryPerClass( + class_name=actor["class_name"], + ) + actor_summary = summary[key] + + state = actor["state"] + if state not in actor_summary.state_counts: + actor_summary.state_counts[state] = 0 + actor_summary.state_counts[state] += 1 + + total_actors += 1 + + return ActorSummaries( + summary=summary, + total_actors=total_actors, + ) + + +@dataclass(init=not IS_PYDANTIC_2) +class ObjectSummaryPerKey: + #: Total number of objects of the type. + total_objects: int + #: Total size in mb. + total_size_mb: float + #: Total number of workers that reference the type of objects. + total_num_workers: int + #: Total number of nodes that reference the type of objects. + total_num_nodes: int + #: State name to the count dict. State name is equivalent to + #: ObjectState. + task_state_counts: Dict[TypeTaskStatus, int] = field(default_factory=dict) + #: Attempt number to the count dict. The attempt number include the current + #: execution + task_attempt_number_counts: Dict[str, int] = field(default_factory=dict) + #: Ref count type to the count dict. State name is equivalent to + #: ObjectState. + ref_type_counts: Dict[TypeReferenceType, int] = field(default_factory=dict) + + +@dataclass +class ObjectSummaries: + #: Group key (actor class name) -> summary + summary: Dict[str, ObjectSummaryPerKey] + #: Total number of referenced objects in the cluster. + total_objects: int + #: Total size of referenced objects in the cluster in MB. + total_size_mb: float + #: Whether or not the callsite collection is enabled. + callsite_enabled: bool + summary_by: str = "callsite" + + @classmethod + def to_summary(cls, *, objects: List[Dict]): + # NOTE: The argument tasks contains a list of dictionary + # that have the same k/v as ObjectState. + summary = {} + total_objects = 0 + total_size_mb = 0 + key_to_workers = {} + key_to_nodes = {} + callsite_enabled = True + + for object in objects: + key = object["call_site"] + if key == "disabled": + callsite_enabled = False + if key not in summary: + summary[key] = ObjectSummaryPerKey( + total_objects=0, + total_size_mb=0, + total_num_workers=0, + total_num_nodes=0, + ) + key_to_workers[key] = set() + key_to_nodes[key] = set() + + object_summary = summary[key] + + task_state = object["task_status"] + if task_state not in object_summary.task_state_counts: + object_summary.task_state_counts[task_state] = 0 + object_summary.task_state_counts[task_state] += 1 + + attempt_number = str(object["attempt_number"]) + if attempt_number not in object_summary.task_attempt_number_counts: + object_summary.task_attempt_number_counts[attempt_number] = 0 + object_summary.task_attempt_number_counts[attempt_number] += 1 + + ref_type = object["reference_type"] + if ref_type not in object_summary.ref_type_counts: + object_summary.ref_type_counts[ref_type] = 0 + object_summary.ref_type_counts[ref_type] += 1 + object_summary.total_objects += 1 + total_objects += 1 + + size_bytes = object["object_size"] + # object_size's unit is byte by default. It is -1, if the size is + # unknown. + if size_bytes != -1: + object_summary.total_size_mb += size_bytes / 1024**2 + total_size_mb += size_bytes / 1024**2 + + key_to_workers[key].add(object["pid"]) + key_to_nodes[key].add(object["ip"]) + + # Convert set of pid & node ips to length. + for key, workers in key_to_workers.items(): + summary[key].total_num_workers = len(workers) + for key, nodes in key_to_nodes.items(): + summary[key].total_num_nodes = len(nodes) + + return ObjectSummaries( + summary=summary, + total_objects=total_objects, + total_size_mb=total_size_mb, + callsite_enabled=callsite_enabled, + ) + + +@dataclass(init=not IS_PYDANTIC_2) +class StateSummary: + #: Node ID -> summary per node + #: If the data is not required to be orgnized per node, it will contain + #: a single key, "cluster". + node_id_to_summary: Dict[str, Union[TaskSummaries, ActorSummaries, ObjectSummaries]] + + +@dataclass(init=not IS_PYDANTIC_2) +class SummaryApiResponse: + # Carried over from ListApiResponse + # We currently use list API for listing the resources + total: int + # Carried over from ListApiResponse + # Number of resources returned by data sources after truncation + num_after_truncation: int + # Number of resources after filtering + num_filtered: int + result: StateSummary = None + partial_failure_warning: Optional[str] = "" + # A list of warnings to print. + warnings: Optional[List[str]] = None + + +def resource_to_schema(resource: StateResource) -> StateSchema: + if resource == StateResource.ACTORS: + return ActorState + elif resource == StateResource.JOBS: + return JobState + elif resource == StateResource.NODES: + return NodeState + elif resource == StateResource.OBJECTS: + return ObjectState + elif resource == StateResource.PLACEMENT_GROUPS: + return PlacementGroupState + elif resource == StateResource.RUNTIME_ENVS: + return RuntimeEnvState + elif resource == StateResource.TASKS: + return TaskState + elif resource == StateResource.WORKERS: + return WorkerState + elif resource == StateResource.CLUSTER_EVENTS: + return ClusterEventState + else: + assert False, "Unreachable" + + +def protobuf_message_to_dict( + message, + fields_to_decode: List[str], + preserving_proto_field_name: bool = True, +) -> dict: + """Convert a protobuf message to dict + + Args: + fields_to_decode: field names which will be decoded from binary to hex. + preserving_proto_field_name: a pass-through option for protobuf message + method. See google.protobuf MessageToDict + + Return: + Dictionary of the converted rpc protobuf. + """ + return dashboard_utils.message_to_dict( + message, + fields_to_decode, + always_print_fields_with_no_presence=True, + preserving_proto_field_name=preserving_proto_field_name, + ) + + +def protobuf_to_task_state_dict(message: TaskEvents) -> dict: + """ + Convert a TaskEvents to a dic repr of `TaskState` + """ + task_attempt = protobuf_message_to_dict( + message=message, + fields_to_decode=[ + "task_id", + "job_id", + "node_id", + "actor_id", + "parent_task_id", + "worker_id", + "placement_group_id", + "component_id", + ], + ) + + task_state = {} + task_info = task_attempt.get("task_info", {}) + state_updates = task_attempt.get("state_updates", {}) + profiling_data = task_attempt.get("profile_events", {}) + if profiling_data: + for event in profiling_data["events"]: + # End/start times are recorded in ns. We convert them to ms. + event["end_time"] = int(event["end_time"]) / 1e6 + event["start_time"] = int(event["start_time"]) / 1e6 + event["extra_data"] = json.loads(event["extra_data"]) + task_state["profiling_data"] = profiling_data + + # Convert those settable fields + mappings = [ + ( + task_info, + [ + "task_id", + "name", + "actor_id", + "type", + "func_or_class_name", + "language", + "required_resources", + "runtime_env_info", + "parent_task_id", + "placement_group_id", + ], + ), + (task_attempt, ["task_id", "attempt_number", "job_id"]), + ( + state_updates, + [ + "node_id", + "worker_id", + "task_log_info", + "actor_repr_name", + "worker_pid", + "is_debugger_paused", + ], + ), + ] + for src, keys in mappings: + for key in keys: + task_state[key] = src.get(key) + + task_state["creation_time_ms"] = None + task_state["start_time_ms"] = None + task_state["end_time_ms"] = None + events = [] + + if "state_ts_ns" in state_updates: + state_ts_ns = state_updates["state_ts_ns"] + for state_name, state in TaskStatus.items(): + # state_ts_ns is Map[str, str] after protobuf MessageToDict + key = str(state) + if key in state_ts_ns: + # timestamp is recorded as nanosecond from the backend. + # We need to convert it to the second. + ts_ms = int(state_ts_ns[key]) // 1e6 + events.append( + { + "state": state_name, + "created_ms": ts_ms, + } + ) + if state == TaskStatus.PENDING_ARGS_AVAIL: + task_state["creation_time_ms"] = ts_ms + if state == TaskStatus.RUNNING: + task_state["start_time_ms"] = ts_ms + if state == TaskStatus.FINISHED or state == TaskStatus.FAILED: + task_state["end_time_ms"] = ts_ms + + task_state["events"] = events + if len(events) > 0: + latest_state = events[-1]["state"] + else: + latest_state = "NIL" + task_state["state"] = latest_state + + # Parse error info + if latest_state == "FAILED": + error_info = state_updates.get("error_info", None) + if error_info: + # We captured colored error message printed to console, e.g. + # "\x1b[31mTraceback (most recent call last):\x1b[0m", + # this is to remove the ANSI escape codes. + task_state["error_message"] = remove_ansi_escape_codes( + error_info.get("error_message", "") + ) + task_state["error_type"] = error_info.get("error_type", "") + + # Parse actor task name for actor with repr name. + if ( + state_updates.get("actor_repr_name") + and task_state["type"] == "ACTOR_TASK" + and task_state["name"] + == task_state["func_or_class_name"] # no name option provided. + ): + # If it's an actor task with no name override, and has repr name defined + # for the actor, we override the name. + method_name = task_state["name"].split(".")[-1] + actor_repr_task_name = f"{state_updates['actor_repr_name']}.{method_name}" + task_state["name"] = actor_repr_task_name + + return task_state + + +def remove_ansi_escape_codes(text: str) -> str: + """Remove ANSI escape codes from a string.""" + import re + + return re.sub(r"\x1b[^m]*m", "", text) + + +def dict_to_state(d: Dict, state_resource: StateResource) -> StateSchema: + + """Convert a dict to a state schema. + + Args: + d: a dict to convert. + state_resource: the state resource to convert to. + + Returns: + A state schema. + """ + try: + return resource_to_schema(state_resource)(**d) + + except Exception as e: + raise RayStateApiException(f"Failed to convert {d} to StateSchema: {e}") from e diff --git a/vllm/lib/python3.10/site-packages/ray/util/state/custom_types.py b/vllm/lib/python3.10/site-packages/ray/util/state/custom_types.py new file mode 100644 index 0000000000000000000000000000000000000000..01d20748b35e4bc91b884e282f3457f3194521ce --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/util/state/custom_types.py @@ -0,0 +1,135 @@ +from ray.core.generated.common_pb2 import ( + TaskStatus, + TaskType, + WorkerExitType, + WorkerType, + ErrorType, + Language, +) +from ray.core.generated.gcs_pb2 import ( + ActorTableData, + GcsNodeInfo, + PlacementGroupTableData, +) +from ray.dashboard.memory_utils import ReferenceType + +from typing import Literal + + +ACTOR_STATUS = [ + "DEPENDENCIES_UNREADY", + "PENDING_CREATION", + "ALIVE", + "RESTARTING", + "DEAD", +] +TypeActorStatus = Literal[tuple(ACTOR_STATUS)] +PLACEMENT_GROUP_STATUS = [ + "PENDING", + "PREPARED", + "CREATED", + "REMOVED", + "RESCHEDULING", +] +TypePlacementGroupStatus = Literal[tuple(PLACEMENT_GROUP_STATUS)] +TASK_STATUS = [ + "NIL", + "PENDING_ARGS_AVAIL", + "PENDING_NODE_ASSIGNMENT", + "PENDING_OBJ_STORE_MEM_AVAIL", + "PENDING_ARGS_FETCH", + "SUBMITTED_TO_WORKER", + "PENDING_ACTOR_TASK_ARGS_FETCH", + "PENDING_ACTOR_TASK_ORDERING_OR_CONCURRENCY", + "RUNNING", + "RUNNING_IN_RAY_GET", + "RUNNING_IN_RAY_WAIT", + "FINISHED", + "FAILED", +] +TypeTaskStatus = Literal[tuple(TASK_STATUS)] +NODE_STATUS = ["ALIVE", "DEAD"] +TypeNodeStatus = Literal[tuple(NODE_STATUS)] +WORKER_TYPE = [ + "WORKER", + "DRIVER", + "SPILL_WORKER", + "RESTORE_WORKER", +] +TypeWorkerType = Literal[tuple(WORKER_TYPE)] +WORKER_EXIT_TYPE = [ + "SYSTEM_ERROR", + "INTENDED_SYSTEM_EXIT", + "USER_ERROR", + "INTENDED_USER_EXIT", + "NODE_OUT_OF_MEMORY", +] +TypeWorkerExitType = Literal[tuple(WORKER_EXIT_TYPE)] +TASK_TYPE = [ + "NORMAL_TASK", + "ACTOR_CREATION_TASK", + "ACTOR_TASK", + "DRIVER_TASK", +] +TypeTaskType = Literal[tuple(TASK_TYPE)] +TypeReferenceType = Literal[ + tuple(reference_type.value for reference_type in ReferenceType) +] +# The ErrorType enum is used in the export API so it is public +# and any modifications must be backward compatible. +ERROR_TYPE = [ + "WORKER_DIED", + "ACTOR_DIED", + "OBJECT_UNRECONSTRUCTABLE", + "TASK_EXECUTION_EXCEPTION", + "OBJECT_IN_PLASMA", + "TASK_CANCELLED", + "ACTOR_CREATION_FAILED", + "RUNTIME_ENV_SETUP_FAILED", + "OBJECT_LOST", + "OWNER_DIED", + "OBJECT_DELETED", + "DEPENDENCY_RESOLUTION_FAILED", + "OBJECT_UNRECONSTRUCTABLE_MAX_ATTEMPTS_EXCEEDED", + "OBJECT_UNRECONSTRUCTABLE_LINEAGE_EVICTED", + "OBJECT_FETCH_TIMED_OUT", + "LOCAL_RAYLET_DIED", + "TASK_PLACEMENT_GROUP_REMOVED", + "ACTOR_PLACEMENT_GROUP_REMOVED", + "TASK_UNSCHEDULABLE_ERROR", + "ACTOR_UNSCHEDULABLE_ERROR", + "OUT_OF_DISK_ERROR", + "OBJECT_FREED", + "OUT_OF_MEMORY", + "NODE_DIED", + "END_OF_STREAMING_GENERATOR", + "ACTOR_UNAVAILABLE", +] +# The Language enum is used in the export API so it is public +# and any modifications must be backward compatible. +LANGUAGE = ["PYTHON", "JAVA", "CPP"] + + +def validate_protobuf_enum(grpc_enum, custom_enum): + """Validate the literal contains the correct enum values from protobuf""" + enum_vals = set(grpc_enum.DESCRIPTOR.values_by_name) + # Sometimes, the grpc enum is mocked, and it + # doesn't include any values in that case. + if len(enum_vals) > 0: + assert enum_vals == set(custom_enum) + + +# Do the enum validation here. +# It is necessary to avoid regression. Alternatively, we can auto generate this +# directly by protobuf. +validate_protobuf_enum(ActorTableData.ActorState, ACTOR_STATUS) +validate_protobuf_enum( + PlacementGroupTableData.PlacementGroupState, PLACEMENT_GROUP_STATUS +) +validate_protobuf_enum(TaskStatus, TASK_STATUS) +validate_protobuf_enum(GcsNodeInfo.GcsNodeState, NODE_STATUS) +validate_protobuf_enum(WorkerType, WORKER_TYPE) +validate_protobuf_enum(WorkerExitType, WORKER_EXIT_TYPE) +validate_protobuf_enum(TaskType, TASK_TYPE) +validate_protobuf_enum(ErrorType, ERROR_TYPE) +validate_protobuf_enum(Language, LANGUAGE) diff --git a/vllm/lib/python3.10/site-packages/ray/util/state/exception.py b/vllm/lib/python3.10/site-packages/ray/util/state/exception.py new file mode 100644 index 0000000000000000000000000000000000000000..8d8a180c2c3233d56f26c32383d7d3b470e8b20b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/util/state/exception.py @@ -0,0 +1,18 @@ +"""Internal Error""" + + +class DataSourceUnavailable(Exception): + pass + + +"""User-facing Error""" + + +class RayStateApiException(Exception): + pass + + +class ServerUnavailable(RayStateApiException): + """Thrown when failing to connect to dashboard server""" + + pass diff --git a/vllm/lib/python3.10/site-packages/ray/util/state/util.py b/vllm/lib/python3.10/site-packages/ray/util/state/util.py new file mode 100644 index 0000000000000000000000000000000000000000..16a5221e458f627deee32900f3666cf76c7bb8a2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/util/state/util.py @@ -0,0 +1,61 @@ +from typing import Optional, Union + + +def convert_string_to_type( + val: Optional[Union[str, int, float, bool]], convert_type: Union[int, float, bool] +) -> Union[int, float, bool]: + """Convert the given value to a convert type. + + If the given val is None, it will just return None without the conversion. + + It supports, + str -> int/float/bool + int -> int + bool -> bool + float -> float + """ + if val is None: + return None + elif type(val) is convert_type: + return val + elif convert_type is int: + try: + val = int(val) + except ValueError: + raise ValueError( + f"Failed to convert a value {val} of type {type(val)} to {convert_type}" + ) + elif convert_type is float: + try: + val = float(val) + except ValueError: + raise ValueError( + f"Failed to convert a value {val} of type {type(val)} to {convert_type}" + ) + elif convert_type is bool: + # Without this, "False" will become True. + if val == "False" or val == "false" or val == "0": + val = False + elif val == "True" or val == "true" or val == "1": + val = True + else: + raise ValueError( + f"Failed to convert a value {val} of type {type(val)} to {convert_type}" + ) + else: + assert False, f"Unsupported convert type {convert_type}" + return val + + +def record_deprecated_state_api_import(): + import warnings + from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag + + warnings.warn( + "Ray state API is no longer experimental. Please import from `ray.util.state`. " + "instead. Importing from `ray.experimental` will be deprecated in " + "future releases. ", + DeprecationWarning, + ) + + record_extra_usage_tag(TagKey.EXPERIMENTAL_STATE_API_IMPORT, "1")